diff --git "a/data/java/test.jsonl" "b/data/java/test.jsonl" deleted file mode 100644--- "a/data/java/test.jsonl" +++ /dev/null @@ -1,196 +0,0 @@ -{"contest_id":"1325","problem_id":"D","statement":"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\u2264u,v\u22641018)(0\u2264u,v\u22641018).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\nOutputCopy2\n3 1InputCopy1 3\nOutputCopy3\n1 1 1InputCopy8 5\nOutputCopy-1InputCopy0 0\nOutputCopy0NoteIn the first sample; 3\u22951=23\u22951=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.","tags":["bitmasks","constructive algorithms","greedy","number theory"],"code":"import java.io.*;\nimport java.util.*;\n\npublic class CodeForces {\n\n \/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*\/\n public static void solve(int tCase) throws IOException {\n long u = sc.nextLong();\n long v = sc.nextLong();\n if(u>v || (v-u) % 2==1){\n out.println(-1);\n return;\n }\n if(u==0){\n if(v==0)out.println(0);\n else {\n out.println(2);\n out.println(v \/ 2 + \" \" + v \/ 2);\n }\n return;\n }\n List ans = new ArrayList<>();\n ans.add(u);\n v-=u;\n int bit = _digitCount(v,2)-1;\n long vv = v;\n while (v>0 && bit >=0){\n long curr = (1L<>bit) & 1) ==0))ans.set(i,ans.get(i)+(1L< 3){\n out.println(3);\n out.println(u+\" \"+vv\/2+\" \"+vv\/2);\n return;\n }\n if(v!=0)throw new IOException(\"V is not zero\");\n long xor = 0;\n for(long x : ans) xor ^=x;\n if(xor!=u)throw new IOException(\"Xor is not valid\");\n out.println(ans.size());\n for(long x : ans)out.println(x);\n }\n\n public static void main(String[] args) throws IOException {\n openIO();\n int testCase = 1;\n\/\/ testCase = sc. nextInt();\n for (int i = 1; i <= testCase; i++) solve(i);\n closeIO();\n }\n\n \/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*\/\n \/*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*\/\n\n public static int mod = (int) 1e9 + 7;\n \/\/ public static int mod = 998244353;\n public static int inf_int = (int) 2e9;\n public static long inf_long = (long) 2e18;\n\n public static void _sort(int[] arr, boolean isAscending) {\n int n = arr.length;\n List list = new ArrayList<>();\n for (int ele : arr) list.add(ele);\n Collections.sort(list);\n if (!isAscending) Collections.reverse(list);\n for (int i = 0; i < n; i++) arr[i] = list.get(i);\n }\n\n public static void _sort(long[] arr, boolean isAscending) {\n int n = arr.length;\n List list = new ArrayList<>();\n for (long ele : arr) list.add(ele);\n Collections.sort(list);\n if (!isAscending) Collections.reverse(list);\n for (int i = 0; i < n; i++) arr[i] = list.get(i);\n }\n\n \/\/ time : O(1), space : O(1)\n public static int _digitCount(long num,int base){\n \/\/ this will give the # of digits needed for a number num in format : base\n return (int)(1 + Math.log(num)\/Math.log(base));\n }\n\n \/\/ time : O(n), space: O(n)\n public static long _fact(int n){\n \/\/ simple factorial calculator\n long ans = 1;\n for(int i=2;i<=n;i++)\n ans = ans * i % mod;\n return ans;\n }\n\n \/\/ time for pre-computation of factorial and inverse-factorial table : O(nlog(mod))\n public static long[] factorial , inverseFact;\n public static void _ncr_precompute(int n){\n factorial = new long[n+1];\n inverseFact = new long[n+1];\n factorial[0] = inverseFact[0] = 1;\n for (int i = 1; i <=n; i++) {\n factorial[i] = (factorial[i - 1] * i) % mod;\n inverseFact[i] = _modExpo(factorial[i], mod - 2);\n }\n }\n \/\/ time of factorial calculation after pre-computation is O(1)\n public static int _ncr(int n,int r){\n if(r > n)return 0;\n return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod);\n }\n public static int _npr(int n,int r){\n if(r > n)return 0;\n return (int)(factorial[n] * inverseFact[n - r] % mod);\n }\n\n\n \/\/ euclidean algorithm time O(max (loga ,logb))\n public static long _gcd(long a, long b) {\n while (a>0){\n long x = a;\n a = b % a;\n b = x;\n }\n return b;\n\/\/ if (a == 0)\n\/\/ return b;\n\/\/ return _gcd(b % a, a);\n }\n\n \/\/ lcm(a,b) * gcd(a,b) = a * b\n public static long _lcm(long a, long b) {\n return (a \/ _gcd(a, b)) * b;\n }\n\n \/\/ binary exponentiation time O(logn)\n public static long _modExpo(long x, long n) {\n long ans = 1;\n while (n > 0) {\n if ((n & 1) == 1) {\n ans *= x;\n ans %= mod;\n n--;\n } else {\n x *= x;\n x %= mod;\n n >>= 1;\n }\n }\n return ans;\n }\n \/\/ function to find a\/b under modulo mod. time : O(logn)\n public static long _modInv(long a,long b){\n return (a * _modExpo(b,mod-2)) % mod;\n }\n\n \/\/sieve or first divisor time : O(mx * log ( log (mx) ) )\n public static int[] _seive(int mx){\n int[] firstDivisor = new int[mx+1];\n for(int i=0;i<=mx;i++)firstDivisor[i] = i;\n for(int i=2;i*i<=mx;i++)\n if(firstDivisor[i] == i)\n for(int j = i*i;j<=mx;j+=i)\n firstDivisor[j] = i;\n return firstDivisor;\n }\n\n \/\/ check if x is a prime # of not. time : O( n ^ 1\/2 )\n private static boolean _isPrime(long x){\n for(long i=2;i*i<=x;i++)\n if(x%i==0)return false;\n return true;\n }\n\n static class Pair{\n K ff;\n V ss;\n\n public Pair(K ff, V ss) {\n this.ff = ff;\n this.ss = ss;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || this.getClass() != o.getClass()) return false;\n Pair pair = (Pair) o;\n return ff.equals(pair.ff) && ss.equals(pair.ss);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(ff, ss);\n }\n @Override\n public String toString(){\n return ff.toString()+\" \"+ss.toString();\n }\n }\n\n \/*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*\/\n \/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*\/\n static FastestReader sc;\n static PrintWriter out;\n\n private static void openIO() throws IOException {\n sc = new FastestReader();\n out = new PrintWriter(System.out);\n }\n\n public static void closeIO() throws IOException {\n out.flush();\n out.close();\n sc.close();\n }\n\n private static final class FastestReader {\n private static final int BUFFER_SIZE = 1 << 16;\n private final DataInputStream din;\n private final byte[] buffer;\n private int bufferPointer, bytesRead;\n\n public FastestReader() {\n din = new DataInputStream(System.in);\n buffer = new byte[BUFFER_SIZE];\n bufferPointer = bytesRead = 0;\n }\n\n public FastestReader(String file_name) throws IOException {\n din = new DataInputStream(new FileInputStream(file_name));\n buffer = new byte[BUFFER_SIZE];\n bufferPointer = bytesRead = 0;\n }\n\n private static boolean isSpaceChar(int c) {\n return !(c >= 33 && c <= 126);\n }\n\n private int skip() throws IOException {\n int b;\n \/\/noinspection StatementWithEmptyBody\n while ((b = read()) != -1 && isSpaceChar(b)) {\n }\n return b;\n }\n\n public String next() throws IOException {\n int b = skip();\n final StringBuilder sb = new StringBuilder();\n while (!isSpaceChar(b)) { \/\/ when nextLine, (isSpaceChar(b) && b != ' ')\n sb.appendCodePoint(b);\n b = read();\n }\n return sb.toString();\n }\n\n public int nextInt() throws IOException {\n int ret = 0;\n byte c = read();\n while (c <= ' ') {\n c = read();\n }\n final boolean neg = c == '-';\n if (neg) {\n c = read();\n }\n do {\n ret = ret * 10 + c - '0';\n } while ((c = read()) >= '0' && c <= '9');\n\n if (neg) {\n return -ret;\n }\n return ret;\n }\n\n public long nextLong() throws IOException {\n long ret = 0;\n byte c = read();\n while (c <= ' ') {\n c = read();\n }\n final boolean neg = c == '-';\n if (neg) {\n c = read();\n }\n do {\n ret = ret * 10 + c - '0';\n } while ((c = read()) >= '0' && c <= '9');\n if (neg) {\n return -ret;\n }\n return ret;\n }\n\n public double nextDouble() throws IOException {\n double ret = 0, div = 1;\n byte c = read();\n while (c <= ' ') {\n c = read();\n }\n final boolean neg = c == '-';\n if (neg) {\n c = read();\n }\n\n do {\n ret = ret * 10 + c - '0';\n } while ((c = read()) >= '0' && c <= '9');\n\n if (c == '.') {\n while ((c = read()) >= '0' && c <= '9') {\n ret += (c - '0') \/ (div *= 10);\n }\n }\n\n if (neg) {\n return -ret;\n }\n return ret;\n }\n\n private void fillBuffer() throws IOException {\n bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);\n if (bytesRead == -1) {\n buffer[0] = -1;\n }\n }\n\n private byte read() throws IOException {\n if (bufferPointer == bytesRead) {\n fillBuffer();\n }\n return buffer[bufferPointer++];\n }\n\n public void close() throws IOException {\n din.close();\n }\n }\n \/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*\/\n}","language":"java"} -{"contest_id":"1303","problem_id":"D","statement":"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\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.The first line of each test case contains two integers nn and mm (1\u2264n\u22641018,1\u2264m\u22641051\u2264n\u22641018,1\u2264m\u2264105) \u2014 the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,\u2026,ama1,a2,\u2026,am (1\u2264ai\u22641091\u2264ai\u2264109) \u2014 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 \u2014 the minimum number of divisions required to fill the bag of size nn (or \u22121\u22121, if it is impossible).ExampleInputCopy3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8\nOutputCopy2\n-1\n0\n","tags":["bitmasks","greedy"],"code":"import java.util.*;\n\nimport java.io.*;\n\npublic class Main {\n\n static class Scan {\n\n private byte[] buf=new byte[1024];\n\n private int index;\n\n private InputStream in;\n\n private int total;\n\n public Scan()\n\n {\n\n in=System.in;\n\n }\n\n public int scan()throws IOException\n\n {\n\n if(total<0)\n\n throw new InputMismatchException();\n\n if(index>=total)\n\n {\n\n index=0;\n\n total=in.read(buf);\n\n if(total<=0)\n\n return -1;\n\n }\n\n return buf[index++];\n\n }\n\n public int scanInt()throws IOException\n\n {\n\n int integer=0;\n\n int n=scan();\n\n while(isWhiteSpace(n))\n\n n=scan();\n\n int neg=1;\n\n if(n=='-')\n\n {\n\n neg=-1;\n\n n=scan();\n\n }\n\n while(!isWhiteSpace(n))\n\n {\n\n if(n>='0'&&n<='9')\n\n {\n\n integer*=10;\n\n integer+=n-'0';\n\n n=scan();\n\n }\n\n else throw new InputMismatchException();\n\n }\n\n return neg*integer;\n\n }\n\n public double scanDouble()throws IOException\n\n {\n\n double doub=0;\n\n int n=scan();\n\n while(isWhiteSpace(n))\n\n n=scan();\n\n int neg=1;\n\n if(n=='-')\n\n {\n\n neg=-1;\n\n n=scan();\n\n }\n\n while(!isWhiteSpace(n)&&n!='.')\n\n {\n\n if(n>='0'&&n<='9')\n\n {\n\n doub*=10;\n\n doub+=n-'0';\n\n n=scan();\n\n }\n\n else throw new InputMismatchException();\n\n }\n\n if(n=='.')\n\n {\n\n n=scan();\n\n double temp=1;\n\n while(!isWhiteSpace(n))\n\n {\n\n if(n>='0'&&n<='9')\n\n {\n\n temp\/=10;\n\n doub+=(n-'0')*temp;\n\n n=scan();\n\n }\n\n else throw new InputMismatchException();\n\n }\n\n }\n\n return doub*neg;\n\n }\n\n public String scanString()throws IOException\n\n {\n\n StringBuilder sb=new StringBuilder();\n\n int n=scan();\n\n while(isWhiteSpace(n))\n\n n=scan();\n\n while(!isWhiteSpace(n))\n\n {\n\n sb.append((char)n);\n\n n=scan();\n\n }\n\n return sb.toString();\n\n }\n\n private boolean isWhiteSpace(int n)\n\n {\n\n if(n==' '||n=='\\n'||n=='\\r'||n=='\\t'||n==-1)\n\n return true;\n\n return false;\n\n }\n\n }\n\n static long n,pow[];\n\n static int m,arr[];\n\n static HashMap map;\n\n public static void main(String args[]) throws IOException {\n\n Scanner input=new Scanner(System.in);\n\n int test=input.nextInt();\n\n pow=new long[32];\n\n pow[0]=1;\n\n map=new HashMap<>();\n\n map.put(1L, 0);\n\n for(int i=1;i0) {\n\n arr[0]--;\n\n n--;\n\n }\n\n else {\n\n for(int i=1;i0) {\n\n arr[i]--;\n\n long tmp=pow[i];\n\n while(tmp!=1) {\n\n\/\/ System.out.println(tmp);\n\n tmp\/=2;\n\n arr[map.get(tmp)]++;\n\n ans++;\n\n }\n\n arr[0]--;\n\n n--;\n\n break;\n\n }\n\n }\n\n } \n\n }\n\n\/\/ System.out.println(\"III\");\n\n arr[1]+=arr[0]\/2;\n\n arr[0]=0;\n\n for(int i=0;i<=62;i++) {\n\n\/\/ System.out.println(\"i \"+i);\n\n if((n&(long)Math.pow(2, i))!=0) {\n\n int tmp=check((long)Math.pow(2, i));\n\n if(tmp==-1) {\n\n return -1;\n\n }\n\n ans+=tmp;\n\n }\n\n }\n\n return ans;\n\n }\n\n public static int check(long tmp) {\n\n long tmp1=tmp;\n\n int tmp_arr[]=new int[arr.length];\n\n for(int i=0;i0;i--) {\n\n while(tmp_arr[i]>0 && pow[i]<=tmp1) {\n\n tmp1-=pow[i];\n\n tmp_arr[i]--;\n\n }\n\n }\n\n if(tmp1==0) {\n\n arr=tmp_arr;\n\n return 0;\n\n }\n\n for(int i=1;i0 && pow[i]>=tmp) {\n\n arr[i]--;\n\n tmp1=pow[i];\n\n int cnt=0;\n\n while(tmp1!=tmp) {\n\n tmp1\/=2;\n\n arr[map.get(tmp1)]++;\n\n cnt++;\n\n }\n\n return cnt;\n\n }\n\n }\n\n return -1;\n\n }\n\n}\n\n","language":"java"} -{"contest_id":"1296","problem_id":"E1","statement":"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\u2264n\u22642001\u2264n\u2264200) \u2014 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\nabacbecfd\nOutputCopyYES\n001010101\nInputCopy8\naaabbcbb\nOutputCopyYES\n01011011\nInputCopy7\nabcdedc\nOutputCopyNO\nInputCopy5\nabcde\nOutputCopyYES\n00000\n","tags":["constructive algorithms","dp","graphs","greedy","sortings"],"code":"import java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.io.BufferedWriter;\nimport java.io.Writer;\nimport java.io.OutputStreamWriter;\nimport java.util.InputMismatchException;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n\/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n *\/\npublic class Main {\n public static void main(String[] args) {\n InputStream inputStream = System.in;\n OutputStream outputStream = System.out;\n InputReader in = new InputReader(inputStream);\n OutputWriter out = new OutputWriter(outputStream);\n E1StringColoringEasyVersion solver = new E1StringColoringEasyVersion();\n solver.solve(1, in, out);\n out.close();\n }\n\n static class E1StringColoringEasyVersion {\n public void solve(int testNumber, InputReader in, OutputWriter out) {\n int n = in.nextInt();\n String s = in.nextString();\n char[] chars = s.toCharArray();\n int[] a = new int[n];\n char last1 = 'a' - 1;\n char last2 = 'a' - 1;\n for (int i = 0; i < n; i++) {\n if (chars[i] >= last1) {\n last1 = chars[i];\n } else {\n if (chars[i] >= last2) {\n last2 = chars[i];\n a[i] = 1;\n } else {\n out.println(\"NO\");\n return;\n }\n }\n }\n out.println(\"YES\");\n for (int i = 0; i < n; i++) {\n out.print(a[i]);\n }\n out.println();\n\n\n }\n\n }\n\n static class InputReader {\n private InputStream stream;\n private byte[] buf = new byte[1024];\n private int curChar;\n private int numChars;\n private InputReader.SpaceCharFilter filter;\n\n public InputReader(InputStream stream) {\n this.stream = stream;\n }\n\n public int read() {\n if (numChars == -1) {\n throw new InputMismatchException();\n }\n if (curChar >= numChars) {\n curChar = 0;\n try {\n numChars = stream.read(buf);\n } catch (IOException e) {\n throw new InputMismatchException();\n }\n if (numChars <= 0) {\n return -1;\n }\n }\n return buf[curChar++];\n }\n\n public int nextInt() {\n int c = read();\n while (isSpaceChar(c)) {\n c = read();\n }\n int sgn = 1;\n if (c == '-') {\n sgn = -1;\n c = read();\n }\n int res = 0;\n do {\n if (c < '0' || c > '9') {\n throw new InputMismatchException();\n }\n res *= 10;\n res += c - '0';\n c = read();\n } while (!isSpaceChar(c));\n return res * sgn;\n }\n\n public String nextString() {\n int c = read();\n while (isSpaceChar(c)) {\n c = read();\n }\n StringBuilder res = new StringBuilder();\n do {\n if (Character.isValidCodePoint(c)) {\n res.appendCodePoint(c);\n }\n c = read();\n } while (!isSpaceChar(c));\n return res.toString();\n }\n\n public boolean isSpaceChar(int c) {\n if (filter != null) {\n return filter.isSpaceChar(c);\n }\n return isWhitespace(c);\n }\n\n public static boolean isWhitespace(int c) {\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n }\n\n public interface SpaceCharFilter {\n public boolean isSpaceChar(int ch);\n\n }\n\n }\n\n static class OutputWriter {\n private final PrintWriter writer;\n\n public OutputWriter(OutputStream outputStream) {\n writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n }\n\n public OutputWriter(Writer writer) {\n this.writer = new PrintWriter(writer);\n }\n\n public void print(Object... objects) {\n for (int i = 0; i < objects.length; i++) {\n if (i != 0) {\n writer.print(' ');\n }\n writer.print(objects[i]);\n }\n }\n\n public void println() {\n writer.println();\n }\n\n public void println(Object... objects) {\n print(objects);\n writer.println();\n }\n\n public void close() {\n writer.close();\n }\n\n public void print(int i) {\n writer.print(i);\n }\n\n }\n}\n\n","language":"java"} -{"contest_id":"1305","problem_id":"F","statement":"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\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u00a0\u2014 the number of elements in the array.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an. (1\u2264ai\u226410121\u2264ai\u22641012) \u00a0\u2014 the elements of the array.OutputPrint a single integer \u00a0\u2014 the minimum number of operations required to make the array good.ExamplesInputCopy3\n6 2 4\nOutputCopy0\nInputCopy5\n9 8 7 3 1\nOutputCopy4\nNoteIn 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.","tags":["math","number theory","probabilities"],"code":"import java.io.BufferedOutputStream;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.io.Reader;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.StringTokenizer;\nimport java.util.stream.Collectors;\n\npublic class C1305F {\n public static void main(String[] args) {\n var scanner = new BufferedScanner();\n var writer = new PrintWriter(new BufferedOutputStream(System.out));\n\n var n = scanner.nextInt();\n var a = new long[n];\n for (int i = 0; i < a.length; i++) {\n a[i] = scanner.nextLong();\n }\n \/\/ TODO 2020\/3\/20: \u4e3a\u4ec0\u4e48distinct\u4e86\u53cd\u800c\u8fc7\u4e0d\u4e86\uff1f\n var distinct = Arrays.stream(a)\/*.distinct()*\/.boxed().collect(Collectors.toList());\n Collections.shuffle(distinct);\n\/\/ var distinct = Arrays.stream(a).distinct().toArray();\n var factors = new HashSet();\n for (int guess = 0; guess < 40 && guess < distinct.size(); guess++) {\n for (int j = -1; j <= 1; j++) {\n factors.addAll(factor(distinct.get(guess) + j));\n }\n }\n\/\/ for (int guess = 0; guess < 20; guess++) {\n\/\/ var i = (int) (Math.random() * distinct.length);\n\/\/ for (int j = -1; j <= 1; j++) {\n\/\/ factors.addAll(factor(distinct[i] + j));\n\/\/ }\n\/\/ }\n var ans = countOps(2, a, n);\n factors.remove(2L);\n for (var factor : factors) {\n var ops = countOps(factor, a, ans);\n ans = Math.min(ans, ops);\n }\n writer.println(ans);\n\n scanner.close();\n writer.flush();\n writer.close();\n }\n\n private static long countOps(long factor, long[] a, long already) {\n var ans = 0L;\n for (var x : a) {\n if (x < factor) {\n ans += factor - x;\n } else {\n var remain = x % factor;\n ans += Math.min(remain, factor - remain);\n\/\/ if (remain < factor \/ 2) {\n\/\/ ans += remain;\n\/\/ } else {\n\/\/ ans += factor - remain;\n\/\/ }\n }\n if (ans >= already) {\n break;\n }\n }\n return ans;\n }\n\n private static List factor(long a) {\n if (a <= 1) {\n return List.of();\n }\n var limit = (long) Math.sqrt(a);\n var ans = new ArrayList();\n for (long i = 2; i <= limit; i++) {\n var count = 0;\n while (a % i == 0) {\n a \/= i;\n count++;\n }\n if (count > 0) {\n ans.add(i);\n }\n }\n if (a > 1) {\n ans.add(a);\n }\n return ans;\n }\n\n public static class BufferedScanner {\n BufferedReader br;\n StringTokenizer st;\n\n public BufferedScanner(Reader reader) {\n br = new BufferedReader(reader);\n }\n\n public BufferedScanner() {\n this(new InputStreamReader(System.in));\n }\n\n String next() {\n while (st == null || !st.hasMoreElements()) {\n try {\n st = new StringTokenizer(br.readLine());\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return st.nextToken();\n }\n\n int nextInt() {\n return Integer.parseInt(next());\n }\n\n long nextLong() {\n return Long.parseLong(next());\n }\n\n double nextDouble() {\n return Double.parseDouble(next());\n }\n\n String nextLine() {\n String str = \"\";\n try {\n str = br.readLine();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return str;\n }\n\n void close() {\n try {\n br.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n }\n\n static long gcd(long a, long b) {\n if (a < b) {\n return gcd(b, a);\n }\n while (b > 0) {\n long tmp = b;\n b = a % b;\n a = tmp;\n }\n return a;\n }\n\n static long inverse(long a, long m) {\n long[] ans = extgcd(a, m);\n return ans[0] == 1 ? (ans[1] + m) % m : -1;\n }\n\n private static long[] extgcd(long a, long m) {\n if (m == 0) {\n return new long[]{a, 1, 0};\n } else {\n long[] ans = extgcd(m, a % m);\n long tmp = ans[1];\n ans[1] = ans[2];\n ans[2] = tmp;\n ans[2] -= ans[1] * (a \/ m);\n return ans;\n }\n }\n\n private static List primes(double upperBound) {\n var limit = (int) Math.sqrt(upperBound);\n var isComposite = new boolean[limit + 1];\n var primes = new ArrayList();\n for (int i = 2; i <= limit; i++) {\n if (isComposite[i]) {\n continue;\n }\n primes.add(i);\n int j = i + i;\n while (j <= limit) {\n isComposite[j] = true;\n j += i;\n }\n }\n return primes;\n }\n\n\n}\n","language":"java"} -{"contest_id":"1304","problem_id":"D","statement":"D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlog\u2061n) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n\u22121n\u22121, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1\u2264t\u22641041\u2264t\u2264104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n\u22121n\u22121.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2\u22c51052\u22c5105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3\n3 <<\n7 >><>><\n5 >>><\nOutputCopy1 2 3\n1 2 3\n5 4 3 7 2 1 6\n4 3 1 7 5 2 6\n4 3 2 1 5\n5 4 2 1 3\nNoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.","tags":["constructive algorithms","graphs","greedy","two pointers"],"code":"\n\nimport java.io.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.io.PrintWriter;\n\nimport java.util.Scanner;\n\nimport java.util.StringTokenizer;\n\n\n\npublic class Main {\n\n public static void main(String[] args) {\n\n InputReader s = new InputReader();\n\n PrintWriter w = new PrintWriter(System.out);\n\n int T = s.nextInt();\n\n while(T-->0){\n\n int n = s.nextInt();\n\n char[] c = s.next().toCharArray();\n\n int[] ans = new int[n];\n\n int num = n, last = 0;\n\n for (int i = 0; i < n; i++)\n\n {\n\n if (i == n - 1 || c[i] == '>')\n\n {\n\n for (int j = i; j >= last; j--)\n\n ans[j] = num--;\n\n last = i + 1;\n\n }\n\n }\n\n for (int i = 0; i < n; i++) w.write(ans[i]+\" \");\n\n w.println();\n\n num = 1;\n\n last = 0;\n\n for (int i = 0; i < n; i++)\n\n {\n\n if (i == n - 1 || c[i] == '<')\n\n {\n\n for (int j = i; j >= last; j--)\n\n ans[j] = num++;\n\n last = i + 1;\n\n }\n\n }\n\n for (int i = 0; i < n; i++) w.write(ans[i]+\" \");\n\n w.println();\n\n }\n\n w.flush();\n\n }\n\n}\n\nclass InputReader {\n\n public BufferedReader reader;\n\n public StringTokenizer tokenizer;\n\n\n\n\n\n public InputReader() {\n\n reader = new BufferedReader(new InputStreamReader(System.in), 32768);\n\n tokenizer = null;\n\n }\n\n\n\n public String next() {\n\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n\n try {\n\n tokenizer = new StringTokenizer(reader.readLine());\n\n } catch (IOException e) {\n\n throw new RuntimeException(e);\n\n }\n\n }\n\n return tokenizer.nextToken();\n\n }\n\n\n\n public int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n public double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n public long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n}","language":"java"} -{"contest_id":"1288","problem_id":"B","statement":"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\u2264a\u2264A1\u2264a\u2264A, 1\u2264b\u2264B1\u2264b\u2264B, and the equation a\u22c5b+a+b=conc(a,b)a\u22c5b+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\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.Each test case contains two integers AA and BB (1\u2264A,B\u2264109)(1\u2264A,B\u2264109).OutputPrint one integer \u2014 the number of pairs (a,b)(a,b) such that 1\u2264a\u2264A1\u2264a\u2264A, 1\u2264b\u2264B1\u2264b\u2264B, and the equation a\u22c5b+a+b=conc(a,b)a\u22c5b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1\n0\n1337\nNoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1\u22c59=191+9+1\u22c59=19).","tags":["math"],"code":"import java.io.BufferedReader;\n\nimport java.io.InputStreamReader;\n\nimport java.io.PrintWriter;\n\nimport java.util.StringTokenizer;\n\n\n\npublic class YetAnotherMemeProblem {\n\n public static void main(String[] args) throws Exception {\n\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n PrintWriter pw = new PrintWriter(System.out);\n\n int t = Integer.parseInt(br.readLine());\n\n for (int i= 0; i < t; i++) {\n\n StringTokenizer st = new StringTokenizer(br.readLine());\n\n\n\n int a = Integer.parseInt(st.nextToken());\n\n int b = Integer.parseInt(st.nextToken());\n\n\n\n String bS = Integer.toString(b);\n\n long nines = bS.length() - 1;\n\n int count = 0;\n\n for (int j = 0; j < bS.length(); j++) {\n\n if (bS.charAt(j) == '9') count++;\n\n }\n\n if (count == bS.length()) nines++;\n\n pw.println(a * nines);\n\n }\n\n\n\n pw.close();\n\n }\n\n}","language":"java"} -{"contest_id":"1284","problem_id":"E","statement":"E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),\u2026,(xn,yn)}s={(x1,y1),(x2,y2),\u2026,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p\u2208sp\u2208s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p\u2208sp\u2208s.InputThe first line contains a single integer nn (5\u2264n\u226425005\u2264n\u22642500).In the next nn lines, two integers xixi and yiyi (\u2212109\u2264xi,yi\u2264109\u2212109\u2264xi,yi\u2264109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p\u2208sp\u2208s.ExamplesInputCopy5\n-1 0\n1 0\n-10 -1\n10 -1\n0 3\nOutputCopy2InputCopy8\n0 1\n1 2\n2 2\n1 3\n0 -1\n-1 -2\n-2 -2\n-1 -3\nOutputCopy40InputCopy10\n588634631 265299215\n-257682751 342279997\n527377039 82412729\n145077145 702473706\n276067232 912883502\n822614418 -514698233\n280281434 -41461635\n65985059 -827653144\n188538640 592896147\n-857422304 -529223472\nOutputCopy213","tags":["combinatorics","geometry","math","sortings"],"code":"import java.io.OutputStream;\n\nimport java.io.IOException;\n\nimport java.io.InputStream;\n\nimport java.io.OutputStream;\n\nimport java.util.Arrays;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.io.BufferedOutputStream;\n\nimport java.io.UncheckedIOException;\n\nimport java.util.Objects;\n\nimport java.nio.charset.Charset;\n\nimport java.util.StringTokenizer;\n\nimport java.io.Writer;\n\nimport java.io.OutputStreamWriter;\n\nimport java.io.BufferedReader;\n\nimport java.io.InputStream;\n\n\n\n\/**\n\n * Built using CHelper plug-in\n\n * Actual solution is at the top\n\n *\n\n * @author mikit\n\n *\/\n\npublic class Main {\n\n public static void main(String[] args) {\n\n InputStream inputStream = System.in;\n\n OutputStream outputStream = System.out;\n\n LightScanner in = new LightScanner(inputStream);\n\n LightWriter out = new LightWriter(outputStream);\n\n ENewYearAndCastleConstruction solver = new ENewYearAndCastleConstruction();\n\n solver.solve(1, in, out);\n\n out.close();\n\n }\n\n\n\n static class ENewYearAndCastleConstruction {\n\n public void solve(int testNumber, LightScanner in, LightWriter out) {\n\n int n = in.ints();\n\n Vec2l[] points = new Vec2l[n];\n\n for (int i = 0; i < n; i++) points[i] = new Vec2l(in.longs(), in.longs());\n\n long ans = n * (n - 1L) * (n - 2L) * (n - 3L) * (n - 4L) \/ 24;\n\n\n\n for (int t = 0; t < n; t++) {\n\n int m = 0;\n\n Vec2l[] angles = new Vec2l[n - 1];\n\n {\n\n Vec2l now = points[t];\n\n for (int i = 0; i < n; i++) {\n\n if (i != t) {\n\n angles[m] = new Vec2l(points[i].x - now.x, points[i].y - now.y);\n\n m++;\n\n }\n\n }\n\n Arrays.sort(angles, Vec2l::compareToByAngle);\n\n }\n\n \/\/System.out.println(Arrays.stream(angles).map(angle -> Double.toString(Math.atan2(angle.y, angle.x))).collect(Collectors.joining(\", \")));\n\n\n\n int hi = 0;\n\n for (int j = 0; j < m; j++) {\n\n while (hi < j + m && (hi <= j || angles[j].det(angles[hi % m]) > 0)) {\n\n hi++;\n\n }\n\n int cnt = hi - j;\n\n ans -= (cnt - 1L) * (cnt - 2L) * (cnt - 3L) \/ 6;\n\n }\n\n }\n\n out.ans(ans).ln();\n\n }\n\n\n\n }\n\n\n\n static class Vec2l implements Comparable {\n\n public long x;\n\n public long y;\n\n\n\n public Vec2l(long x, long y) {\n\n this.x = x;\n\n this.y = y;\n\n }\n\n\n\n public long det(Vec2l other) {\n\n return x * other.y - other.x * y;\n\n }\n\n\n\n public boolean equals(Object o) {\n\n if (this == o) return true;\n\n if (o == null || getClass() != o.getClass()) return false;\n\n Vec2l vec2i = (Vec2l) o;\n\n return x == vec2i.x &&\n\n y == vec2i.y;\n\n }\n\n\n\n public int hashCode() {\n\n return Objects.hash(x, y);\n\n }\n\n\n\n public String toString() {\n\n return \"(\" + x + \", \" + y + \")\";\n\n }\n\n\n\n public int compareTo(Vec2l o) {\n\n if (x == o.x) {\n\n return Long.compare(y, o.y);\n\n }\n\n return Long.compare(x, o.x);\n\n }\n\n\n\n public int compareToByAngle(Vec2l o) {\n\n if ((y >= 0) != (o.y >= 0)) {\n\n return y >= 0 ? 1 : -1;\n\n } else {\n\n return Long.signum(o.x * y - x * o.y);\n\n }\n\n }\n\n\n\n }\n\n\n\n static class LightWriter implements AutoCloseable {\n\n private final Writer out;\n\n private boolean autoflush = false;\n\n private boolean breaked = true;\n\n\n\n public LightWriter(Writer out) {\n\n this.out = out;\n\n }\n\n\n\n public LightWriter(OutputStream out) {\n\n this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset()));\n\n }\n\n\n\n public LightWriter print(char c) {\n\n try {\n\n out.write(c);\n\n breaked = false;\n\n } catch (IOException ex) {\n\n throw new UncheckedIOException(ex);\n\n }\n\n return this;\n\n }\n\n\n\n public LightWriter print(String s) {\n\n try {\n\n out.write(s, 0, s.length());\n\n breaked = false;\n\n } catch (IOException ex) {\n\n throw new UncheckedIOException(ex);\n\n }\n\n return this;\n\n }\n\n\n\n public LightWriter ans(String s) {\n\n if (!breaked) {\n\n print(' ');\n\n }\n\n return print(s);\n\n }\n\n\n\n public LightWriter ans(long l) {\n\n return ans(Long.toString(l));\n\n }\n\n\n\n public LightWriter ln() {\n\n print(System.lineSeparator());\n\n breaked = true;\n\n if (autoflush) {\n\n try {\n\n out.flush();\n\n } catch (IOException ex) {\n\n throw new UncheckedIOException(ex);\n\n }\n\n }\n\n return this;\n\n }\n\n\n\n public void close() {\n\n try {\n\n out.close();\n\n } catch (IOException ex) {\n\n throw new UncheckedIOException(ex);\n\n }\n\n }\n\n\n\n }\n\n\n\n static class LightScanner {\n\n private BufferedReader reader = null;\n\n private StringTokenizer tokenizer = null;\n\n\n\n public LightScanner(InputStream in) {\n\n reader = new BufferedReader(new InputStreamReader(in));\n\n }\n\n\n\n public String string() {\n\n if (tokenizer == null || !tokenizer.hasMoreTokens()) {\n\n try {\n\n tokenizer = new StringTokenizer(reader.readLine());\n\n } catch (IOException e) {\n\n throw new UncheckedIOException(e);\n\n }\n\n }\n\n return tokenizer.nextToken();\n\n }\n\n\n\n public int ints() {\n\n return Integer.parseInt(string());\n\n }\n\n\n\n public long longs() {\n\n return Long.parseLong(string());\n\n }\n\n\n\n }\n\n}\n\n\n\n","language":"java"} -{"contest_id":"1325","problem_id":"D","statement":"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\u2264u,v\u22641018)(0\u2264u,v\u22641018).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\nOutputCopy2\n3 1InputCopy1 3\nOutputCopy3\n1 1 1InputCopy8 5\nOutputCopy-1InputCopy0 0\nOutputCopy0NoteIn the first sample; 3\u22951=23\u22951=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.","tags":["bitmasks","constructive algorithms","greedy","number theory"],"code":"import java.util.*;\n\n\n\n\n\npublic class D_Ehab_the_Xorcist{\n\n public static void main(String[] args) {\n\n Scanner sc = new Scanner(System.in);\n\n long u = sc.nextLong();\n\n long v = sc.nextLong();\n\n if(u>v){\n\n System.out.println(-1);\n\n }else if(u==v){\n\n if(u==0){\n\n System.out.println(0);\n\n }else{\n\n System.out.println(1);\n\n System.out.println(u);\n\n }\n\n }else{\n\n long diff = v-u;\n\n if(diff%2==0){\n\n long d2 = diff\/2;\n\n if((d2^u)==(d2+u)){\n\n System.out.println(2);\n\n System.out.println((d2+u)+\" \"+d2);\n\n }else{\n\n System.out.println(3);\n\n System.out.println(u + \" \"+d2+\" \"+d2);\n\n }\n\n }else{\n\n System.out.println(-1);\n\n }\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1296","problem_id":"E1","statement":"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\u2264n\u22642001\u2264n\u2264200) \u2014 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\nabacbecfd\nOutputCopyYES\n001010101\nInputCopy8\naaabbcbb\nOutputCopyYES\n01011011\nInputCopy7\nabcdedc\nOutputCopyNO\nInputCopy5\nabcde\nOutputCopyYES\n00000\n","tags":["constructive algorithms","dp","graphs","greedy","sortings"],"code":"\/*\n\n Author : Akshat Jindal\n\n from NIT Jalandhar , Punjab , India\n\n JAI MATA DI\n\n *\/\n\nimport java.util.*;\n\n\n\nimport javax.swing.text.Segment;\n\n\n\n\n\nimport java.io.*;\n\nimport java.math.*;\n\nimport java.sql.Array;\n\n\n\n\n\n\n\npublic class Main {\n\n\t static class FR{\n\n\t\t \n\n\t\t\tBufferedReader br;\n\n\t\t\tStringTokenizer st;\n\n\t\t\tpublic FR() {\n\n\t\t\t\tbr = new BufferedReader(new InputStreamReader(System.in));\n\n\t\t\t}\n\n\t\t\tString next() \n\n\t\t { \n\n\t\t while (st == null || !st.hasMoreElements()) \n\n\t\t { \n\n\t\t try\n\n\t\t { \n\n\t\t st = new StringTokenizer(br.readLine()); \n\n\t\t } \n\n\t\t catch (IOException e) \n\n\t\t { \n\n\t\t e.printStackTrace(); \n\n\t\t } \n\n\t\t } \n\n\t\t return st.nextToken(); \n\n\t\t } \n\n\n\n\t\t int nextInt() \n\n\t\t { \n\n\t\t return Integer.parseInt(next()); \n\n\t\t } \n\n\n\n\t\t long nextLong() \n\n\t\t { \n\n\t\t return Long.parseLong(next()); \n\n\t\t } \n\n\n\n\t\t double nextDouble() \n\n\t\t { \n\n\t\t return Double.parseDouble(next()); \n\n\t\t } \n\n\n\n\t\t String nextLine() \n\n\t\t { \n\n\t\t String str = \"\"; \n\n\t\t try\n\n\t\t { \n\n\t\t str = br.readLine(); \n\n\t\t } \n\n\t\t catch (IOException e) \n\n\t\t { \n\n\t\t e.printStackTrace(); \n\n\t\t } \n\n\t\t return str; \n\n\t\t } \n\n\t\t}\n\n\t \n\n\t static long mod = (long)(1e9 + 7);\n\n\t \n\n\tstatic void sort(long[] arr ) {\n\n\t\t ArrayList al = new ArrayList<>();\n\n\t\t for(long e:arr) al.add(e);\n\n\t\t Collections.sort(al);\n\n\t\t for(int i = 0 ; i al = new ArrayList<>();\n\n\t\t for(int e:arr) al.add(e);\n\n\t\t Collections.sort(al);\n\n\t\t for(int i = 0 ; i al = new ArrayList();\n\n\t\tfor(char cc:arr) al.add(cc);\n\n\t\tCollections.sort(al);\n\n\t\tfor(int i = 0 ;i=j) {\n\n\t\t\tint temp = arr[i];\n\n\t\t\tarr[i] = arr[j];\n\n\t\t\tarr[j] = temp;\n\n\t\t\ti++;\n\n\t\t\tj--;\n\n\t\t}\n\n\t}\n\n\tstatic void rvrs(long[] arr) {\n\n\t\tint i =0 , j = arr.length-1;\n\n\t\twhile(i>=j) {\n\n\t\t\tlong temp = arr[i];\n\n\t\t\tarr[i] = arr[j];\n\n\t\t\tarr[j] = temp;\n\n\t\t\ti++;\n\n\t\t\tj--;\n\n\t\t}\n\n\t}\n\n\n\n\tstatic long mod_mul(long a , long b ,long mod) {\n\n\t\treturn ((a%mod)*(b%mod))%mod;\n\n\t}\n\n\t static long gcd(long a, long b)\n\n\t { \n\n\t if (b == 0)\n\n\t return a;\n\n\t return gcd(b, a % b); \n\n\t }\n\n\t static boolean[] prime(int num) {\n\n\t\t\tboolean[] bool = new boolean[num];\n\n\t\t \n\n\t\t for (int i = 0; i< bool.length; i++) {\n\n\t\t bool[i] = true;\n\n\t\t }\n\n\t\t for (int i = 2; i< Math.sqrt(num); i++) {\n\n\t\t if(bool[i] == true) {\n\n\t\t for(int j = (i*i); j= 0) {\n\n\t\t \t bool[0] = false;\n\n\t\t \t bool[1] = false;\n\n\t\t }\n\n\t\t \n\n\t\t return bool;\n\n\t\t}\n\n\n\n\t static long modInverse(long a, long m)\n\n\t {\n\n\t long g = gcd(a, m);\n\n\t \n\n\t return power(a, m - 2, m);\n\n\t \n\n\t }\n\n\t \n\n\t static long power(long x, long y, long m){\n\n\t if (y == 0) return 1; long p = power(x, y \/ 2, m) % m; p = (int)((p * (long)p) % m);\n\n\t if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }\n\n\t \n\n static class Combinations{\n\n\t \t private long[] z;\n\n\t \t private long[] z1;\n\n\t \t private long[] z2;\n\n\t \t public Combinations(long N , long mod) {\n\n\t\t\t\tz = new long[(int)N+1];\n\n\t\t\t\tz1 = new long[(int)N+1];\n\n\t\t\t\tz[0] = 1;\n\n\t\t\t\tfor(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;\n\n\t\t\t z2 = new long[(int)N+1];\n\n\t\t\t\tz2[0] = z2[1] = 1;\n\n\t\t\t for (int i = 2; i <= N; i++)\n\n\t\t\t z2[i] = z2[(int)(mod % i)] * (mod - mod \/ i) % mod;\n\n\t\t\t \n\n\t\t\t \n\n\t\t\t z1[0] = z1[1] = 1;\n\n\t\t\t \n\n\t\t\t for (int i = 2; i <= N; i++)\n\n\t\t\t z1[i] = (z2[i] * z1[i - 1]) % mod;\n\n\t\t\t}\n\n\t \t long fac(long n) {\n\n\t \t\t return z[(int)n];\n\n\t \t }\n\n\t \t long invrsNum(long n) {\n\n\t \t\t return z2[(int)n];\n\n\t \t }\n\n\t \t long invrsFac(long n) {\n\n\t \t\t return invrsFac((int)n);\n\n\t \t }\n\n\t \t long ncr(long N, long R, long mod)\n\n\t \t {\t\tif(R<0 || R>N ) return 0;\n\n\t \t\t long ans = ((z[(int)N] * z1[(int)R])\n\n\t \t\t % mod * z1[(int)(N - R)])\n\n\t \t\t % mod;\n\n\t \t\t return ans;\n\n\t \t\t}\n\n\t }\n\n\t static class DisjointUnionSets {\n\n\t\t\t int[] rank, parent;\n\n\t\t\t int n;\n\n\t\t\t \n\n\t\t\t public DisjointUnionSets(int n)\n\n\t\t\t {\n\n\t\t\t rank = new int[n];\n\n\t\t\t parent = new int[n];\n\n\t\t\t this.n = n;\n\n\t\t\t makeSet();\n\n\t\t\t }\n\n\t\t\t \n\n\t\t\t void makeSet()\n\n\t\t\t {\n\n\t\t\t for (int i = 0; i < n; i++) {\n\n\t\t\t \n\n\t\t\t parent[i] = i;\n\n\t\t\t }\n\n\t\t\t }\n\n\t\t\t \n\n\t\t\t int find(int x)\n\n\t\t\t {\n\n\t\t\t if (parent[x] != x) {\n\n\t\t\t \n\n\t\t\t parent[x] = find(parent[x]);\n\n\t\t\t \n\n\t\t\t }\n\n\t\t\t \n\n\t\t\t return parent[x];\n\n\t\t\t }\n\n\t\t\t \n\n\t\t\t void union(int x, int y)\n\n\t\t\t {\n\n\t\t\t int xRoot = find(x), yRoot = find(y);\n\n\t\t\t \n\n\t\t\t if (xRoot == yRoot)\n\n\t\t\t return;\n\n\t\t\t \n\n\t\t\t if (rank[xRoot] < rank[yRoot])\n\n\t\t\t \n\n\t\t\t parent[xRoot] = yRoot;\n\n\t\t\t \n\n\t\t\t else if (rank[yRoot] < rank[xRoot])\n\n\t\t\t \n\n\t\t\t parent[yRoot] = xRoot;\n\n\t\t\t \n\n\t\t\t else\n\n\t\t\t {\n\n\t\t\t parent[yRoot] = xRoot;\n\n\t\t\t \n\n\t\t\t rank[xRoot] = rank[xRoot] + 1;\n\n\t\t\t }\n\n\t\t\t }\n\n\t\t\t}\n\n\t static int[] KMP(String str) {\n\n\t \t int n = str.length();\n\n\t \t int[] kmp = new int[n];\n\n\t \t for(int i = 1 ; i0 && str.charAt(i) != str.charAt(j)) {\n\n\t \t\t\t j = kmp[j-1];\n\n\t \t\t }\n\n\t \t\t if(str.charAt(i) == str.charAt(j)) j++;\n\n\t \t\t kmp[i] = j;\n\n\t \t }\n\n\t \t \n\n\t \t return kmp;\n\n\t }\n\n\t \n\n\t \n\n\/************************************************ Query **************************************************************************************\/\t \n\n\t \n\n\/***************************************** \t\tSparse Table\t********************************************************\/\n\n\t static class SparseTable{\n\n\t \t\t\n\n\t \t\tprivate long[][] st;\n\n\t \t\t\n\n\t \t\tSparseTable(long[] arr){\n\n\t \t\t\tint n = arr.length;\n\n\t \t\t\tst = new long[n][25];\n\n\t \t\t\tlog = new int[n+2];\n\n\t \t\t\tbuild_log(n+1);\n\n\t \t\t\tbuild(arr);\n\n\t \t\t}\n\n\t \t\t\n\n\t \t\tprivate void build(long[] arr) {\n\n\t \t\t\tint n = arr.length;\n\n\t \t\t\t\n\n\t \t\t\tfor(int i = n-1 ; i>=0 ; i--) {\n\n\t \t\t\t\tfor(int j = 0 ; j<25 ; j++) {\n\n\t \t\t\t\t\tint r = i + (1<=n) break;\n\n\t \t\t\t\t\tif(j == 0 ) st[i][j] = arr[i];\n\n\t \t\t\t\t\telse st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );\n\n\t \t\t\t\t}\n\n\t \t\t\t}\n\n\t \t\t}\n\n\t \t\tpublic long gcd(long a ,long b) {\n\n\t \t\t\tif(a == 0) return b;\n\n\t \t\t\treturn gcd(b%a , a);\n\n\t \t\t}\n\n\t \t\tpublic long query(int l ,int r) {\n\n\t \t\t\tint w = r-l+1;\n\n\t \t\t\tint power = log[w];\n\n\t \t\t\treturn Math.min(st[l][power],st[r - (1<=qs && se<=qe) return tree[index];\n\n\t\t\t\t\t\n\n\t\t\t\t\tif(qeei) return;\n\n\t\t\t\t if(si == ei ) { \n\n\t\t\t\t\t tree[index] = arr[id];\n\n\t\t\t\t\t return;\n\n\t\t\t\t }\n\n\t\t\t\t if(si > ei) return;\n\n\t\t\t\t int mid = (ei + si)\/2;\n\n\t\t\t\t\t\n\n\t\t\t\t\tupdate( id, si, mid , 2*index);\n\n\t\t\t\t\tupdate( id , mid+1, ei , 2*index+1);\n\n\t\t\t\t\t\n\n\t\t\t\t\ttree[index] = Math.min(tree[2*index] ,tree[2*index+1]);\n\n\t\t\t }\n\n\t\t\t \n\n\t\t }\n\n\t\t *\/\n\n\n\n\/* ***************************************************************************************************************************************************\/\t \n\n\t \n\n\t static FR sc = new FR();\n\n\t static StringBuilder sb = new StringBuilder();\n\n\t public static void main(String args[]) throws IOException {\n\n\t\n\n\t\t int tc = 1;\n\n\/\/\t\t tc = sc.nextInt();\n\n\t\t \n\n\t\t while(tc-->0) {\n\n\t\t\t TEST_CASE();\n\n\t\t\t \n\n\t\t }\n\n\t\t System.out.println(sb);\n\n\t }\n\n\t static void TEST_CASE() {\n\n\t\t int n = sc.nextInt();\n\n\t\t char[] str = sc.next().toCharArray();\n\n\t\t int[] ans = new int[n];\n\n\t\t boolean bool = fnc(str, ans);\n\n\t\t if(bool) {\n\n\t\t\t System.out.println(\"YES\");\n\n\t\t\t for(int e:ans) sb.append(e);\n\n\t\t }else {\n\n\t\t\t System.out.println(\"NO\");\n\n\t\t }\n\n\t }\n\n\t static boolean fnc(char[] str ,int[] ans) {\n\n\t\t int n = str.length;\n\n\t\t Arrays.fill(ans, -1);\n\n\t\t \n\n\t\t for(int k =0 ; k<26 ; k++) {\n\n\t\t\t ArrayList ind = new ArrayList<>();\n\n\t\t\t for(int i = 0 ;i non = new ArrayList<>();\n\n\t\t\t for(int i =0 ; i k)\n\n\t\t\t\t non.add(i);\n\n\t\t\t }\n\n\t\t\t boolean one = false , zero = false;\n\n\t\t\t for(int e:non) {\n\n\t\t\t\t if(ans[e] == 0) zero = true;\n\n\t\t\t\t if(ans[e] == 1) one = true;\n\n\t\t\t }\n\n\t\t\t if(one && zero) return false;\n\n\t\t\t if( (one && ans[ind.get(0)] == 1) || (zero && ans[ind.get(0)] == 0) ) \n\n\t\t\t\t return false; \n\n\t\t\t if(one || ans[ind.get(0)] == 0) {\n\n\t\t\t\t ans[ind.get(0)] = 0;\n\n\t\t\t\t for(int e:non) ans[e] = 1;\n\n\t\t\t }else {\n\n\t\t\t\t ans[ind.get(0)] = 1;\n\n\t\t\t\t for(int e:non) ans[e] = 0;\n\n\t\t\t }\n\n\t\t\t for(int i = 1 ; i();\n\n\t\t\t\t for(int j = ind.get(i-1)+1 ; j<=ind.get(i)-1 ; j++) {\n\n\t\t\t\t\t if(str[j] - 'a' > k) non.add(j);\n\n\t\t\t\t }\n\n\t\t\t\t for(int e:non) {\n\n\t\t\t\t\t if(ans[e] == 0) zero = true;\n\n\t\t\t\t\t if(ans[e] == 1) one = true;\n\n\t\t\t\t }\n\n\t\t\t\t if(one && zero) return false;\n\n\t\t\t\t if( (one && ans[ind.get(i)] == 1) || (zero && ans[ind.get(i)] == 0) )\n\n\t\t\t\t\t return false;\n\n\t\t\t\t if(one || ans[ind.get(i)] == 0) {\n\n\t\t\t\t\t ans[ind.get(i)] = 0;\n\n\t\t\t\t\t for(int e:non) ans[e] = 1;\n\n\t\t\t\t }else {\n\n\t\t\t\t\t ans[ind.get(i)] = 1;\n\n\t\t\t\t\t for(int e:non) ans[e] = 0;\n\n\t\t\t\t }\n\n\t\t\t\t \n\n\t\t\t }\n\n\/\/\t\t\t System.out.println(k);\n\n\/\/\t\t\t for(int e:ans) System.out.print(e+\" \");\n\n\/\/\t\t\t System.out.println();\n\n\/\/\t\t\t System.out.println(\"------------\");\n\n\t\t }\n\n\t\t \n\n\t\t return true;\n\n\t }\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\/*******************************************************************************************************************************************************\/\n\n\n\n\/**\n\n \n\n \n\n \n\n \n\n \n\n *\/\n\n","language":"java"} -{"contest_id":"1324","problem_id":"E","statement":"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\u22121ai\u22121 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\u2264n\u22642000,3\u2264h\u22642000,0\u2264l\u2264r 0) {\n\n int n=sc.nextInt();\n\n int h=sc.nextInt();\n\n int l=sc.nextInt();\n\n int r=sc.nextInt();\n\n int[] arr=new int[n];\n\n for(int i=0;i=arr.length)return 0;\n\n if(dp[ch][idx]!=-1)return dp[ch][idx];\n\n int currTimeLess=(ch+arr[idx]-1)%h;\n\n int withOut=recSol(currTimeLess,idx+1,h,l,r,arr,dp);\n\n if(currTimeLess>=l && currTimeLess<=r)withOut++;\n\n int currTimeMore=(ch+arr[idx])%h;\n\n int with=recSol(currTimeMore, idx+1, h, l, r, arr, dp);\n\n if(currTimeMore>=l && currTimeMore<=r)with++;\n\n return dp[ch][idx]=Math.max(with,withOut);\n\n\n\n }\n\n\n\n public static class pair {\n\n int ff;\n\n int ss;\n\n\n\n pair(int ff, int ss) {\n\n this.ff = ff;\n\n this.ss = ss;\n\n }\n\n }\n\n\n\n static int BS(int[] arr, int l, int r, int element) {\n\n int low = l;\n\n int high = r;\n\n while (high - low > 1) {\n\n int mid = low + (high - low) \/ 2;\n\n if (arr[mid] < element) {\n\n low = mid + 1;\n\n } else {\n\n high = mid;\n\n }\n\n }\n\n if (arr[low] == element) {\n\n return low;\n\n } else if (arr[high] == element) {\n\n return high;\n\n }\n\n return -1;\n\n }\n\n\n\n static int lower_bound(int[] arr, int l, int r, int element) {\n\n int low = l;\n\n int high = r;\n\n while (high - low > 1) {\n\n int mid = low + (high - low) \/ 2;\n\n if (arr[mid] < element) {\n\n low = mid + 1;\n\n } else {\n\n high = mid;\n\n }\n\n }\n\n if (arr[low] >= element) {\n\n return low;\n\n } else if (arr[high] >= element) {\n\n return high;\n\n }\n\n return -1;\n\n }\n\n\n\n static int upper_bound(int[] arr, int l, int r, int element) {\n\n int low = l;\n\n int high = r;\n\n while (high - low > 1) {\n\n int mid = low + (high - low) \/ 2;\n\n if (arr[mid] <= element) {\n\n low = mid + 1;\n\n } else {\n\n high = mid;\n\n }\n\n }\n\n if (arr[low] > element) {\n\n return low;\n\n } else if (arr[high] > element) {\n\n return high;\n\n }\n\n return -1;\n\n }\n\n\n\n public static long gcd_long(long a, long b) {\n\n \/\/ a\/b,a-> dividant b-> divisor\n\n if (b == 0)\n\n return a;\n\n return gcd_long(b, a % b);\n\n }\n\n\n\n public static int gcd_int(int a, int b) {\n\n \/\/ a\/b,a-> dividant b-> divisor\n\n if (b == 0)\n\n return a;\n\n return gcd_int(b, a % b);\n\n }\n\n\n\n public static int lcm(int a, int b) {\n\n int gcd = gcd_int(a, b);\n\n return (a * b) \/ gcd;\n\n }\n\n\n\n static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public FastReader() {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n\n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n String nextLine() {\n\n String s = \"\";\n\n try {\n\n s = br.readLine();\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return s;\n\n }\n\n\n\n Long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n }\n\n\n\n \/\/ FACTORISATION OF A NUMBER ---> OPTIMISED CODE\n\n \/\/ TC -->O(sqrt(N));\n\n public static void factorize(int n) {\n\n for (int i = 2; i * i <= n; i++) {\n\n if (n % i == 0) {\n\n int cnt = 0;\n\n while (n % i == 0) {\n\n n \/= i;\n\n cnt++;\n\n }\n\n System.out.println(\"DIVISOR is \" + i + \" \" + \"COUNT is \" + cnt);\n\n }\n\n }\n\n if (n != 1) {\n\n \/\/ n is prime number\n\n System.out.println(\"DIVISOR is \" + n + \" \" + \"COUNT is \" + 1);\n\n }\n\n }\n\n\n\n \/\/ DISJOINT SET UNINION OPTIMALLY IMPLEMENTED USING PATH COMPRESSION AND RANK\n\n \/\/ ARRAY------>>>>>>>>>>>>>>>>>>>>>\n\n \/\/ parent[i].ff==parent of i and parent[i].ss gives the rant of the set in which\n\n \/\/ i belongs to\n\n public static int find_set(int a, pair[] parent) {\n\n if (parent[a].ff == a)\n\n return a;\n\n return parent[a].ff = find_set(parent[a].ff, parent);\n\n }\n\n\n\n public static void union_set(int a, int b, pair[] parent) {\n\n int a_root = find_set(a, parent);\n\n int b_root = find_set(b, parent);\n\n if (a_root == b_root)\n\n return;\n\n if (parent[a_root].ss < parent[b_root].ss) {\n\n parent[a_root].ff = b_root;\n\n } else if (parent[a_root].ss > parent[b_root].ss) {\n\n parent[b_root].ff = a_root;\n\n } else {\n\n parent[b_root].ff = a_root;\n\n parent[a_root].ss++;\n\n }\n\n }\n\n\n\n public static class UnionFind {\n\n int[] p, rank, setSize;\n\n int numSets;\n\n\n\n public UnionFind(int N) {\n\n p = new int[numSets = N];\n\n rank = new int[N];\n\n setSize = new int[N];\n\n for (int i = 0; i < N; i++) {\n\n p[i] = i;\n\n setSize[i] = 1;\n\n }\n\n }\n\n\n\n public int findSet(int i) {\n\n return p[i] == i ? i : (p[i] = findSet(p[i]));\n\n }\n\n\n\n public boolean isSameSet(int i, int j) {\n\n return findSet(i) == findSet(j);\n\n }\n\n\n\n public void unionSet(int i, int j) {\n\n if (isSameSet(i, j))\n\n return;\n\n numSets--;\n\n int x = findSet(i), y = findSet(j);\n\n if (rank[x] > rank[y]) {\n\n p[y] = x;\n\n setSize[x] += setSize[y];\n\n } else {\n\n p[x] = y;\n\n setSize[y] += setSize[x];\n\n if (rank[x] == rank[y])\n\n rank[y]++;\n\n }\n\n }\n\n\n\n public int numDisjointSets() {\n\n return numSets;\n\n }\n\n\n\n public int sizeOfSet(int i) {\n\n return setSize[findSet(i)];\n\n }\n\n }\n\n \/\/\/\/SEGMENT TREE NORMAL ONE FOR MAX ELEMENT OF A RANGE\n\n public static void buildTree(int v,int l,int r,int[] arr,int[] st){\n\n if(rr){\n\n return Integer.MIN_VALUE;\n\n }\n\n if(cl>=l && cr<=r){\n\n return st[v];\n\n }\n\n int cmid=(cl+cr)\/2;\n\n return Math.max(query(2*v+1, cl, cmid, l, r, st),query(2*v+2, cmid+1, cr, l, r, st));\n\n }\n\n\n\n}\n\n\n\n\/*\n\n * public static boolean lie(int n,int m,int k){ if(n==1 && m==1 && k==0){\n\n * return true; } if(n<1 || m<1 || k<0){ return false; } boolean\n\n * tc=lie(n-1,m,k-m); boolean lc=lie(n,m-1,k-n); if(tc || lc){ return true; }\n\n * return false; }\n\n *\/\n\n","language":"java"} -{"contest_id":"1295","problem_id":"D","statement":"D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0\u2264x 0) {\n\n long X = sc.nextLong();\n\n long Y = sc.nextLong();\n\n long result = Y \/ getGCD(X, Y);\n\n long val = result;\n\n for (long ctr = 2; ctr * ctr <= val; ctr++) {\n\n if (val % ctr == 0) {\n\n result -= result \/ ctr;\n\n }\n\n while (val % ctr == 0) {\n\n val \/= ctr;\n\n }\n\n }\n\n if (val != 1) {\n\n result -= result \/ val;\n\n }\n\n System.out.println(result);\n\n }\n\n }\n\n\n\n private static long getGCD(long a, long b) {\n\n return b == 0 ? a : getGCD(b, a % b);\n\n }\n\n}","language":"java"} -{"contest_id":"1286","problem_id":"C1","statement":"C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r \u2013 ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s \u2013 guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the string, and the following line should contain the string ss.ExampleInputCopy4\n\na\naa\na\n\ncb\nb\nc\n\ncOutputCopy? 1 2\n\n? 3 4\n\n? 4 4\n\n! aabc","tags":["brute force","constructive algorithms","interactive","math"],"code":"import java.io.OutputStream;\n\nimport java.io.IOException;\n\nimport java.io.InputStream;\n\nimport java.io.OutputStream;\n\nimport java.io.PrintWriter;\n\nimport java.util.Arrays;\n\nimport java.io.BufferedWriter;\n\nimport java.util.InputMismatchException;\n\nimport java.io.IOException;\n\nimport java.util.ArrayList;\n\nimport java.io.Writer;\n\nimport java.io.OutputStreamWriter;\n\nimport java.io.InputStream;\n\n\n\n\/**\n\n * Built using CHelper plug-in Actual solution is at the top\n\n *\n\n * @author ilyakor\n\n *\/\n\npublic class Main {\n\n\n\n public static void main(String[] args) {\n\n InputStream inputStream = System.in;\n\n OutputStream outputStream = System.out;\n\n InputReader in = new InputReader(inputStream);\n\n OutputWriter out = new OutputWriter(outputStream);\n\n TaskC1 solver = new TaskC1();\n\n solver.solve(1, in, out);\n\n out.close();\n\n }\n\n\n\n static class TaskC1 {\n\n\n\n InputReader in;\n\n OutputWriter out;\n\n\n\n public void solve(int testNumber, InputReader in, OutputWriter out) {\n\n \/\/ Random random = new Random(0xdead);\n\n \/\/ for (int it = 0; it < 10000; ++it) {\n\n \/\/ int n = 8;\n\n \/\/ StringBuilder sb = new StringBuilder();\n\n \/\/ for (int i = 0; i < n; ++i)\n\n \/\/ sb.append((char)('a' + random.nextInt(26)));\n\n \/\/ S = sb.toString();\n\n \/\/ sum = 0;\n\n \/\/ String res = new String(doSolve(S.length()));\n\n \/\/ if (sum > (n + 1) * (n + 1))\n\n \/\/ throw new RuntimeException();\n\n \/\/ if (!res.equals(S))\n\n \/\/ throw new RuntimeException();\n\n \/\/ }\n\n\n\n this.in = in;\n\n this.out = out;\n\n\n\n int n = in.nextInt();\n\n if (n == 1) {\n\n char c1 = doQuery(1, 1).get(0)[0];\n\n out.printLine(\"! \" + c1);\n\n out.flush();\n\n return;\n\n }\n\n if (n == 2) {\n\n char c1 = doQuery(1, 1).get(0)[0];\n\n out.printLine(\"? 2 2\");\n\n out.flush();\n\n char c2 = in.nextToken().toCharArray()[0];\n\n out.printLine(\"! \" + c1 + \"\" + c2);\n\n out.flush();\n\n return;\n\n }\n\n if (n == 3) {\n\n char c1 = doQuery(1, 1).get(0)[0];\n\n out.printLine(\"? 2 2\");\n\n out.flush();\n\n char c2 = in.nextToken().toCharArray()[0];\n\n out.printLine(\"? 3 3\");\n\n out.flush();\n\n char c3 = in.nextToken().toCharArray()[0];\n\n out.printLine(\"! \" + c1 + \"\" + c2 + \"\" + c3);\n\n out.flush();\n\n return;\n\n }\n\n char[] res = doSolve(n);\n\n out.printLine(\"! \" + new String(res));\n\n out.flush();\n\n }\n\n\n\n public char[] doSolve(int n) {\n\n char c1 = doQuery(1, 1).get(0)[0];\n\n char[][] qn = query(1, n);\n\n int m = 1;\n\n \/\/ int m = n \/ 2 - 1;\n\n \/\/ if ((n - m) % 2 == 1) ++m;\n\n char[][] qm = query(m + 1, n);\n\n char[] res = new char[n];\n\n char c = c1;\n\n int pos = 0;\n\n for (int it = 0; it < n; ++it) {\n\n res[pos] = c;\n\n if (it == n - 1) {\n\n break;\n\n }\n\n if (res[n - 1 - pos] == 0) {\n\n c = other(qn[Math.min(pos, n - 1 - pos)], c);\n\n pos = n - 1 - pos;\n\n } else {\n\n if (res[m + n - 1 - pos] != 0) {\n\n throw new RuntimeException();\n\n }\n\n c = other(qm[Math.min(pos, m + n - 1 - pos) - m], c);\n\n pos = m + n - 1 - pos;\n\n }\n\n }\n\n return res;\n\n }\n\n\n\n private char other(char[] a, char c) {\n\n if (a[0] != c) {\n\n return a[0];\n\n }\n\n return a[1];\n\n }\n\n\n\n private char[][] query(int l, int r) {\n\n int n = r - l + 1;\n\n ArrayList output = doQuery(l, r);\n\n ArrayList[] ans = new ArrayList[n + 1];\n\n for (int i = 0; i < ans.length; ++i) {\n\n ans[i] = new ArrayList<>();\n\n }\n\n for (char[] s : output) {\n\n Arrays.sort(s);\n\n ans[s.length].add(s);\n\n }\n\n char[][] res = new char[(n + 1) \/ 2][2];\n\n int[] cnts = new int[26];\n\n char[] st = new char[20];\n\n int ss = 0;\n\n for (char[] s : ans[n - 1]) {\n\n char[] os = ans[n].get(0);\n\n Arrays.fill(cnts, 0);\n\n for (char c : os) {\n\n ++cnts[c - 'a'];\n\n }\n\n for (char c : s) {\n\n --cnts[c - 'a'];\n\n }\n\n for (int i = 0; i < cnts.length; ++i) {\n\n if (cnts[i] > 0) {\n\n st[ss++] = (char) ('a' + i);\n\n }\n\n }\n\n }\n\n if (ss != 2) {\n\n throw new RuntimeException();\n\n }\n\n res[0][0] = st[0];\n\n res[0][1] = st[1];\n\n for (int i = 1; i < res.length; ++i) {\n\n int len = n - i - 1;\n\n Arrays.fill(cnts, 0);\n\n for (char[] s : ans[len]) {\n\n for (char c : s) {\n\n ++cnts[c - 'a'];\n\n }\n\n }\n\n for (int j = 0; j < i; ++j) {\n\n for (char c : res[j]) {\n\n cnts[c - 'a'] -= j + 1;\n\n }\n\n }\n\n ss = 0;\n\n for (int j = 0; j < cnts.length; ++j) {\n\n if (cnts[j] % (i + 2) != 0) {\n\n st[ss++] = (char) ('a' + j);\n\n }\n\n }\n\n if (ss != 1 && ss != 2) {\n\n throw new RuntimeException();\n\n }\n\n if (ss == 1) {\n\n st[1] = st[0];\n\n }\n\n res[i][0] = st[0];\n\n res[i][1] = st[1];\n\n }\n\n return res;\n\n }\n\n\n\n ArrayList doQuery(int l, int r) {\n\n \/\/ ArrayList res = new ArrayList<>();\n\n \/\/ for (int i = l - 1; i <= r - 1; ++i)\n\n \/\/ for (int j = i; j <= r - 1; ++j)\n\n \/\/ res.add(S.substring(i, j + 1).toCharArray());\n\n \/\/ sum += res.size();\n\n \/\/ return res;\n\n out.printLine(\"? \" + l + \" \" + r);\n\n out.flush();\n\n int n = r - l + 1;\n\n ArrayList res = new ArrayList<>();\n\n for (int i = 0; i < (n * (n + 1)) \/ 2; ++i) {\n\n res.add(in.nextToken().toCharArray());\n\n }\n\n return res;\n\n }\n\n\n\n }\n\n\n\n static class OutputWriter {\n\n\n\n private final PrintWriter writer;\n\n\n\n public OutputWriter(OutputStream outputStream) {\n\n writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n\n }\n\n\n\n public OutputWriter(Writer writer) {\n\n this.writer = new PrintWriter(writer);\n\n }\n\n\n\n public void print(Object... objects) {\n\n for (int i = 0; i < objects.length; i++) {\n\n if (i != 0) {\n\n writer.print(' ');\n\n }\n\n writer.print(objects[i]);\n\n }\n\n }\n\n\n\n public void printLine(Object... objects) {\n\n print(objects);\n\n writer.println();\n\n }\n\n\n\n public void close() {\n\n writer.close();\n\n }\n\n\n\n public void flush() {\n\n writer.flush();\n\n }\n\n\n\n }\n\n\n\n static class InputReader {\n\n\n\n private InputStream stream;\n\n private byte[] buffer = new byte[10000];\n\n private int cur;\n\n private int count;\n\n\n\n public InputReader(InputStream stream) {\n\n this.stream = stream;\n\n }\n\n\n\n public static boolean isSpace(int c) {\n\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n\n }\n\n\n\n public int read() {\n\n if (count == -1) {\n\n throw new InputMismatchException();\n\n }\n\n try {\n\n if (cur >= count) {\n\n cur = 0;\n\n count = stream.read(buffer);\n\n if (count <= 0) {\n\n return -1;\n\n }\n\n }\n\n } catch (IOException e) {\n\n throw new InputMismatchException();\n\n }\n\n return buffer[cur++];\n\n }\n\n\n\n public int readSkipSpace() {\n\n int c;\n\n do {\n\n c = read();\n\n } while (isSpace(c));\n\n return c;\n\n }\n\n\n\n public String nextToken() {\n\n int c = readSkipSpace();\n\n StringBuilder sb = new StringBuilder();\n\n while (!isSpace(c)) {\n\n sb.append((char) c);\n\n c = read();\n\n }\n\n return sb.toString();\n\n }\n\n\n\n public int nextInt() {\n\n int sgn = 1;\n\n int c = readSkipSpace();\n\n if (c == '-') {\n\n sgn = -1;\n\n c = read();\n\n }\n\n int res = 0;\n\n do {\n\n if (c < '0' || c > '9') {\n\n throw new InputMismatchException();\n\n }\n\n res = res * 10 + c - '0';\n\n c = read();\n\n } while (!isSpace(c));\n\n res *= sgn;\n\n return res;\n\n }\n\n\n\n }\n\n}\n\n\n\n","language":"java"} -{"contest_id":"1291","problem_id":"A","statement":"A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive\/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n\u22121n\u22121.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 \u2192\u2192 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u226410001\u2264t\u22641000) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u226430001\u2264n\u22643000) \u00a0\u2014 the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print \"-1\" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4\n4\n1227\n1\n0\n6\n177013\n24\n222373204424185217171912\nOutputCopy1227\n-1\n17703\n2237344218521717191\nNoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 \u2192\u2192 22237320442418521717191 (delete the last digit).","tags":["greedy","math","strings"],"code":"import java.util.Scanner;\n\n\n\npublic class Main {\n\n static long cnt = 0;\n\n\n\n public static void main(String[] args) {\n\n\n\n Scanner sc = new Scanner(System.in);\n\n int t = sc.nextInt();\n\n\n\n while (t-- > 0) {\n\n int n = sc.nextInt();\n\n String s = sc.next();\n\n int cnt = 0;\n\n String ans = \" \";\n\n for (int i = 0; i < n; i++) {\n\n char c = s.charAt(i);\n\n if ((c - '0') % 2 == 1) {\n\n ans += c; \n\n cnt++;\n\n }\n\n if (cnt == 2) {\n\n System.out.println(ans);\n\n break;\n\n }\n\n }\n\n\n\n if (cnt != 2) {\n\n System.out.println(-1);\n\n }\n\n }\n\n }\n\n\n\n}\n\n","language":"java"} -{"contest_id":"1285","problem_id":"D","statement":"D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,\u2026,ana1,a2,\u2026,an and challenged him to choose an integer XX such that the value max1\u2264i\u2264n(ai\u2295X)max1\u2264i\u2264n(ai\u2295X) is minimum possible, where \u2295\u2295 denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1\u2264i\u2264n(ai\u2295X)max1\u2264i\u2264n(ai\u2295X).InputThe first line contains integer nn (1\u2264n\u22641051\u2264n\u2264105).The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u2264230\u221210\u2264ai\u2264230\u22121).OutputPrint one integer \u2014 the minimum possible value of max1\u2264i\u2264n(ai\u2295X)max1\u2264i\u2264n(ai\u2295X).ExamplesInputCopy3\n1 2 3\nOutputCopy2\nInputCopy2\n1 5\nOutputCopy4\nNoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.","tags":["bitmasks","brute force","dfs and similar","divide and conquer","dp","greedy","strings","trees"],"code":"import java.io.BufferedReader;\n\nimport java.io.BufferedWriter;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.io.OutputStreamWriter;\n\nimport java.io.PrintWriter;\n\nimport java.util.ArrayList;\n\nimport java.util.StringTokenizer;\n\n\n\npublic class drevilunderscores {\n\n\tpublic static void main(String[] args) throws IOException {\n\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n\t\tPrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));\n\n\n\n\t\tint n = Integer.parseInt(br.readLine());\n\n\t\tStringTokenizer token = new StringTokenizer(br.readLine());\n\n\t\t\n\n\t\tArrayList a = new ArrayList<>();\n\n\t\tfor (int i = 0; i < n; i++) a.add(Integer.parseInt(token.nextToken()));\n\n\t\t\n\n\t\tSystem.out.println(solve(a, 30));\n\n\t}\n\n\t\n\n\tpublic static int solve(ArrayList a, int b) {\n\n\t\tif (b == -1) return 0;\n\n\t\tArrayList l = new ArrayList<>();\n\n\t\tArrayList r = new ArrayList<>();\n\n\t\tfor (int i : a) {\n\n\t\t\tif (((i >> b) & 1) == 0) l.add(i);\n\n\t\t\telse r.add(i);\n\n\t\t}\n\n\t\t\n\n\t\tif (l.size()==0) return solve(r, b-1);\n\n\t\tif (r.size()==0) return solve(l, b-1);\n\n\t\treturn Math.min(solve(l, b-1), solve(r, b-1)) + (1 << b);\n\n\t}\n\n}\n\n","language":"java"} -{"contest_id":"1284","problem_id":"B","statement":"B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,\u2026,al]a=[a1,a2,\u2026,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1\u2264i maximums = new ArrayList<>();\n\n List minimums = new ArrayList<>();\n\n for (int i = 0; i < n; i++) {\n\n boolean alreadyHasAscent = false;\n\n int totalElements = sc.nextInt();\n\n int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;\n\n for (int j = 0; j < totalElements; j++) {\n\n int value = sc.nextInt();\n\n if (value > min) {\n\n alreadyHasAscent = true;\n\n }\n\n min = Math.min(min, value);\n\n max = Math.max(max, value);\n\n }\n\n if (alreadyHasAscent) {\n\n min = Integer.MIN_VALUE;\n\n max = Integer.MAX_VALUE;\n\n }\n\n minimums.add(min);\n\n maximums.add(max);\n\n }\n\n Collections.sort(minimums);\n\n Collections.sort(maximums);\n\n \/\/out.println(maximums);\n\n long totalPairs = 0;\n\n for (int i = 0; i < minimums.size(); i++) {\n\n totalPairs += binarySearch(maximums, minimums.get(i));\n\n }\n\n out.println(totalPairs);\n\n }\n\n\n\n private static long binarySearch(List maximums, int minValue) {\n\n int n = maximums.size();\n\n int lo = 0, hi = n - 1;\n\n int res = n;\n\n while (lo <= hi) {\n\n int mid = (lo + hi) >> 1;\n\n if (maximums.get(mid) > minValue) {\n\n \/\/out.println(\"ok\");\n\n res = Math.min(res, mid);\n\n hi = mid - 1;\n\n }else {\n\n lo = mid + 1;\n\n }\n\n }\n\n return n - res;\n\n }\n\n\n\n\n\n public static FastReader sc;\n\n public static PrintWriter out;\n\n static class FastReader\n\n {\n\n BufferedReader br;\n\n StringTokenizer str;\n\n\n\n public FastReader()\n\n {\n\n br = new BufferedReader(new\n\n InputStreamReader(System.in));\n\n }\n\n\n\n String next()\n\n {\n\n while (str == null || !str.hasMoreElements())\n\n {\n\n try\n\n {\n\n str = new StringTokenizer(br.readLine());\n\n }\n\n catch (IOException end)\n\n {\n\n end.printStackTrace();\n\n }\n\n }\n\n return str.nextToken();\n\n }\n\n\n\n int nextInt()\n\n {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n long nextLong()\n\n {\n\n return Long.parseLong(next());\n\n }\n\n\n\n double nextDouble()\n\n {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n String nextLine()\n\n {\n\n String str = \"\";\n\n try\n\n {\n\n str = br.readLine();\n\n }\n\n catch (IOException end)\n\n {\n\n end.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1304","problem_id":"E","statement":"E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3\u2264n\u22641053\u2264n\u2264105), the number of vertices of the tree.Next n\u22121n\u22121 lines contain two integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n, u\u2260vu\u2260v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1\u2264q\u22641051\u2264q\u2264105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1\u2264x,y,a,b\u2264n1\u2264x,y,a,b\u2264n, x\u2260yx\u2260y, 1\u2264k\u22641091\u2264k\u2264109) \u2013 the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print \"YES\" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print \"NO\".You can print each letter in any case (upper or lower).ExampleInputCopy5\n1 2\n2 3\n3 4\n4 5\n5\n1 3 1 2 2\n1 4 1 3 2\n1 4 1 3 3\n4 2 3 3 9\n5 2 3 3 9\nOutputCopyYES\nYES\nNO\nYES\nNO\nNoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with \"YES\" answers are: 11-st query: 11 \u2013 33 \u2013 22 22-nd query: 11 \u2013 22 \u2013 33 44-th query: 33 \u2013 44 \u2013 22 \u2013 33 \u2013 44 \u2013 22 \u2013 33 \u2013 44 \u2013 22 \u2013 33 ","tags":["data structures","dfs and similar","shortest paths","trees"],"code":"\/*\n\n \"Everything in the universe is balanced. Every disappointment\n\n you face in life will be balanced by something good for you!\n\n Keep going, never give up.\"\n\n\n\n Just have Patience + 1...\n\n\n\n*\/\n\n\n\n\n\n\n\n\n\nimport java.util.*;\n\nimport java.lang.*;\n\nimport java.io.*;\n\n\n\n\n\npublic class Solution {\n\n\n\n static int MAX = 100005, DEPTH = 25;\n\n\n\n static int[] tin = new int[MAX];\n\n static int[] tout = new int[MAX];\n\n static int time = 1;\n\n\n\n static int[] distance = new int[MAX];\n\n static int[][] ancestor = new int[MAX][DEPTH];\n\n\n\n static Map> graph = new HashMap<>();\n\n\n\n public static void main(String[] args) throws java.lang.Exception {\n\n out = new PrintWriter(new BufferedOutputStream(System.out));\n\n sc = new FastReader();\n\n\n\n int test = 1;\n\n for (int t = 1; t <= test; t++) {\n\n solve();\n\n }\n\n out.close();\n\n }\n\n\n\n private static void solve() {\n\n int n = sc.nextInt();\n\n\n\n for (int i = 1; i <= n; i++) {\n\n graph.put(i, new ArrayList<>());\n\n }\n\n\n\n for (int i = 0; i < n - 1; i++) {\n\n int u = sc.nextInt();\n\n int v = sc.nextInt();\n\n graph.get(u).add(v);\n\n graph.get(v).add(u);\n\n }\n\n\n\n dfs(1, 1);\n\n\n\n int q = sc.nextInt();\n\n for (int i = 0; i < q; i++) {\n\n\n\n \/\/ add edge between x and y\n\n int x = sc.nextInt();\n\n int y = sc.nextInt();\n\n\n\n \/\/ find a path from a to b having exactly k edges\n\n int a = sc.nextInt();\n\n int b = sc.nextInt();\n\n int k = sc.nextInt();\n\n\n\n \/\/ if path length between a and b is l, then since a path can contain the same vertices and same edges multiple times,\n\n \/\/ we can also find a path between a and b with length l + 2 * constant\n\n \/\/ we should find a path with length l <= k, which have parity same as parity of k\n\n\n\n List possiblePathLengths = new ArrayList<>();\n\n\n\n \/\/ case1 : path from a to b without using added edge between x and y\n\n possiblePathLengths.add(findDistanceBetweenTwoNodes(a, b));\n\n\n\n \/\/ case2 : path from a to x, then use added edge from x to y (only once, otherwise it won't affect the parity), and then from y to b\n\n possiblePathLengths.add(findDistanceBetweenTwoNodes(a, x) + 1 + findDistanceBetweenTwoNodes(b, y));\n\n\n\n \/\/ case3 : path from a to y, then use added edge from y to x (only once, otherwise it won't affect the parity), and then from x to b\n\n possiblePathLengths.add(findDistanceBetweenTwoNodes(a, y) + 1 + findDistanceBetweenTwoNodes(b, x));\n\n\n\n boolean found = false;\n\n for (int length : possiblePathLengths) {\n\n if (length <= k && (length % 2 == k % 2)) {\n\n found = true;\n\n break;\n\n }\n\n }\n\n\n\n out.println(found ? \"YES\" : \"NO\");\n\n }\n\n }\n\n\n\n private static void dfs(int currNode, int parent) {\n\n tin[currNode] = time++;\n\n\n\n ancestor[currNode][0] = parent;\n\n for (int j = 1; j < DEPTH; j++) {\n\n ancestor[currNode][j] = ancestor[ancestor[currNode][j - 1]][j - 1];\n\n }\n\n\n\n for (int adjacentNode : graph.get(currNode)) {\n\n if (adjacentNode == parent) {\n\n continue;\n\n }\n\n distance[adjacentNode] = distance[currNode] + 1;\n\n dfs(adjacentNode, currNode);\n\n }\n\n\n\n tout[currNode] = time++;\n\n }\n\n\n\n private static int findDistanceBetweenTwoNodes(int u, int v) {\n\n int lcaNode = findLCA(u, v);\n\n return distance[u] + distance[v] - 2 * distance[lcaNode];\n\n }\n\n\n\n private static int findLCA(int u, int v) {\n\n if (isAncestor(u, v)) {\n\n return u;\n\n }\n\n if (isAncestor(v, u)) {\n\n return v;\n\n }\n\n\n\n for (int j = DEPTH - 1; j >= 0; j--) {\n\n if (!isAncestor(ancestor[u][j], v)) {\n\n u = ancestor[u][j];\n\n }\n\n }\n\n\n\n return ancestor[u][0];\n\n }\n\n\n\n private static boolean isAncestor(int u, int v) { \/\/ check if u is ancestor of v\n\n return tin[u] <= tin[v] && tout[u] >= tout[v];\n\n }\n\n\n\n\n\n public static FastReader sc;\n\n public static PrintWriter out;\n\n static class FastReader\n\n {\n\n BufferedReader br;\n\n StringTokenizer str;\n\n\n\n public FastReader()\n\n {\n\n br = new BufferedReader(new\n\n InputStreamReader(System.in));\n\n }\n\n\n\n String next()\n\n {\n\n while (str == null || !str.hasMoreElements())\n\n {\n\n try\n\n {\n\n str = new StringTokenizer(br.readLine());\n\n }\n\n catch (IOException lastMonthOfVacation)\n\n {\n\n lastMonthOfVacation.printStackTrace();\n\n }\n\n }\n\n return str.nextToken();\n\n }\n\n\n\n int nextInt()\n\n {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n long nextLong()\n\n {\n\n return Long.parseLong(next());\n\n }\n\n\n\n double nextDouble()\n\n {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n String nextLine()\n\n {\n\n String str = \"\";\n\n try\n\n {\n\n str = br.readLine();\n\n }\n\n catch (IOException lastMonthOfVacation)\n\n {\n\n lastMonthOfVacation.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n\n\n}\n\n","language":"java"} -{"contest_id":"1296","problem_id":"E1","statement":"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\u2264n\u22642001\u2264n\u2264200) \u2014 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\nabacbecfd\nOutputCopyYES\n001010101\nInputCopy8\naaabbcbb\nOutputCopyYES\n01011011\nInputCopy7\nabcdedc\nOutputCopyNO\nInputCopy5\nabcde\nOutputCopyYES\n00000\n","tags":["constructive algorithms","dp","graphs","greedy","sortings"],"code":"\/*\n\n \"Everything in the universe is balanced. Every disappointment\n\n you face in life will be balanced by something good for you!\n\n Keep going, never give up.\"\n\n\n\n Just have Patience + 1...\n\n\n\n*\/\n\n\n\n\n\n\n\nimport java.util.*;\n\nimport java.lang.*;\n\nimport java.io.*;\n\n\n\n\n\npublic class Solution {\n\n\n\n public static void main(String[] args) throws java.lang.Exception {\n\n out = new PrintWriter(new BufferedOutputStream(System.out));\n\n sc = new FastReader();\n\n\n\n int test = 1;\n\n for (int t = 0; t < test; t++) {\n\n solve();\n\n }\n\n out.close();\n\n }\n\n\n\n private static void solve() {\n\n int n = sc.nextInt();\n\n char[] s = sc.next().toCharArray();\n\n char prev = 'a', prevToPrev = 'a';\n\n String res = \"\";\n\n for (int i = 0; i < n; i++) {\n\n if (s[i] >= prev) {\n\n res += '0';\n\n prev = s[i];\n\n }else if (s[i] >= prevToPrev) {\n\n res += '1';\n\n prevToPrev = s[i];\n\n }else {\n\n out.println(\"NO\");\n\n return;\n\n }\n\n }\n\n out.println(\"YES\");\n\n out.println(res);\n\n }\n\n\n\n\n\n public static FastReader sc;\n\n public static PrintWriter out;\n\n static class FastReader\n\n {\n\n BufferedReader br;\n\n StringTokenizer str;\n\n\n\n public FastReader()\n\n {\n\n br = new BufferedReader(new\n\n InputStreamReader(System.in));\n\n }\n\n\n\n String next()\n\n {\n\n while (str == null || !str.hasMoreElements())\n\n {\n\n try\n\n {\n\n str = new StringTokenizer(br.readLine());\n\n }\n\n catch (IOException end)\n\n {\n\n end.printStackTrace();\n\n }\n\n }\n\n return str.nextToken();\n\n }\n\n\n\n int nextInt()\n\n {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n long nextLong()\n\n {\n\n return Long.parseLong(next());\n\n }\n\n\n\n double nextDouble()\n\n {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n String nextLine()\n\n {\n\n String str = \"\";\n\n try\n\n {\n\n str = br.readLine();\n\n }\n\n catch (IOException end)\n\n {\n\n end.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n}\n\n","language":"java"} -{"contest_id":"1313","problem_id":"A","statement":"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\u2264t\u22645001\u2264t\u2264500)\u00a0\u2014 the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0\u2264a,b,c\u2264100\u2264a,b,c\u226410)\u00a0\u2014 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\u00a0\u2014 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.","tags":["brute force","greedy","implementation"],"code":"\nimport java.util.*;\n\npublic class Training1 {\n\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n for (int i = 0; i < t; i++) {\n int arr[]=new int[3];\n arr[0] = sc.nextInt();\n arr[1] = sc.nextInt();\n arr[2] = sc.nextInt();\n Arrays.sort(arr);\n int res = 0;\n if (arr[0] > 0) {\n arr[0]--;\n res++;\n }\n if (arr[1] > 0) {\n arr[1]--;\n res++;\n }\n if (arr[2] > 0) {\n arr[2]--;\n res++;\n }\n if (arr[2] > 0 && arr[0] > 0) {\n arr[2]--;\n arr[0]--;\n res++;\n }\n if (arr[2] > 0 && arr[1] > 0) {\n arr[2]--;\n arr[1]--;\n res++;\n }\n if (arr[0] > 0 && arr[1] > 0) {\n arr[0]--;\n arr[1]--;\n res++;\n }\n if (arr[0] > 0 && arr[1] > 0&& arr[2]>0) {\n res++;\n }\n System.out.println(res);\n }\n\n }\n\n}\n\n\t\t\t \t\t \t \t \t\t\t\t \t \t\t\t \t","language":"java"} -{"contest_id":"1303","problem_id":"B","statement":"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,\u2026,g1,2,\u2026,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\u2264T\u22641041\u2264T\u2264104) \u2014 the number of test cases.Next TT lines contain test cases \u2014 one per line. Each line contains three integers nn, gg and bb (1\u2264n,g,b\u22641091\u2264n,g,b\u2264109) \u2014 the length of the highway and the number of good and bad days respectively.OutputPrint TT integers \u2014 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\n5 1 1\n8 10 10\n1000000 1 1000000\nOutputCopy5\n8\n499999500000\nNoteIn 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.","tags":["math"],"code":"\n\n\n\nimport java.lang.reflect.Array;\n\nimport java.math.BigInteger;\n\nimport java.util.*;\n\nimport java.lang.*;\n\nimport java.io.*;\n\n\n\npublic class Solution {\n\n\n\n static int MAX = 31630;\n\n static boolean[] isPrime = new boolean[MAX];\n\n static List primes = new ArrayList<>();\n\n\n\n public static void main(String[] args) throws Exception {\n\n FastReader fastReader = new FastReader();\n\n int t = fastReader.nextInt();\n\n\n\n\n\n while (t-- > 0) {\n\n int n =fastReader.nextInt();\n\n int g=fastReader.nextInt();\n\n int b = fastReader.nextInt();\n\n\n\n \n\n int goodDays =(int) Math.ceil((1.0*n)\/2);\n\n long totalDays = (long) goodDays \/ g * (g+b) ;\n\n int remainder =goodDays%g;\n\n totalDays = remainder==0?totalDays-b:totalDays+remainder;\n\n\n\n System.out.println(Math.max(totalDays,n));\n\n\n\n\n\n }\n\n }\n\n\n\n\n\n private static void solve(int t) {\n\n int n = sc.nextInt();\n\n int[] arr = new int[n];\n\n for (int i = 0; i < n; i++) {\n\n arr[i] = sc.nextInt();\n\n }\n\n for (int prime : primes) {\n\n int count = 0;\n\n for (int i = 0; i < n; i++) {\n\n if (arr[i] % prime == 0) {\n\n count++;\n\n if (count > 1) {\n\n out.println(\"YES\");\n\n return;\n\n }\n\n while (arr[i] % prime == 0) {\n\n arr[i] \/= prime;\n\n }\n\n }\n\n }\n\n }\n\n HashSet seen = new HashSet<>();\n\n for (int i = 0; i < n; i++) {\n\n if (arr[i] == 1) {\n\n continue;\n\n }\n\n if (seen.contains(arr[i])) {\n\n out.println(\"YES\");\n\n return;\n\n }\n\n seen.add(arr[i]);\n\n }\n\n\n\n out.println(\"NO\");\n\n }\n\n\n\n private static void sieve() {\n\n Arrays.fill(isPrime, true);\n\n isPrime[0] = isPrime[1] = false;\n\n for (int i = 2; i < MAX; i++) {\n\n if (isPrime[i]) {\n\n primes.add(i);\n\n for (int j = 2 * i; j < MAX; j += i) {\n\n isPrime[j] = false;\n\n }\n\n }\n\n }\n\n }\n\n\n\n\n\n public static FastReader sc;\n\n public static PrintWriter out;\n\n\n\n static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer str;\n\n\n\n public FastReader() {\n\n br = new BufferedReader(new\n\n InputStreamReader(System.in));\n\n }\n\n\n\n String next() {\n\n while (str == null || !str.hasMoreElements()) {\n\n try {\n\n str = new StringTokenizer(br.readLine());\n\n } catch (IOException lastMonthOfVacation) {\n\n lastMonthOfVacation.printStackTrace();\n\n }\n\n\n\n }\n\n return str.nextToken();\n\n }\n\n\n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n\n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n String nextLine() {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n } catch (IOException lastMonthOfVacation) {\n\n lastMonthOfVacation.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1285","problem_id":"B","statement":"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\u2264l\u2264r\u2264n)(1\u2264l\u2264r\u2264n) 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,\u2026,rl,l+1,\u2026,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,\u22121][7,4,\u22121]. Yasser will buy all of them, the total tastiness will be 7+4\u22121=107+4\u22121=10. Adel can choose segments [7],[4],[\u22121],[7,4][7],[4],[\u22121],[7,4] or [4,\u22121][4,\u22121], their total tastinesses are 7,4,\u22121,117,4,\u22121,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\u2264t\u22641041\u2264t\u2264104). The description of the test cases follows.The first line of each test case contains nn (2\u2264n\u22641052\u2264n\u2264105).The second line of each test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (\u2212109\u2264ai\u2264109\u2212109\u2264ai\u2264109), 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\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5\nOutputCopyYES\nNO\nNO\nNoteIn 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.","tags":["dp","greedy","implementation"],"code":"\n\n\n\nimport java.io.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.io.PrintWriter;\n\nimport java.util.StringTokenizer;\n\n\n\npublic class JustEatIt {\n\n\n\n\tpublic static void main(String[] args) {\n\n\t\t\/\/ TODO Auto-generated method stub\n\n\t\tFastScanner fs = new FastScanner();\n\n\t\tPrintWriter pw = new PrintWriter(System.out);\n\n\t\tint T = fs.nextInt();\n\n\t\twhile (T-- > 0)\n\n\t\t{\n\n\t\t\tint N = fs.nextInt();\n\n\t\t\tlong[] arr = fs.readArray(N);\n\n\t\t\tlong Yasser = 0;\n\n\t\t\tfor (long ele : arr)\n\n\t\t\t{\n\n\t\t\t\tYasser += ele;\n\n\t\t\t}\n\n\t\t\tlong Abdel = Math.max(Kadane(arr,0, N - 2), Kadane(arr,1, N - 1));\n\n\t\t\tif (Yasser > Abdel)\n\n\t\t\t{\n\n\t\t\t\tpw.println(\"YES\");\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tpw.println(\"NO\");\n\n\t\t\t}\n\n\t\t\t\n\n\t\t}\n\n\t\n\n pw.close();\n\n\t}\n\n\t\n\n\t\n\n\tprivate static long Kadane(long[] arr, int start, int end)\n\n\t{\n\n\t\tlong sum = 0;\n\n\t\tlong max = Long.MIN_VALUE;\n\n\t\tfor (int i = start; i <= end; i++)\n\n\t\t{\n\n\t\t\tsum += arr[i];\n\n\t\t\tmax = Math.max(max, sum);\n\n\t\t if (sum < 0)\n\n\t\t {\n\n\t\t \tsum = 0;\n\n\t\t }\n\n\t\t}\n\n\t\t\n\n\t\treturn max;\n\n\t\t\n\n\t}\n\n\t\n\n\n\n\tprivate static class FastScanner {\n\n\t\t \n\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n StringTokenizer st = new StringTokenizer(\"\");\n\n \n\n public String next() {\n\n while (!st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n \n\n long[] readArray(int n) {\n\n long[] a = new long[n];\n\n for (int i = 0; i < n; i++) {\n\n a[i] = nextLong();\n\n }\n\n return a;\n\n }\n\n \n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n \n\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n \n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n}\n\n}\n\n","language":"java"} -{"contest_id":"1305","problem_id":"A","statement":"A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1\u2264t\u22641001\u2264t\u2264100) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100) \u00a0\u2014 the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226410001\u2264ai\u22641000) \u00a0\u2014 the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u226410001\u2264bi\u22641000) \u00a0\u2014 the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,\u2026,xnx1,x2,\u2026,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,\u2026,yny1,y2,\u2026,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,\u2026,xn+ynx1+y1,x2+y2,\u2026,xn+yn should all be distinct. The numbers x1,\u2026,xnx1,\u2026,xn should be equal to the numbers a1,\u2026,ana1,\u2026,an in some order, and the numbers y1,\u2026,yny1,\u2026,yn should be equal to the numbers b1,\u2026,bnb1,\u2026,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2\n3\n1 8 5\n8 4 5\n3\n1 7 5\n6 1 2\nOutputCopy1 8 5\n8 4 5\n5 1 7\n6 2 1\nNoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.","tags":["brute force","constructive algorithms","greedy","sortings"],"code":"import java.io.* ;\nimport java.util.* ;\n\n\n \npublic class App {\n public static void main (String[] args) throws java.lang.Exception {\n\t\tBufferedReader reader = new BufferedReader(new InputStreamReader(System.in));\n \/\/reader = new BufferedReader(new FileReader(new File(\"C:\\\\Users\\\\Anjali\\\\Desktop\\\\projects\\\\HelloWorld\\\\src\\\\input.txt\")));\n\t\tBufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));\n \/\/writer = new BufferedWriter(new FileWriter(new File(\"C:\\\\Users\\\\Anjali\\\\Desktop\\\\projects\\\\HelloWorld\\\\src\\\\output.txt\")));\n\t\t\/\/int tests = Integer.parseInt(reader.readLine());\n int tests = 1;\n\t\t\/\/StringBuilder sb = new StringBuilder(tests);\n\t\twhile (tests-- > 0){\n\t\t solve(reader, writer);\n writer.write(\"\\n\");\n\t\t}\n\t\treader.close();\n writer.flush();\n writer.close();\n }\n\n \n static void solve(BufferedReader reader, BufferedWriter writer) throws IOException {\n\t\tint tests = Integer.parseInt(reader.readLine());\n\t\tfor (int i = 0; i < tests; i++) {\n\t\t\tint n = Integer.parseInt(reader.readLine());\n\t\t\tint[] a = new int[n];\n\t\t\tint[] b = new int[n];\n\t\t\tString[] input = reader.readLine().split(\" \");\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\ta[j] = Integer.parseInt(input[j]);\n\t\t\t}\n\t\t\tString[] input1 = reader.readLine().split(\" \");\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tb[j] = Integer.parseInt(input1[j]);\n\t\t\t}\n\t\t\tArrays.sort(a);\n\t\t\tArrays.sort(b);\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\twriter.write(a[j] + \" \");\n\t\t\t}\n\t\t\twriter.write(\"\\n\");\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\twriter.write(b[j] + \" \");\n\t\t\t}\n\t\t\twriter.write(\"\\n\");\n\t\t}\n\t}\n}\n","language":"java"} -{"contest_id":"1304","problem_id":"A","statement":"A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x0)\n\n {\n\n int x = sc.nextInt();\n\n int y = sc.nextInt();\n\n int a = sc.nextInt();\n\n int b = sc.nextInt();\n\n if((int)Math.ceil((double)(y-x)\/(double)(a+b)) == ((y-x)\/(a+b)))\n\n System.out.println((y-x)\/(a+b));\n\n else System.out.println(\"-1\");\n\n t--;\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1301","problem_id":"D","statement":"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\u22122n\u22122m)(4nm\u22122n\u22122m) 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\u22121,j)(i\u22121,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j\u22121)(i,j\u22121); 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\u2264n,m\u22645001\u2264n,m\u2264500, 1\u2264k\u22641091\u2264k\u2264109), 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\u2264a\u226430001\u2264a\u22643000)\u00a0\u2014 the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1\u2264f\u22641091\u2264f\u2264109) 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\nOutputCopyYES\n2\n2 R\n2 L\nInputCopy3 3 1000000000\nOutputCopyNO\nInputCopy3 3 8\nOutputCopyYES\n3\n2 R\n2 D\n1 LLRR\nInputCopy4 4 9\nOutputCopyYES\n1\n3 RLD\nInputCopy3 4 16\nOutputCopyYES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D\nNoteThe 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):","tags":["constructive algorithms","graphs","implementation"],"code":"import java.util.*;\n\nimport java.io.*;\n\npublic class Main {\n\n static class Scan {\n\n private byte[] buf=new byte[1024];\n\n private int index;\n\n private InputStream in;\n\n private int total;\n\n public Scan()\n\n {\n\n in=System.in;\n\n }\n\n public int scan()throws IOException\n\n {\n\n if(total<0)\n\n throw new InputMismatchException();\n\n if(index>=total)\n\n {\n\n index=0;\n\n total=in.read(buf);\n\n if(total<=0)\n\n return -1;\n\n }\n\n return buf[index++];\n\n }\n\n public int scanInt()throws IOException\n\n {\n\n int integer=0;\n\n int n=scan();\n\n while(isWhiteSpace(n))\n\n n=scan();\n\n int neg=1;\n\n if(n=='-')\n\n {\n\n neg=-1;\n\n n=scan();\n\n }\n\n while(!isWhiteSpace(n))\n\n {\n\n if(n>='0'&&n<='9')\n\n {\n\n integer*=10;\n\n integer+=n-'0';\n\n n=scan();\n\n }\n\n else throw new InputMismatchException();\n\n }\n\n return neg*integer;\n\n }\n\n public double scanDouble()throws IOException\n\n {\n\n double doub=0;\n\n int n=scan();\n\n while(isWhiteSpace(n))\n\n n=scan();\n\n int neg=1;\n\n if(n=='-')\n\n {\n\n neg=-1;\n\n n=scan();\n\n }\n\n while(!isWhiteSpace(n)&&n!='.')\n\n {\n\n if(n>='0'&&n<='9')\n\n {\n\n doub*=10;\n\n doub+=n-'0';\n\n n=scan();\n\n }\n\n else throw new InputMismatchException();\n\n }\n\n if(n=='.')\n\n {\n\n n=scan();\n\n double temp=1;\n\n while(!isWhiteSpace(n))\n\n {\n\n if(n>='0'&&n<='9')\n\n {\n\n temp\/=10;\n\n doub+=(n-'0')*temp;\n\n n=scan();\n\n }\n\n else throw new InputMismatchException();\n\n }\n\n }\n\n return doub*neg;\n\n }\n\n public String scanString()throws IOException\n\n {\n\n StringBuilder sb=new StringBuilder();\n\n int n=scan();\n\n while(isWhiteSpace(n))\n\n n=scan();\n\n while(!isWhiteSpace(n))\n\n {\n\n sb.append((char)n);\n\n n=scan();\n\n }\n\n return sb.toString();\n\n }\n\n private boolean isWhiteSpace(int n)\n\n {\n\n if(n==' '||n=='\\n'||n=='\\r'||n=='\\t'||n==-1)\n\n return true;\n\n return false;\n\n }\n\n }\n\n static ArrayList adj_lst[];\n\n static boolean vis[];\n\n public static void main(String args[]) throws IOException {\n\n Scan input=new Scan();\n\n int n=input.scanInt();\n\n int m=input.scanInt();\n\n int k=input.scanInt();\n\n StringBuilder ans=new StringBuilder(\"\");\n\n int cnt=0;\n\n if(n==1) {\n\n if(k>=m-1) {\n\n ans.append((m-1)+\" \"+\"R\\n\");\n\n k-=m-1;\n\n cnt++;\n\n }\n\n else if(k>0) {\n\n ans.append(k+\" \"+\"R\\n\");\n\n k-=k;\n\n cnt++;\n\n }\n\n \n\n if(k>=m-1) {\n\n ans.append((m-1)+\" \"+\"L\\n\");\n\n k-=m-1;\n\n cnt++;\n\n }\n\n else if(k>0) {\n\n ans.append(k+\" \"+\"L\\n\");\n\n k-=k;\n\n cnt++;\n\n }\n\n if(k!=0) {\n\n System.out.println(\"NO\");\n\n return;\n\n }\n\n System.out.println(\"YES\\n\"+cnt+\"\\n\"+ans);\n\n return;\n\n }\n\n if(m==1) {\n\n if(k>=n-1) {\n\n ans.append((n-1)+\" \"+\"D\\n\");\n\n k-=n-1;\n\n cnt++;\n\n }\n\n else if(k>0) {\n\n ans.append(k+\" \"+\"D\\n\");\n\n k-=k;\n\n cnt++;\n\n }\n\n \n\n if(k>=n-1) {\n\n ans.append((n-1)+\" \"+\"U\\n\");\n\n k-=n-1;\n\n cnt++;\n\n }\n\n else if(k>0) {\n\n ans.append(k+\" \"+\"U\\n\");\n\n k-=k;\n\n cnt++;\n\n }\n\n if(k!=0) {\n\n System.out.println(\"NO\");\n\n return;\n\n }\n\n System.out.println(\"YES\\n\"+cnt+\"\\n\"+ans);\n\n return;\n\n }\n\n \n\n for(int i=1;i<=m\/2;i++) {\n\n if(i!=1) {\n\n if(k>=1) {\n\n if(k>=1) {\n\n ans.append(1+\" \"+\"R\\n\");\n\n k--;\n\n cnt++;\n\n }\n\n }\n\n else {\n\n break;\n\n }\n\n }\n\n if(k>=n-1) {\n\n ans.append(1+\" \"+\"D\\n\");\n\n k--;\n\n cnt++;\n\n int tmp_cnt=0;\n\n int j=1;\n\n boolean br=false;\n\n for(j=1;j<=n-2;j++) {\n\n if(k<3) {\n\n br=true;\n\n break;\n\n }\n\n tmp_cnt++;\n\n k-=3;\n\n }\n\n if(tmp_cnt>0) {\n\n ans.append(tmp_cnt+\" \"+\"RLD\\n\");\n\n cnt++;\n\n }\n\n if(br && k>0) {\n\n if(k==1) {\n\n ans.append(1+\" \"+\"R\\n\");\n\n k--;\n\n cnt++;\n\n }\n\n else if(k==2) {\n\n ans.append(1+\" \"+\"RL\\n\");\n\n k-=2;\n\n cnt++;\n\n }\n\n }\n\n }\n\n else if(k!=0) {\n\n ans.append(k+\" \"+\"D\\n\");\n\n k-=k;\n\n cnt++;\n\n }\n\n \n\n if(i!=1 && k>0) {\n\n ans.append(1+\" \"+\"L\\n\");\n\n k--;\n\n cnt++;\n\n } \n\n if(i!=1 && k>0) {\n\n ans.append(1+\" \"+\"R\\n\");\n\n k--;\n\n cnt++;\n\n } \n\n \n\n \n\n if(k==0) {\n\n break;\n\n }\n\n \n\n if(k>=1) {\n\n ans.append(1+\" \"+\"R\\n\");\n\n k--;\n\n cnt++;\n\n }\n\n \n\n if(k==0) {\n\n break;\n\n }\n\n if(m%2==0 && i==m\/2) {\n\n if(k>=n-1) {\n\n cnt++;\n\n k-=n-1;\n\n ans.append((n-1)+\" \"+\"U\\n\");\n\n }\n\n else if(k!=0){\n\n ans.append(k+\" \"+\"U\\n\");\n\n k-=k;\n\n cnt++;\n\n }\n\n }\n\n else {\n\n if(k>=n-1) {\n\n ans.append(1+\" \"+\"U\\n\");\n\n k--;\n\n cnt++;\n\n int tmp_cnt=0;\n\n int j=1;\n\n boolean br=false;\n\n for(j=1;j<=n-2;j++) {\n\n if(k<3) {\n\n br=true;\n\n break;\n\n }\n\n tmp_cnt++;\n\n k-=3;\n\n }\n\n if(tmp_cnt>0) {\n\n ans.append(tmp_cnt+\" \"+\"RLU\\n\");\n\n cnt++;\n\n }\n\n if(br && k>0) {\n\n if(k==1) {\n\n ans.append(1+\" \"+\"R\\n\");\n\n k--;\n\n cnt++;\n\n }\n\n else if(k==2) {\n\n ans.append(1+\" \"+\"RL\\n\");\n\n k-=2;\n\n cnt++;\n\n }\n\n }\n\n }\n\n else if(k!=0){\n\n ans.append(k+\" \"+\"U\\n\");\n\n k-=k;\n\n cnt++;\n\n }\n\n }\n\n \n\n if(k==0) {\n\n break;\n\n }\n\n \n\n if(k>=n-1) {\n\n ans.append((n-1)+\" \"+\"D\\n\");\n\n k-=n-1;\n\n cnt++;\n\n }\n\n else if(k!=0){\n\n ans.append(k+\" \"+\"D\\n\");\n\n k-=k;\n\n cnt++;\n\n }\n\n \n\n if(k==0) {\n\n break;\n\n }\n\n \n\n if(k>=1) {\n\n ans.append(1+\" \"+\"L\\n\");\n\n k--;\n\n cnt++;\n\n }\n\n \n\n if(k==0) {\n\n break;\n\n }\n\n \n\n if(k>=n-1) {\n\n ans.append((n-1)+\" \"+\"U\\n\");\n\n k-=n-1;\n\n cnt++;\n\n }\n\n else if(k!=0){\n\n ans.append(k+\" \"+\"U\\n\");\n\n k-=k;\n\n cnt++;\n\n }\n\n \n\n if(k==0) {\n\n break;\n\n }\n\n \n\n if(k>=1) {\n\n ans.append(1+\" \"+\"R\\n\");\n\n k--;\n\n cnt++;\n\n }\n\n }\n\n if(m%2==1) {\n\n if(k>=1) {\n\n ans.append(1+\" \"+\"R\\n\");\n\n k--;\n\n cnt++;\n\n }\n\n if(k>=n-1) {\n\n ans.append((n-1)+\" \"+\"D\\n\");\n\n k-=n-1;\n\n cnt++;\n\n }\n\n else if(k>0){\n\n ans.append(k+\" \"+\"D\\n\");\n\n k-=k;\n\n cnt++;\n\n }\n\n \n\n if(k>=1) {\n\n ans.append(1+\" \"+\"L\\n\");\n\n k--;\n\n cnt++;\n\n }\n\n \n\n if(k>=1) {\n\n ans.append(1+\" \"+\"R\\n\");\n\n k--;\n\n cnt++;\n\n }\n\n \n\n if(k>=n-1) {\n\n ans.append((n-1)+\" \"+\"U\\n\");\n\n k-=n-1;\n\n cnt++;\n\n }\n\n else if(k!=0) {\n\n ans.append(k+\" \"+\"U\\n\");\n\n k-=k;\n\n cnt++;\n\n }\n\n }\n\n if(k>=m-1) {\n\n ans.append((m-1)+\" \"+\"L\\n\");\n\n k-=m-1;\n\n cnt++;\n\n }\n\n else if(k!=0) {\n\n ans.append(k+\" \"+\"L\\n\");\n\n k-=k;\n\n cnt++;\n\n }\n\n if(k!=0) {\n\n System.out.println(\"NO\");\n\n return;\n\n }\n\n System.out.println(\"YES\\n\"+cnt+\"\\n\"+ans);\n\n }\n\n}\n\n","language":"java"} -{"contest_id":"1305","problem_id":"A","statement":"A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1\u2264t\u22641001\u2264t\u2264100) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100) \u00a0\u2014 the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226410001\u2264ai\u22641000) \u00a0\u2014 the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u226410001\u2264bi\u22641000) \u00a0\u2014 the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,\u2026,xnx1,x2,\u2026,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,\u2026,yny1,y2,\u2026,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,\u2026,xn+ynx1+y1,x2+y2,\u2026,xn+yn should all be distinct. The numbers x1,\u2026,xnx1,\u2026,xn should be equal to the numbers a1,\u2026,ana1,\u2026,an in some order, and the numbers y1,\u2026,yny1,\u2026,yn should be equal to the numbers b1,\u2026,bnb1,\u2026,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2\n3\n1 8 5\n8 4 5\n3\n1 7 5\n6 1 2\nOutputCopy1 8 5\n8 4 5\n5 1 7\n6 2 1\nNoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.","tags":["brute force","constructive algorithms","greedy","sortings"],"code":"import java.util.Arrays;\n\nimport java.util.Collections;\n\nimport java.util.Scanner;\n\n\n\npublic class kuroniAndGifts {\n\n\n\n\tpublic static void main(String[] args) {\n\n\t\tScanner s = new Scanner(System.in);\n\n\t\tint t = s.nextInt();\n\n\t\twhile(t-->0) {\n\n\t\t\tint n = s.nextInt();\n\n\t\t\tint arr1[] = new int[n];\n\n\t\t\tint arr2[] = new int[n];\n\n\t\t\tfor(int i = 0; i 0) {\n\n solve();\n\n }\n\n\n\n fw.out.close();\n\n }\n\n\n\n private static void solve() {\n\n\n\n int n = fs.nextInt(), a = fs.nextInt(), b = fs.nextInt(), k = fs.nextInt();\n\n Integer[] monsters_power = readIntArray(n);\n\n List list = new ArrayList<>();\n\n long sum = (long) a + b;\n\n for (long x : monsters_power) {\n\n long div = ceilDiv(x, sum);\n\n long diff = x - ((sum * div) - b);\n\n if (diff <= 0) {\n\n list.add(0L);\n\n continue;\n\n }\n\n long skip = ceilDiv(diff, a);\n\n list.add(skip);\n\n }\n\n\n\n Collections.sort(list);\n\n int ans = 0;\n\n for (long x : list) {\n\n k -= x;\n\n if (k < 0) break;\n\n ans++;\n\n }\n\n fw.out.println(ans);\n\n }\n\n\n\n private static class UnionFind {\n\n\n\n private final int[] parent;\n\n private final int[] rank;\n\n\n\n UnionFind(int n) {\n\n parent = new int[n + 5];\n\n rank = new int[n + 5];\n\n for (int i = 0; i <= n; i++) {\n\n parent[i] = i;\n\n rank[i] = 0;\n\n }\n\n }\n\n\n\n private int find(int i) {\n\n if (parent[i] == i)\n\n return i;\n\n return parent[i] = find(parent[i]);\n\n }\n\n\n\n private void union(int a, int b) {\n\n a = find(a);\n\n b = find(b);\n\n if (a != b) {\n\n if (rank[a] < rank[b]) {\n\n int temp = a;\n\n a = b;\n\n b = temp;\n\n }\n\n parent[b] = a;\n\n if (rank[a] == rank[b])\n\n rank[a]++;\n\n }\n\n }\n\n }\n\n\n\n private static long gcd(long a, long b) {\n\n return (b == 0 ? a : gcd(b, a % b));\n\n }\n\n\n\n private static long lcm(long a, long b) {\n\n return ((a * b) \/ gcd(a, b));\n\n }\n\n\n\n private static long pow(long a, long b, int mod) {\n\n long result = 1;\n\n while (b > 0) {\n\n if ((b & 1L) == 1) {\n\n result = (result * a) % mod;\n\n }\n\n a = (a * a) % mod;\n\n b >>= 1;\n\n }\n\n\n\n return result;\n\n }\n\n\n\n private static long ceilDiv(long a, long b) {\n\n return ((a + b - 1) \/ b);\n\n }\n\n\n\n private static long getMin(long... args) {\n\n long min = lMax;\n\n for (long arg : args)\n\n min = Math.min(min, arg);\n\n return min;\n\n }\n\n\n\n private static long getMax(long... args) {\n\n long max = lMin;\n\n for (long arg : args)\n\n max = Math.max(max, arg);\n\n return max;\n\n }\n\n\n\n private static boolean isPalindrome(String s, int l, int r) {\n\n\n\n int i = l, j = r;\n\n while (j - i >= 1) {\n\n if (s.charAt(i) != s.charAt(j))\n\n return false;\n\n i++;\n\n j--;\n\n }\n\n return true;\n\n }\n\n\n\n private static List primes(int n) {\n\n\n\n boolean[] primeArr = new boolean[n + 5];\n\n Arrays.fill(primeArr, true);\n\n for (int i = 2; (i * i) <= n; i++) {\n\n if (primeArr[i]) {\n\n for (int j = i * i; j <= n; j += i) {\n\n primeArr[j] = false;\n\n }\n\n }\n\n }\n\n\n\n List primeList = new ArrayList<>();\n\n for (int i = 2; i <= n; i++) {\n\n if (primeArr[i])\n\n primeList.add(i);\n\n }\n\n\n\n return primeList;\n\n }\n\n\n\n private static class Pair {\n\n\n\n private final U first;\n\n private final V second;\n\n\n\n @Override\n\n public boolean equals(Object o) {\n\n if (this == o) return true;\n\n if (o == null || getClass() != o.getClass()) return false;\n\n Pair pair = (Pair) o;\n\n return first.equals(pair.first) && second.equals(pair.second);\n\n }\n\n\n\n @Override\n\n public int hashCode() {\n\n return Objects.hash(first, second);\n\n }\n\n\n\n @Override\n\n public String toString() {\n\n return \"(\" + first + \", \" + second + \")\";\n\n }\n\n\n\n private Pair(U ff, V ss) {\n\n this.first = ff;\n\n this.second = ss;\n\n }\n\n }\n\n\n\n private static void randomizeArr(T[] arr, int n) {\n\n Random r = new Random();\n\n for (int i = (n - 1); i > 0; i--) {\n\n int j = r.nextInt(i + 1);\n\n swap(arr, i, j);\n\n }\n\n }\n\n\n\n private static Integer[] readIntArray(int n) {\n\n Integer[] arr = new Integer[n];\n\n for (int i = 0; i < n; i++)\n\n arr[i] = fs.nextInt();\n\n return arr;\n\n }\n\n\n\n private static List readIntList(int n) {\n\n List list = new ArrayList<>();\n\n for (int i = 0; i < n; i++)\n\n list.add(fs.nextInt());\n\n return list;\n\n }\n\n\n\n private static void swap(T[] arr, int i, int j) {\n\n T temp = arr[i];\n\n arr[i] = arr[j];\n\n arr[j] = temp;\n\n }\n\n\n\n private static void displayArr(T[] arr) {\n\n for (T x : arr)\n\n fw.out.print(x + \" \");\n\n fw.out.println();\n\n }\n\n\n\n private static void displayList(List list) {\n\n for (T x : list)\n\n fw.out.print(x + \" \");\n\n fw.out.println();\n\n }\n\n\n\n private static class FastScanner {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n FastScanner() throws IOException {\n\n if (checkOnlineJudge)\n\n this.br = new BufferedReader(new FileReader(\"src\/input.txt\"));\n\n else\n\n this.br = new BufferedReader(new InputStreamReader(System.in));\n\n\n\n this.st = new StringTokenizer(\"\");\n\n }\n\n\n\n public String next() {\n\n while (!st.hasMoreTokens()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException err) {\n\n err.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n public String nextLine() {\n\n if (st.hasMoreTokens()) {\n\n return st.nextToken(\"\").trim();\n\n }\n\n try {\n\n return br.readLine().trim();\n\n } catch (IOException err) {\n\n err.printStackTrace();\n\n }\n\n return \"\";\n\n }\n\n\n\n public int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n public long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n\n\n public double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n }\n\n\n\n private static class FastWriter {\n\n PrintWriter out;\n\n\n\n FastWriter() throws IOException {\n\n if (checkOnlineJudge)\n\n out = new PrintWriter(new FileWriter(\"src\/output.txt\"));\n\n else\n\n out = new PrintWriter(System.out);\n\n }\n\n }\n\n}\n\n","language":"java"} -{"contest_id":"1284","problem_id":"C","statement":"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\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n. This indicates the subsegment where l\u22121l\u22121 elements from the beginning and n\u2212rn\u2212r elements from the end are deleted from the sequence.For a permutation p1,p2,\u2026,pnp1,p2,\u2026,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,\u2026,pr}\u2212min{pl,pl+1,\u2026,pr}=r\u2212lmax{pl,pl+1,\u2026,pr}\u2212min{pl,pl+1,\u2026,pr}=r\u2212l. 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\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n, 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\u2264n\u22642500001\u2264n\u2264250000, 108\u2264m\u2264109108\u2264m\u2264109, mm is prime).OutputPrint rr (0\u2264r Arrays.sort(primitive) is O(n^2)\n --> Never use '=' to compare to Integer data types, instead use 'equals()'\n --> -4 % 3 = -1, actually it should be 2, so add '+n' to modulo result\n *\/\n\nimport java.io.*;\nimport java.util.*;\n\npublic class CodeForces {\n\n public static void main(String[] args) throws IOException {\n openIO();\n int testCase = 1;\n\/\/ testCase = sc. nextInt();\n for (int i = 1; i <= testCase; i++) solve(i);\n closeIO();\n }\n \/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*\/\n\n public static void solve(int tCase) throws IOException {\n int n = sc.nextInt();\n mod = sc.nextInt();\n _ncr_precompute(n);\n long ans = 0;\n for(int l = 0;l list = new ArrayList<>();\n for (int ele : arr) list.add(ele);\n Collections.sort(list);\n if (!isAscending) Collections.reverse(list);\n for (int i = 0; i < n; i++) arr[i] = list.get(i);\n }\n\n public static void _sort(long[] arr, boolean isAscending) {\n int n = arr.length;\n List list = new ArrayList<>();\n for (long ele : arr) list.add(ele);\n Collections.sort(list);\n if (!isAscending) Collections.reverse(list);\n for (int i = 0; i < n; i++) arr[i] = list.get(i);\n }\n\n \/\/ time : O(1), space : O(1)\n public static int _digitCount(long num,int base){\n \/\/ this will give the # of digits needed for a number num in format : base\n return (int)(1 + Math.log(num)\/Math.log(base));\n }\n\n \/\/ time : O(n), space: O(n)\n public static long _fact(int n){\n \/\/ simple factorial calculator\n long ans = 1;\n for(int i=2;i<=n;i++)\n ans = ans * i % mod;\n return ans;\n }\n\n \/\/ time for pre-computation of factorial and inverse-factorial table : O(nlog(mod))\n public static long[] factorial , inverseFact;\n public static void _ncr_precompute(int n){\n factorial = new long[n+1];\n inverseFact = new long[n+1];\n factorial[0] = inverseFact[0] = 1;\n for (int i = 1; i <=n; i++) {\n factorial[i] = (factorial[i - 1] * i) % mod;\n inverseFact[i] = _power(factorial[i], mod - 2);\n }\n }\n \/\/ time of factorial calculation after pre-computation is O(1)\n public static int _ncr(int n,int r){\n if(r > n)return 0;\n return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod);\n }\n public static int _npr(int n,int r){\n if(r > n)return 0;\n return (int)(factorial[n] * inverseFact[n - r] % mod);\n }\n\n\n \/\/ euclidean algorithm time O(max (loga ,logb))\n public static long _gcd(long a, long b) {\n if (a == 0)\n return b;\n return _gcd(b % a, a);\n }\n\n \/\/ lcm(a,b) * gcd(a,b) = a * b\n public static long _lcm(long a, long b) {\n return (a \/ _gcd(a, b)) * b;\n }\n\n \/\/ binary exponentiation time O(logn)\n public static long _power(long x, long n) {\n long ans = 1;\n while (n > 0) {\n if ((n & 1) == 1) {\n ans *= x;\n ans %= mod;\n n--;\n } else {\n x *= x;\n x %= mod;\n n >>= 1;\n }\n }\n return ans;\n }\n\n \/\/sieve or first divisor time : O(mx * log ( log (mx) ) )\n public static int[] _seive(int mx){\n int[] firstDivisor = new int[mx+1];\n for(int i=0;i<=mx;i++)firstDivisor[i] = i;\n for(int i=2;i*i<=mx;i++)\n if(firstDivisor[i] == i)\n for(int j = i*i;j<=mx;j+=i)\n firstDivisor[j] = i;\n return firstDivisor;\n }\n\n \/\/ check if x is a prime # of not. time : O( n ^ 1\/2 )\n private static boolean _isPrime(long x){\n for(long i=2;i*i<=x;i++)\n if(x%i==0)return false;\n return true;\n }\n\n static class Pair{\n K ff;\n V ss;\n\n public Pair(K ff, V ss) {\n this.ff = ff;\n this.ss = ss;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || this.getClass() != o.getClass()) return false;\n Pair pair = (Pair) o;\n return ff.equals(pair.ff) && ss.equals(pair.ss);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(ff, ss);\n }\n }\n\n static FastestReader sc;\n static PrintWriter out;\n\n private static void openIO() throws IOException {\n sc = new FastestReader();\n out = new PrintWriter(System.out);\n }\n \/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*\/\n\n public static void closeIO() throws IOException {\n out.flush();\n out.close();\n sc.close();\n }\n\n private static final class FastestReader {\n private static final int BUFFER_SIZE = 1 << 16;\n private final DataInputStream din;\n private final byte[] buffer;\n private int bufferPointer, bytesRead;\n\n public FastestReader() {\n din = new DataInputStream(System.in);\n buffer = new byte[BUFFER_SIZE];\n bufferPointer = bytesRead = 0;\n }\n\n public FastestReader(String file_name) throws IOException {\n din = new DataInputStream(new FileInputStream(file_name));\n buffer = new byte[BUFFER_SIZE];\n bufferPointer = bytesRead = 0;\n }\n\n private static boolean isSpaceChar(int c) {\n return !(c >= 33 && c <= 126);\n }\n\n private int skip() throws IOException {\n int b;\n \/\/noinspection StatementWithEmptyBody\n while ((b = read()) != -1 && isSpaceChar(b)) {\n }\n return b;\n }\n\n public String next() throws IOException {\n int b = skip();\n final StringBuilder sb = new StringBuilder();\n while (!isSpaceChar(b)) { \/\/ when nextLine, (isSpaceChar(b) && b != ' ')\n sb.appendCodePoint(b);\n b = read();\n }\n return sb.toString();\n }\n\n public int nextInt() throws IOException {\n int ret = 0;\n byte c = read();\n while (c <= ' ') {\n c = read();\n }\n final boolean neg = c == '-';\n if (neg) {\n c = read();\n }\n do {\n ret = ret * 10 + c - '0';\n } while ((c = read()) >= '0' && c <= '9');\n\n if (neg) {\n return -ret;\n }\n return ret;\n }\n\n public long nextLong() throws IOException {\n long ret = 0;\n byte c = read();\n while (c <= ' ') {\n c = read();\n }\n final boolean neg = c == '-';\n if (neg) {\n c = read();\n }\n do {\n ret = ret * 10 + c - '0';\n } while ((c = read()) >= '0' && c <= '9');\n if (neg) {\n return -ret;\n }\n return ret;\n }\n\n public double nextDouble() throws IOException {\n double ret = 0, div = 1;\n byte c = read();\n while (c <= ' ') {\n c = read();\n }\n final boolean neg = c == '-';\n if (neg) {\n c = read();\n }\n\n do {\n ret = ret * 10 + c - '0';\n } while ((c = read()) >= '0' && c <= '9');\n\n if (c == '.') {\n while ((c = read()) >= '0' && c <= '9') {\n ret += (c - '0') \/ (div *= 10);\n }\n }\n\n if (neg) {\n return -ret;\n }\n return ret;\n }\n\n private void fillBuffer() throws IOException {\n bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);\n if (bytesRead == -1) {\n buffer[0] = -1;\n }\n }\n\n private byte read() throws IOException {\n if (bufferPointer == bytesRead) {\n fillBuffer();\n }\n return buffer[bufferPointer++];\n }\n\n public void close() throws IOException {\n din.close();\n }\n }\n \/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*\/\n}","language":"java"} -{"contest_id":"1325","problem_id":"F","statement":"F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly \u2308n\u2212\u2212\u221a\u2309\u2308n\u2309 vertices. find a simple cycle of length at least \u2308n\u2212\u2212\u221a\u2309\u2308n\u2309. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5\u2264n\u22641055\u2264n\u2264105, n\u22121\u2264m\u22642\u22c5105n\u22121\u2264m\u22642\u22c5105)\u00a0\u2014 the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print \"1\", followed by a line containing \u2308n\u2212\u2212\u221a\u2309\u2308n\u2309 distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print \"2\", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6\n1 3\n3 4\n4 2\n2 6\n5 6\n5 1\nOutputCopy1\n1 6 4InputCopy6 8\n1 3\n3 4\n4 2\n2 6\n5 6\n5 1\n1 4\n2 5\nOutputCopy2\n4\n1 5 2 4InputCopy5 4\n1 2\n1 3\n2 4\n2 5\nOutputCopy1\n3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2\u22124\u22123\u22121\u22125\u221262\u22124\u22123\u22121\u22125\u22126 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2\u22125\u221262\u22125\u22126, for example, is acceptable.In the third sample:","tags":["constructive algorithms","dfs and similar","graphs","greedy"],"code":"import java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PrintWriter;\nimport java.util.Arrays;\nimport java.io.IOException;\nimport java.util.TreeSet;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.io.InputStream;\n\n\/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n *\/\npublic class Main {\n public static void main(String[] args) {\n InputStream inputStream = System.in;\n OutputStream outputStream = System.out;\n InputReader in = new InputReader(inputStream);\n PrintWriter out = new PrintWriter(outputStream);\n FEhabsLastTheorem solver = new FEhabsLastTheorem();\n solver.solve(1, in, out);\n out.close();\n }\n\n static class FEhabsLastTheorem {\n PrintWriter out;\n InputReader in;\n ArrayList[] graph;\n HashSet[] tset;\n int[] par;\n int[] dep;\n int max_cycle = 0;\n int start = 0;\n int end = 0;\n DSU ob;\n boolean[] visited;\n int[] tin;\n int[] low;\n int timer = 0;\n int[] cnt = new int[2];\n\n void dfs(int v, int p, int h) {\n dep[v] = h;\n for (int u : graph[v]) {\n if (dep[u] == -1) {\n par[u] = v;\n dfs(u, v, h + 1);\n } else if (u != par[v]) {\n if (dep[v] - dep[u] + 1 > max_cycle) {\n max_cycle = dep[v] - dep[u] + 1;\n start = v;\n end = u;\n }\n }\n }\n }\n\n void tarjan(int v, int p) {\n visited[v] = true;\n tin[v] = low[v] = timer++;\n for (int u : graph[v]) {\n int to = u;\n if (to == p) continue;\n if (visited[to]) {\n low[v] = Math.min(low[v], tin[to]);\n } else {\n tarjan(to, v);\n low[v] = Math.min(low[v], low[to]);\n if (low[to] > tin[v]) {\n \/\/its a bridge\n } else {\n ob.unite(to, v);\n }\n }\n }\n }\n\n void dfs2(int v, int p, int h) {\n dep[v] = h;\n cnt[h % 2]++;\n for (int u : tset[v]) {\n if (u != p)\n dfs2(u, v, h + 1);\n }\n }\n\n TreeSet MIS(int n) {\n TreeSet is = new TreeSet<>();\n TreeSet set = new TreeSet<>();\n int deg[] = new int[n + 1];\n for (int i = 0; i < n; ++i) {\n set.add(new Pair(graph[i].size(), i));\n deg[i] = graph[i].size();\n }\n while (!set.isEmpty()) {\n Pair v = set.pollFirst();\n for (int e : graph[v.y]) {\n if (set.contains(new Pair(deg[e], e))) {\n for (int f : graph[e]) {\n if (set.contains(new Pair(deg[f], f))) {\n set.remove(new Pair(deg[f], f));\n set.add(new Pair(--deg[f], f));\n }\n }\n set.remove(new Pair(deg[e], e));\n }\n }\n is.add(v.y);\n }\n return is;\n }\n\n public void solve(int testNumber, InputReader in, PrintWriter out) {\n this.out = out;\n this.in = in;\n int n = ni();\n int m = ni();\n visited = new boolean[n];\n low = new int[n];\n tin = new int[n];\n ob = new DSU(n);\n graph = new ArrayList[n];\n tset = new HashSet[n];\n par = new int[n];\n dep = new int[n];\n int sq = (int) Math.sqrt(n);\n if (sq * sq != n)\n sq++;\n int i = 0;\n for (i = 0; i < n; i++) {\n graph[i] = new ArrayList<>();\n tset[i] = new HashSet<>();\n }\n Arrays.fill(dep, -1);\n for (i = 0; i < m; i++) {\n int u = ni() - 1;\n int v = ni() - 1;\n graph[u].add(v);\n graph[v].add(u);\n }\n dfs(0, -1, 0);\n if (max_cycle >= sq) {\n pn(2);\n pn(max_cycle);\n ArrayList ans = new ArrayList<>();\n for (i = start; i != end; i = par[i])\n ans.add(i);\n ans.add(end);\n for (int x : ans)\n p(x + 1 + \" \");\n return;\n }\n if (n < 50) {\n TreeSet mis = MIS(n);\n pn(1);\n int c = 0;\n for (int x : mis) {\n p(x + 1 + \" \");\n c++;\n if (c == sq)\n break;\n }\n return;\n }\n tarjan(0, -1);\n int root = -1;\n HashSet hset = new HashSet<>();\n for (i = 0; i < n; i++) {\n int father = ob.find(i);\n for (int x : graph[i]) {\n int lull = ob.find(x);\n if (lull == father)\n continue;\n tset[lull].add(father);\n tset[father].add(lull);\n }\n hset.add(father);\n if (father == i)\n root = i;\n }\n\n dfs2(root, -1, 0);\n ArrayList ans = new ArrayList<>();\n pn(1);\n TreeSet good = new TreeSet<>();\n for (i = 0; i < n; i++)\n good.add(i);\n if (cnt[0] > cnt[1]) {\n int c = 0;\n for (int x : hset) {\n if (dep[x] % 2 == 0) {\n ans.add(x);\n good.remove(x);\n for (int y : graph[x]) {\n good.remove(y);\n }\n }\n if (ans.size() == sq)\n break;\n }\n } else {\n int c = 0;\n for (int x : hset) {\n if (dep[x] % 2 != 0) {\n ans.add(x);\n good.remove(x);\n for (int y : graph[x]) {\n good.remove(y);\n }\n }\n if (ans.size() == sq)\n break;\n }\n }\n while (ans.size() < sq) {\n int x = good.pollFirst();\n ans.add(x);\n for (int y : graph[x])\n good.remove(y);\n }\n for (int x : ans)\n p(x + 1 + \" \");\n }\n\n int ni() {\n return in.nextInt();\n }\n\n void pn(long zx) {\n out.println(zx);\n }\n\n void p(Object o) {\n out.print(o);\n }\n\n class DSU {\n int[] par;\n int[] sz;\n\n DSU(int n) {\n par = new int[n];\n sz = new int[n];\n int i = 0;\n for (i = 0; i < n; i++) {\n par[i] = i;\n sz[i] = 1;\n }\n }\n\n int find(int x) {\n if (par[x] != x)\n return par[x] = find(par[x]);\n return par[x];\n }\n\n void unite(int x, int y) {\n int x_root = find(x);\n int y_root = find(y);\n if (x_root == y_root)\n return;\n if (sz[x_root] <= sz[y_root]) {\n par[x_root] = y_root;\n sz[y_root] += sz[x_root];\n } else {\n par[y_root] = x_root;\n sz[x_root] += sz[y_root];\n }\n }\n\n }\n\n class Pair implements Comparable {\n int x;\n int y;\n\n Pair(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public int compareTo(Pair other) {\n if (this.x != other.x)\n return this.x - other.x;\n return this.y - other.y;\n }\n\n public String toString() {\n return \"(\" + x + \",\" + y + \")\";\n }\n\n }\n\n }\n\n static class InputReader {\n private InputStream stream;\n private byte[] buf = new byte[1024];\n private int curChar;\n private int numChars;\n\n public InputReader(InputStream stream) {\n this.stream = stream;\n }\n\n public int read() {\n if (numChars == -1)\n throw new UnknownError();\n if (curChar >= numChars) {\n curChar = 0;\n try {\n numChars = stream.read(buf);\n } catch (IOException e) {\n throw new UnknownError();\n }\n if (numChars <= 0)\n return -1;\n }\n return buf[curChar++];\n }\n\n public int nextInt() {\n return Integer.parseInt(next());\n }\n\n public String next() {\n int c = read();\n while (isSpaceChar(c))\n c = read();\n StringBuffer res = new StringBuffer();\n do {\n res.appendCodePoint(c);\n c = read();\n } while (!isSpaceChar(c));\n\n return res.toString();\n }\n\n private boolean isSpaceChar(int c) {\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n }\n\n }\n}\n\n","language":"java"} -{"contest_id":"1301","problem_id":"C","statement":"C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols \"0\" and \"1\"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to \"1\".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1\u2264l\u2264r\u2264|s|1\u2264l\u2264r\u2264|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,\u2026,srsl,sl+1,\u2026,sr is equal to \"1\". For example, if s=s=\"01010\" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to \"1\", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u22641051\u2264t\u2264105) \u00a0\u2014 the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1\u2264n\u22641091\u2264n\u2264109, 0\u2264m\u2264n0\u2264m\u2264n)\u00a0\u2014 the length of the string and the number of symbols equal to \"1\" in it.OutputFor every test case print one integer number\u00a0\u2014 the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to \"1\".ExampleInputCopy5\n3 1\n3 2\n3 3\n4 0\n5 2\nOutputCopy4\n5\n6\n0\n12\nNoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to \"1\". These strings are: s1=s1=\"100\", s2=s2=\"010\", s3=s3=\"001\". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is \"101\".In the third test case, the string ss with the maximum value is \"111\".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to \"1\" is \"0000\" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is \"01010\" and it is described as an example in the problem statement.","tags":["binary search","combinatorics","greedy","math","strings"],"code":"import java.io.*;\n\nimport java.util.*;\n\nimport java.awt.Point;\n\n\n\npublic class Ayubfunction {\n\n public static void main(String[] args) throws Exception {\n\n Scanner sc=new Scanner(System.in);\n\n StringBuilder sb=new StringBuilder();\n\n int t=sc.nextInt();\n\n while(t-->0){\n\n long n=sc.nextInt(),m=sc.nextInt();\n\n long zero=n-m;\n\n long k=zero\/(m+1);\n\n sb.append((n*(n+1)\/2)-((m+1)*k*(k+1)\/2)-((k+1)*(zero%(m+1)))+\"\\n\");\n\n }\n\n System.out.println(sb);\n\n }\n\n}","language":"java"} -{"contest_id":"1293","problem_id":"A","statement":"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\u2264t\u226410001\u2264t\u22641000)\u00a0\u2014 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\u2264n\u22641092\u2264n\u2264109, 1\u2264s\u2264n1\u2264s\u2264n, 1\u2264k\u2264min(n\u22121,1000)1\u2264k\u2264min(n\u22121,1000))\u00a0\u2014 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,\u2026,aka1,a2,\u2026,ak (1\u2264ai\u2264n1\u2264ai\u2264n)\u00a0\u2014 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\u00a0\u2014 the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77\nOutputCopy2\n0\n4\n0\n2\nNoteIn 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.","tags":["binary search","brute force","implementation"],"code":"import java.util.*;\n\nimport java.lang.*;\n\nimport java.io.*;\n\npublic class Main\n\n{\n\n static final PrintWriter out =new PrintWriter(System.out);\n\n static final FastReader sc = new FastReader();\n\n public static boolean sorted(int a[])\n\n {\n\n int n=a.length,i;\n\n int b[]=new int[n];\n\n for(i=0;i0)\n\n\t {\n\n\t int n=sc.nextInt();\n\n\t int s=sc.nextInt();\n\n\t int k=sc.nextInt();\n\n\t ArrayList arr=new ArrayList<>();\n\n\t int i;\n\n\t for(i=0;i=1 && !arr.contains(s-i))\n\n\t {\n\n\t System.out.println(i);\n\n\t continue label;\n\n\t }\n\n\t }\n\n\t }\n\n\t}\n\n\tpublic static int first(ArrayList arr, int low, int high, int x, int n)\n\n {\n\n if (high >= low) {\n\n int mid = low + (high - low) \/ 2;\n\n if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)\n\n return mid;\n\n else if (x > arr.get(mid))\n\n return first(arr, (mid + 1), high, x, n);\n\n else\n\n return first(arr, low, (mid - 1), x, n);\n\n }\n\n return -1;\n\n }\n\n\tpublic static int last(ArrayList arr, int low, int high, int x, int n)\n\n {\n\n if (high >= low) {\n\n int mid = low + (high - low) \/ 2;\n\n if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)\n\n return mid;\n\n else if (x < arr.get(mid))\n\n return last(arr, low, (mid - 1), x, n);\n\n else\n\n return last(arr, (mid + 1), high, x, n);\n\n }\n\n return -1;\n\n }\n\n\tpublic static int lis(int[] arr) {\n\n\tint n = arr.length;\n\n\tArrayList al = new ArrayList();\n\n\tal.add(arr[0]);\n\n\tfor(int i = 1 ; i=x) {\n\n\t\t\tal.add(arr[i]);\n\n\t\t}else {\n\n\t\t\tint v = upper_bound(al, 0, al.size(), arr[i]);\n\n\t\t\tal.set(v, arr[i]);\n\n\t\t}\n\n\t}\n\n\treturn al.size();\n\n}\n\n \n\n\tpublic static int lower_bound(ArrayList ar,int lo , int hi , long k)\n\n{\n\n Collections.sort(ar);\n\n int s=lo;\n\n int e=hi;\n\n while (s !=e)\n\n {\n\n int mid = s+e>>1;\n\n if (ar.get((int)mid) ar,int lo , int hi, int k)\n\n{\n\n Collections.sort(ar);\n\n int s=lo;\n\n int e=hi;\n\n while (s !=e)\n\n {\n\n int mid = s+e>>1;\n\n if (ar.get(mid) <=k)\n\n {\n\n s=mid+1;\n\n }\n\n else\n\n {\n\n e=mid;\n\n }\n\n }\n\n if(s==ar.size())\n\n {\n\n return -1;\n\n }\n\n return s;\n\n}\n\nstatic boolean isPrime(long N)\n\n {\n\n if (N<=1) return false; \n\n if (N<=3) return true; \n\n if (N%2 == 0 || N%3 == 0) return false; \n\n for (int i=5; i*i<=N; i=i+6) \n\n if (N%i == 0 || N%(i+2) == 0) \n\n return false; \n\n return true; \n\n }\n\n static int countBits(long a)\n\n {\n\n return (int)(Math.log(a)\/Math.log(2)+1);\n\n }\n\n \n\n static long fact(long N)\n\n { \n\n long mod=1000000007;\n\n long n=2; \n\n if(N<=1)return 1;\n\n else\n\n {\n\n for(int i=3; i<=N; i++)n=(n*i)%mod;\n\n }\n\n return n;\n\n }\n\n private static boolean isInteger(String s) {\n\n try {\n\n Integer.parseInt(s);\n\n } catch (NumberFormatException e) {\n\n return false;\n\n } catch (NullPointerException e) {\n\n return false;\n\n }\n\n return true;\n\n }\n\n private static long gcd(long a, long b) {\n\n if (b == 0)\n\n return a;\n\n return gcd(b, a % b);\n\n }\n\n private static long lcm(long a, long b) {\n\n return (a \/ gcd(a, b)) * b;\n\n }\n\n private static boolean isPalindrome(String str) {\n\n int i = 0, j = str.length() - 1;\n\n while (i < j)\n\n if (str.charAt(i++) != str.charAt(j--))\n\n return false;\n\n return true;\n\n }\n\n \n\n private static String reverseString(String str) {\n\n StringBuilder sb = new StringBuilder(str);\n\n return sb.reverse().toString();\n\n } \n\n\tstatic class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n \n\n public FastReader()\n\n {\n\n br = new BufferedReader(\n\n new InputStreamReader(System.in));\n\n }\n\n \n\n String next()\n\n {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n }\n\n catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n \n\n int nextInt() { return Integer.parseInt(next()); }\n\n \n\n long nextLong() { return Long.parseLong(next()); }\n\n \n\n double nextDouble()\n\n {\n\n return Double.parseDouble(next());\n\n }\n\n \n\n String nextLine()\n\n {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n }\n\n catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1307","problem_id":"A","statement":"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\u2264i,j\u2264n1\u2264i,j\u2264n) such that |i\u2212j|=1|i\u2212j|=1 and ai>0ai>0 and apply ai=ai\u22121ai=ai\u22121, 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\u2264t\u22641001\u2264t\u2264100) \u00a0\u2014 the number of test cases. Next 2t2t lines contain a description of test cases \u00a0\u2014 two lines per test case.The first line of each test case contains integers nn and dd (1\u2264n,d\u22641001\u2264n,d\u2264100) \u2014 the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u22641000\u2264ai\u2264100) \u00a0\u2014 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\n4 5\n1 0 3 2\n2 2\n100 1\n1 8\n0\nOutputCopy3\n101\n0\nNoteIn 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.","tags":["greedy","implementation"],"code":"import java.util.*;\n\nimport java.lang.*;\n\nimport java.io.*;\n\n\n\npublic class Main\n\n{\n\n static long mod = (int)1e9+7;\n\n\tpublic static void main (String[] args) throws java.lang.Exception\n\n\t{\n\n\t\tFastReader sc =new FastReader();\n\n\t\t\n\n\t int t=sc.nextInt();\n\n\t \n\n\t \/\/ int t=1;\n\n\t \n\n\t while(t-->0)\n\n\t {\n\n\t int n=sc.nextInt();\n\n\t int d=sc.nextInt();\n\n\t \n\n\t int arr[] = sc.readArray(n);\n\n\t \n\n\t for(int i=1;i>>8&0xff)+1]++;\n\n\t\t\tc2[(v>>>16&0xff)+1]++;\n\n\t\t\tc3[(v>>>24^0x80)+1]++;\n\n\t\t}\n\n\t\tfor(int i = 0;i < 0xff;i++) {\n\n\t\t\tc0[i+1] += c0[i];\n\n\t\t\tc1[i+1] += c1[i];\n\n\t\t\tc2[i+1] += c2[i];\n\n\t\t\tc3[i+1] += c3[i];\n\n\t\t}\n\n\t\tint[] t = new int[n];\n\n\t\tfor(int v : a)t[c0[v&0xff]++] = v;\n\n\t\tfor(int v : t)a[c1[v>>>8&0xff]++] = v;\n\n\t\tfor(int v : a)t[c2[v>>>16&0xff]++] = v;\n\n\t\tfor(int v : t)a[c3[v>>>24^0x80]++] = v;\n\n\t\treturn a;\n\n\t}\n\n\t\n\n\t\n\n \n\n public static HashMap sortByValue(HashMap hm)\n\n {\n\n \/\/ Create a list from elements of HashMap\n\n List > list =\n\n new LinkedList >(hm.entrySet());\n\n \n\n \/\/ Sort the list\n\n Collections.sort(list, new Comparator >() {\n\n public int compare(Map.Entry o1,\n\n Map.Entry o2)\n\n {\n\n return (o1.getValue()).compareTo(o2.getValue());\n\n }\n\n });\n\n \n\n \/\/ put data from sorted list to hashmap\n\n HashMap temp = new LinkedHashMap();\n\n for (Map.Entry aa : list) {\n\n temp.put(aa.getKey(), aa.getValue());\n\n }\n\n return temp;\n\n }\n\n \n\n static void leftRotate(int arr[], int d, int n)\n\n {\n\n for (int i = 0; i < d; i++)\n\n leftRotatebyOne(arr, n);\n\n }\n\n \n\n static void leftRotatebyOne(int arr[], int n)\n\n {\n\n int i, temp;\n\n temp = arr[0];\n\n for (i = 0; i < n - 1; i++)\n\n arr[i] = arr[i + 1];\n\n arr[n-1] = temp;\n\n \n\n }\n\n \n\n static boolean isPalindrome(String str)\n\n {\n\n \n\n \/\/ Pointers pointing to the beginning\n\n \/\/ and the end of the string\n\n int i = 0, j = str.length() - 1;\n\n \n\n \/\/ While there are characters to compare\n\n while (i < j) {\n\n \n\n \/\/ If there is a mismatch\n\n if (str.charAt(i) != str.charAt(j))\n\n return false;\n\n \n\n \/\/ Increment first pointer and\n\n \/\/ decrement the other\n\n i++;\n\n j--;\n\n }\n\n \n\n \/\/ Given string is a palindrome\n\n return true;\n\n }\n\n \n\n static boolean palindrome_array(char arr[], int n)\n\n {\n\n \/\/ Initialise flag to zero.\n\n int flag = 0;\n\n \n\n \/\/ Loop till array size n\/2.\n\n for (int i = 0; i <= n \/ 2 && n != 0; i++) {\n\n \n\n \/\/ Check if first and last element are different\n\n \/\/ Then set flag to 1.\n\n if (arr[i] != arr[n - i - 1]) {\n\n flag = 1;\n\n break;\n\n }\n\n }\n\n \n\n \/\/ If flag is set then print Not Palindrome\n\n \/\/ else print Palindrome.\n\n if (flag == 1)\n\n return false;\n\n else\n\n return true;\n\n }\n\n \n\n\tstatic boolean allElementsEqual(int[] arr,int n)\n\n\t{\n\n\t int z=0;\n\n\t for(int i=0;i a[i + 1]) {\n\n return false;\n\n }\n\n }\n\n \n\n return true;\n\n }\n\n \n\n \n\n \n\n static boolean isReverseSorted(int[] a)\n\n {\n\n for (int i = 0; i < a.length - 1; i++)\n\n {\n\n if (a[i] < a[i + 1]) {\n\n return false;\n\n }\n\n }\n\n \n\n return true;\n\n }\n\n \n\n static int[] rearrangeEvenAndOdd(int arr[], int n)\n\n {\n\n ArrayList list = new ArrayList<>();\n\n\t\t \n\n\t\t for(int i=0;ii).toArray();\n\n\t\t return array;\n\n }\n\n \n\n static long[] rearrangeEvenAndOddLong(long arr[], int n)\n\n {\n\n ArrayList list = new ArrayList<>();\n\n\t\t \n\n\t\t for(int i=0;ii).toArray();\n\n\t\t return array;\n\n }\n\n\t\n\n\t\n\n \n\n static boolean isPrime(long n)\n\n {\n\n \n\n \/\/ Check if number is less than\n\n \/\/ equal to 1\n\n if (n <= 1)\n\n return false;\n\n \n\n \/\/ Check if number is 2\n\n else if (n == 2)\n\n return true;\n\n \n\n \/\/ Check if n is a multiple of 2\n\n else if (n % 2 == 0)\n\n return false;\n\n \n\n \/\/ If not, then just check the odds\n\n for (long i = 3; i <= Math.sqrt(n); i += 2)\n\n {\n\n if (n % i == 0)\n\n return false;\n\n }\n\n return true;\n\n }\n\n \n\n static int getSum(int n)\n\n { \n\n int sum = 0;\n\n \n\n while (n != 0)\n\n {\n\n sum = sum + n % 10;\n\n n = n\/10;\n\n }\n\n \n\n return sum;\n\n }\n\n \n\n static int gcd(int a, int b)\n\n {\n\n if (b == 0)\n\n return a;\n\n return gcd(b, a % b);\n\n }\n\n \n\n static long gcdLong(long a, long b)\n\n {\n\n if (b == 0)\n\n return a;\n\n return gcdLong(b, a % b);\n\n }\n\n \n\n static void swap(int i, int j)\n\n {\n\n int temp = i;\n\n i = j;\n\n j = temp;\n\n }\n\n\t\n\n\tstatic int countDigit(long n)\n\n {\n\n return (int)Math.floor(Math.log10(n) + 1);\n\n }\n\n\t\n\n}","language":"java"} -{"contest_id":"1288","problem_id":"B","statement":"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\u2264a\u2264A1\u2264a\u2264A, 1\u2264b\u2264B1\u2264b\u2264B, and the equation a\u22c5b+a+b=conc(a,b)a\u22c5b+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\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.Each test case contains two integers AA and BB (1\u2264A,B\u2264109)(1\u2264A,B\u2264109).OutputPrint one integer \u2014 the number of pairs (a,b)(a,b) such that 1\u2264a\u2264A1\u2264a\u2264A, 1\u2264b\u2264B1\u2264b\u2264B, and the equation a\u22c5b+a+b=conc(a,b)a\u22c5b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1\n0\n1337\nNoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1\u22c59=191+9+1\u22c59=19).","tags":["math"],"code":"\n\nimport java.io.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.util.StringTokenizer;\n\n\n\npublic class MemeProb {\n\n\n\n public static void main(String[] args) throws IOException {\n\n BufferedReader r = new BufferedReader(new InputStreamReader(System.in));\n\n\n\n var st = new StringTokenizer(r.readLine());\n\n var t = Integer.parseInt(st.nextToken());\n\n for (int i = 0; i < t; i++) {\n\n st = new StringTokenizer(r.readLine());\n\n var first = Integer.parseInt(st.nextToken());\n\n var str = st.nextToken();\n\n var len = Long.valueOf(str.length()-1);\n\n var count = 0;\n\n for (char j : str.toCharArray()) {\n\n if (j=='9') {\n\n count++;\n\n }\n\n }\n\n if(count==str.length()) {\n\n len++;\n\n }\n\n System.out.println(first*len);\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1296","problem_id":"D","statement":"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\u2264n\u22642\u22c5105,1\u2264a,b,k\u22641091\u2264n\u22642\u22c5105,1\u2264a,b,k\u2264109) \u2014 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,\u2026,hnh1,h2,\u2026,hn (1\u2264hi\u22641091\u2264hi\u2264109), where hihi is the health points of the ii-th monster.OutputPrint one integer \u2014 the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3\n7 10 50 12 1 8\nOutputCopy5\nInputCopy1 1 100 99\n100\nOutputCopy1\nInputCopy7 4 2 1\n1 3 5 4 2 7 6\nOutputCopy6\n","tags":["greedy","sortings"],"code":"import static java.lang.Math.max;\n\nimport static java.lang.Math.min;\n\nimport static java.lang.Math.abs;\n\n\n\nimport java.util.*;\n\nimport java.io.*;\n\nimport java.math.*;\n\n\n\n\n\npublic class D_Fight_with_Monsters {\n\n static long mod = Long.MAX_VALUE;\n\n\n\n public static void main(String[] args) {\n\n OutputStream outputStream = System.out;\n\n PrintWriter out = new PrintWriter(outputStream);\n\n FastReader f = new FastReader();\n\n int t = 1;\n\n\n\n while(t-- > 0){\n\n solve(f, out);\n\n }\n\n\n\n\n\n\n\n out.close();\n\n }\n\n\n\n\n\n public static void solve(FastReader f, PrintWriter out) {\n\n int n = f.nextInt();\n\n long a = f.nextLong();\n\n long b = f.nextLong();\n\n long k = f.nextLong();\n\n long arr[] = f.nextArray(n);\n\n\n\n long used[] = new long[n];\n\n for(int i = 0; i < n; i++) {\n\n long rem = arr[i]%(a+b);\n\n if(rem == 0) {\n\n rem = a+b;\n\n }\n\n used[i] = (rem+a-1)\/a - 1;\n\n }\n\n\n\n \/\/ for(int i = 0; i < n; i++) {\n\n \/\/ out.print(used[i] + \" \");\n\n \/\/ }\n\n \/\/ out.println();\n\n\n\n sort(used);\n\n int point = 0;\n\n for(int i = 0; i < n; i++) {\n\n if(k-used[i] >= 0) {\n\n point++;\n\n k -= used[i];\n\n } else {\n\n break;\n\n }\n\n }\n\n\n\n out.println(point);\n\n \n\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n \/\/ Sort an array\n\n public static void sort(long arr[]) {\n\n ArrayList al = new ArrayList<>();\n\n for(long i: arr) {\n\n al.add(i);\n\n }\n\n Collections.sort(al);\n\n for(int i = 0; i < arr.length; i++) {\n\n arr[i] = al.get(i);\n\n }\n\n }\n\n\n\n \/\/ Find all divisors of n\n\n public static void allDivisors(int n) {\n\n for(int i = 1; i*i <= n; i++) {\n\n if(n%i == 0) {\n\n System.out.println(i + \" \");\n\n if(i != n\/i) {\n\n System.out.println(n\/i + \" \");\n\n }\n\n }\n\n }\n\n }\n\n\n\n \/\/ Check if n is prime or not\n\n public static boolean isPrime(int n) {\n\n if(n < 1) return false;\n\n if(n == 2 || n == 3) return true;\n\n if(n % 2 == 0 || n % 3 == 0) return false;\n\n for(int i = 5; i*i <= n; i += 6) {\n\n if(n % i == 0 || n % (i+2) == 0) {\n\n return false;\n\n }\n\n }\n\n return true;\n\n }\n\n\n\n \/\/ Find gcd of a and b\n\n public static long gcd(long a, long b) {\n\n long dividend = a > b ? a : b;\n\n long divisor = a < b ? a : b;\n\n \n\n while(divisor > 0) {\n\n long reminder = dividend % divisor;\n\n dividend = divisor;\n\n divisor = reminder;\n\n }\n\n return dividend;\n\n }\n\n\n\n \/\/ Find lcm of a and b\n\n public static long lcm(long a, long b) {\n\n long lcm = gcd(a, b);\n\n long hcf = (a * b) \/ lcm;\n\n return hcf;\n\n }\n\n\n\n \/\/ Find factorial in O(n) time\n\n public static long fact(int n) {\n\n long res = 1;\n\n for(int i = 2; i <= n; i++) {\n\n res = res * i;\n\n }\n\n return res;\n\n }\n\n\n\n \/\/ Find power in O(logb) time\n\n public static long power(long a, long b) {\n\n long res = 1;\n\n while(b > 0) {\n\n if((b&1) == 1) {\n\n res = (res * a)%mod;\n\n }\n\n a = (a * a)%mod;\n\n b >>= 1;\n\n }\n\n return res;\n\n }\n\n\n\n \/\/ Find nCr\n\n public static long nCr(int n, int r) {\n\n if(r < 0 || r > n) {\n\n return 0;\n\n }\n\n long ans = fact(n) \/ (fact(r) * fact(n-r));\n\n return ans;\n\n }\n\n\n\n \/\/ Find nPr\n\n public static long nPr(int n, int r) {\n\n if(r < 0 || r > n) {\n\n return 0;\n\n }\n\n long ans = fact(n) \/ fact(r);\n\n return ans;\n\n }\n\n\n\n\n\n \/\/ sort all characters of a string\n\n public static String sortString(String inputString) {\n\n char tempArray[] = inputString.toCharArray();\n\n Arrays.sort(tempArray);\n\n return new String(tempArray);\n\n }\n\n\n\n \/\/ User defined class for fast I\/O\n\n static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n \n\n public FastReader() {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n \n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n }\n\n catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n boolean hasNext() {\n\n if (st != null && st.hasMoreTokens()) {\n\n return true;\n\n }\n\n String tmp;\n\n try {\n\n br.mark(1000);\n\n tmp = br.readLine();\n\n if (tmp == null) {\n\n return false;\n\n }\n\n br.reset();\n\n } catch (IOException e) {\n\n return false;\n\n }\n\n return true;\n\n }\n\n \n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n \n\n long nextLong() {\n\n return Long.parseLong(next()); \n\n }\n\n \n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n \n\n float nextFloat() {\n\n return Float.parseFloat(next());\n\n }\n\n \n\n boolean nextBoolean() {\n\n return Boolean.parseBoolean(next());\n\n }\n\n \n\n String nextLine() {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n }\n\n catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n\n\n long[] nextArray(int n) {\n\n long[] a = new long[n];\n\n for(int i=0; i 94 ^ 126 ~\n\n 31 US (unit separator) 63 ? 95 _ 127 DEL\n\n *\/\n\n\n\n\n\n \n\n\/\/ (a\/b)%mod == (a * moduloInverse(b)) % mod;\n\n\/\/ moduloInverse(b) = power(b, mod-2);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","language":"java"} -{"contest_id":"1286","problem_id":"B","statement":"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\u00a0\u2014 the number of vertices jj in the subtree of vertex ii, such that aj{\n\n\t\tint i,val;\n\n\t\tnode(int ii,int v){\n\n\t\t\ti=ii;val=v;\n\n\t\t}\n\n\t\t@Override\n\n\t\tpublic int compareTo(node o) {\n\n\t\t\tif(val==o.val)return i-o.i;\n\n\t\t\treturn val-o.val;\n\n\t\t}\n\n\t\tpublic String toString() {return i+\" \"+val;}\n\n\t}\n\n\tstatic LinkedListchildren[];\n\n\tstatic int[]cnt;\n\n\tstatic boolean ok=true;\n\n\tstatic int[]empty=new int[1];\n\n\tstatic ArrayList dfs(int i) {\n\n\t\tif(!ok) {\n\n\t\t\treturn new ArrayList();\n\n\t\t}\n\n\t\tif(children[i].size()==0) {\n\n\t\t\tif(cnt[i]>0) {\n\n\t\t\t\tok=false;\n\n\t\t\t\treturn new ArrayList();\n\n\t\t\t}\n\n\t\t\tArrayListarr=new ArrayList();\n\n\t\t\tarr.add(new node(i, 1));\n\n\t\t\treturn arr;\n\n\t\t}\n\n\t\tArrayListarr=new ArrayList();\n\n\t\tfor(int j:children[i]) {\n\n\t\t\tArrayListchild=dfs(j);\n\n\t\t\tfor(node n:child) {\n\n\t\t\t\tarr.add(n);\n\n\t\t\t}\n\n\t\t}\n\n\t\tif(cnt[i]>arr.size()) {\n\n\t\t\tok=false;\n\n\t\t\treturn new ArrayList();\n\n\t\t}\n\n\t\tCollections.sort(arr);\n\n\t\t\/\/System.out.println(i+\" \"+arr);\n\n\t\tint val;\n\n\t\tif(cnt[i]==0)val=1;\n\n\t\telse {\n\n\t\t\tval=arr.get(cnt[i]-1).val+1;\n\n\t\t}\n\n\t\tif(cnt[i]();\n\n\t\tfor(int i=0;ians=dfs(root);\n\n\t\t\/\/System.out.println(ans);\n\n\t\tif(!ok) {\n\n\t\t\tpw.println(\"NO\");\n\n\t\t\tpw.flush();\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tpw.println(\"YES\");\n\n\t\tint[]vals=new int[n];\n\n\t\tfor(node x:ans) {\n\n\t\t\tvals[x.i]=x.val;\n\n\t\t}\n\n\t\tfor(int i:vals)pw.println(i);\n\n\t\tpw.flush();\n\n\t}\n\n\tstatic class MScanner {\n\n\t\tStringTokenizer st;\n\n\t\tBufferedReader br;\n\n\t\tpublic MScanner(InputStream system) {\n\n\t\t\tbr = new BufferedReader(new InputStreamReader(system));\n\n\t\t}\n\n \n\n\t\tpublic MScanner(String file) throws Exception {\n\n\t\t\tbr = new BufferedReader(new FileReader(file));\n\n\t\t}\n\n \n\n\t\tpublic String next() throws IOException {\n\n\t\t\twhile (st == null || !st.hasMoreTokens())\n\n\t\t\t\tst = new StringTokenizer(br.readLine());\n\n\t\t\treturn st.nextToken();\n\n\t\t}\n\n\t\tpublic int[] takearr(int n) throws IOException {\n\n\t int[]in=new int[n];for(int i=0;i2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers\u00a0\u2014 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\n8 8 0 0\n1 10 0 3\n17 31 10 4\n2 1 0 0\n5 10 3 9\n10 10 4 8\nOutputCopy56\n6\n442\n1\n45\n80\nNoteIn the first test case; the screen resolution is 8\u00d788\u00d78, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. ","tags":["implementation"],"code":"import static java.lang.Math.max;\n\nimport static java.lang.Math.min;\n\nimport static java.lang.Math.abs;\n\nimport static java.lang.System.out;\n\nimport java.util.*;\n\nimport java.io.*;\n\nimport java.math.*;\n\n\/*\n\n-> Give your 100%, that's it!\n\n-> Rule To Solve Any Problem:\n\n 1. Read the problem.\n\n 2. Think About It.\n\n 3. Solve it!\n\n*\/\n\n\n\npublic class Template {\n\n \n\n\tstatic int mod = 1000000007;\n\n\n\n\tpublic static void main(String[] args){\n\n FastScanner sc = new FastScanner();\n\n PrintWriter out = new PrintWriter(System.out);\n\n int yo = sc.nextInt();\n\n while (yo-- > 0) {\n\n int a = sc.nextInt(), b = sc.nextInt();\n\n int x = sc.nextInt(), y = sc.nextInt();\n\n int up = x * b;\n\n int down =(a-x-1) * b;\n\n int left = a * y;\n\n int right = a * (b-y-1);\n\n out.println(max(max(up,down),max(left,right)));\n\n }\n\n out.close();\n\n\t}\n\n \n\n \n\n \n\n \n\n \/*\n\n Source: hu_tao\n\n Random stuff to try when stuck:\n\n -if it's 2C then it's dp\n\n -for combo\/probability problems, expand the given form we're interested in\n\n -make everything the same then build an answer (constructive, make everything 0 then do something)\n\n -something appears in parts of 2 --> model as graph\n\n -assume a greedy then try to show why it works\n\n -find way to simplify into one variable if multiple exist\n\n -treat it like fmc (note any passing thoughts\/algo that could be used so you can revisit them)\n\n -find lower and upper bounds on answer\n\n -figure out what ur trying to find and isolate it\n\n -see what observations you have and come up with more continuations\n\n -work backwards (in constructive, go from the goal to the start)\n\n -turn into prefix\/suffix sum argument (often works if problem revolves around adjacent array elements)\n\n -instead of solving for answer, try solving for complement (ex, find n-(min) instead of max)\n\n -draw something\n\n -simulate a process\n\n -dont implement something unless if ur fairly confident its correct\n\n -after 3 bad submissions move on to next problem if applicable\n\n -do something instead of nothing and stay organized\n\n -write stuff down\n\n Random stuff to check when wa:\n\n -if code is way too long\/cancer then reassess\n\n -switched N\/M\n\n -int overflow\n\n -switched variables\n\n -wrong MOD\n\n -hardcoded edge case incorrectly\n\n Random stuff to check when tle:\n\n -continue instead of break\n\n -condition in for\/while loop bad\n\n Random stuff to check when rte:\n\n -switched N\/M\n\n -long to int\/int overflow\n\n -division by 0\n\n -edge case for empty list\/data structure\/N=1\n\n *\/\n\n\n\n\tpublic static class Pair {\n\n\t\tint x;\n\n\t\tint y;\n\n\n\n\t\tpublic Pair(int x, int y) {\n\n\t\t\tthis.x = x;\n\n\t\t\tthis.y = y;\n\n\t\t}\n\n\t}\n\n\n\n\tpublic static void sort(int[] arr) {\n\n\t\tArrayList ls = new ArrayList();\n\n\t\tfor (int x : arr)\n\n\t\t\tls.add(x);\n\n\t\tCollections.sort(ls);\n\n\t\tfor (int i = 0; i < arr.length; i++)\n\n\t\t\tarr[i] = ls.get(i);\n\n\t}\n\n\n\n\tpublic static long gcd(long a, long b) {\n\n\t\tif (b == 0)\n\n\t\t\treturn a;\n\n\t\treturn gcd(b, a % b);\n\n\t}\n\n\n\n\tstatic boolean[] sieve(int N) {\n\n\t\tboolean[] sieve = new boolean[N + 1];\n\n\t\tfor (int i = 2; i <= N; i++)\n\n\t\t\tsieve[i] = true;\n\n\n\n\t\tfor (int i = 2; i <= N; i++) {\n\n\t\t\tif (sieve[i]) {\n\n\t\t\t\tfor (int j = 2 * i; j <= N; j += i) {\n\n\t\t\t\t\tsieve[j] = false;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn sieve;\n\n\t}\n\n\n\n\tpublic static long power(long x, long y, long p) {\n\n\t\tlong res = 1L;\n\n\t\tx = x % p;\n\n\t\twhile (y > 0) {\n\n\t\t\tif ((y & 1) == 1)\n\n\t\t\t\tres = (res * x) % p;\n\n\t\t\ty >>= 1;\n\n\t\t\tx = (x * x) % p;\n\n\t\t}\n\n\t\treturn res;\n\n\t}\n\n\n\n\tpublic static void print(int[] arr) {\n\n\t\t\/\/for debugging only\n\n\t\tfor (int x : arr)\n\n\t\t\tout.print(x + \" \");\n\n\t\tout.println();\n\n\t}\n\n\n\n\tstatic class FastScanner {\n\n\t\tprivate int BS = 1 << 16;\n\n\t\tprivate char NC = (char) 0;\n\n\t\tprivate byte[] buf = new byte[BS];\n\n\t\tprivate int bId = 0, size = 0;\n\n\t\tprivate char c = NC;\n\n\t\tprivate double cnt = 1;\n\n\t\tprivate BufferedInputStream in;\n\n\n\n\t\tpublic FastScanner() {\n\n\t\t\tin = new BufferedInputStream(System.in, BS);\n\n\t\t}\n\n\n\n\t\tpublic FastScanner(String s) {\n\n\t\t\ttry {\n\n\t\t\t\tin = new BufferedInputStream(new FileInputStream(new File(s)), BS);\n\n\t\t\t} catch (Exception e) {\n\n\t\t\t\tin = new BufferedInputStream(System.in, BS);\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tprivate char getChar() {\n\n\t\t\twhile (bId == size) {\n\n\t\t\t\ttry {\n\n\t\t\t\t\tsize = in.read(buf);\n\n\t\t\t\t} catch (Exception e) {\n\n\t\t\t\t\treturn NC;\n\n\t\t\t\t}\n\n\t\t\t\tif (size == -1)\n\n\t\t\t\t\treturn NC;\n\n\t\t\t\tbId = 0;\n\n\t\t\t}\n\n\t\t\treturn (char) buf[bId++];\n\n\t\t}\n\n\n\n\t\tpublic int nextInt() {\n\n\t\t\treturn (int) nextLong();\n\n\t\t}\n\n\n\n\t\tpublic int[] readInts(int N) {\n\n\t\t\tint[] res = new int[N];\n\n\t\t\tfor (int i = 0; i < N; i++) {\n\n\t\t\t\tres[i] = (int) nextLong();\n\n\t\t\t}\n\n\t\t\treturn res;\n\n\t\t}\n\n\n\n\t\tpublic long[] readLongs(int N) {\n\n\t\t\tlong[] res = new long[N];\n\n\t\t\tfor (int i = 0; i < N; i++) {\n\n\t\t\t\tres[i] = nextLong();\n\n\t\t\t}\n\n\t\t\treturn res;\n\n\t\t}\n\n\n\n\t\tpublic long nextLong() {\n\n\t\t\tcnt = 1;\n\n\t\t\tboolean neg = false;\n\n\t\t\tif (c == NC)\n\n\t\t\t\tc = getChar();\n\n\t\t\tfor (; (c < '0' || c > '9'); c = getChar()) {\n\n\t\t\t\tif (c == '-')\n\n\t\t\t\t\tneg = true;\n\n\t\t\t}\n\n\t\t\tlong res = 0;\n\n\t\t\tfor (; c >= '0' && c <= '9'; c = getChar()) {\n\n\t\t\t\tres = (res << 3) + (res << 1) + c - '0';\n\n\t\t\t\tcnt *= 10;\n\n\t\t\t}\n\n\t\t\treturn neg ? -res : res;\n\n\t\t}\n\n\n\n\t\tpublic double nextDouble() {\n\n\t\t\tdouble cur = nextLong();\n\n\t\t\treturn c != '.' ? cur : cur + nextLong() \/ cnt;\n\n\t\t}\n\n\n\n\t\tpublic double[] readDoubles(int N) {\n\n\t\t\tdouble[] res = new double[N];\n\n\t\t\tfor (int i = 0; i < N; i++) {\n\n\t\t\t\tres[i] = nextDouble();\n\n\t\t\t}\n\n\t\t\treturn res;\n\n\t\t}\n\n\n\n\t\tpublic String next() {\n\n\t\t\tStringBuilder res = new StringBuilder();\n\n\t\t\twhile (c <= 32)\n\n\t\t\t\tc = getChar();\n\n\t\t\twhile (c > 32) {\n\n\t\t\t\tres.append(c);\n\n\t\t\t\tc = getChar();\n\n\t\t\t}\n\n\t\t\treturn res.toString();\n\n\t\t}\n\n\n\n\t\tpublic String nextLine() {\n\n\t\t\tStringBuilder res = new StringBuilder();\n\n\t\t\twhile (c <= 32)\n\n\t\t\t\tc = getChar();\n\n\t\t\twhile (c != '\\n') {\n\n\t\t\t\tres.append(c);\n\n\t\t\t\tc = getChar();\n\n\t\t\t}\n\n\t\t\treturn res.toString();\n\n\t\t}\n\n\n\n\t\tpublic boolean hasNext() {\n\n\t\t\tif (c > 32)\n\n\t\t\t\treturn true;\n\n\t\t\twhile (true) {\n\n\t\t\t\tc = getChar();\n\n\t\t\t\tif (c == NC)\n\n\t\t\t\t\treturn false;\n\n\t\t\t\telse if (c > 32)\n\n\t\t\t\t\treturn true;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\t\/\/\tFor Input.txt and Output.txt\t\n\n\t\/\/\tFileInputStream in = new FileInputStream(\"input.txt\");\n\n\t\/\/\tFileOutputStream out = new FileOutputStream(\"output.txt\");\n\n\t\/\/\tPrintWriter pw = new PrintWriter(out);\n\n\t\/\/\tScanner sc = new Scanner(in);\n\n}","language":"java"} -{"contest_id":"1141","problem_id":"G","statement":"G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n\u22121n\u22121 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right \u2014 the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2\u2264n\u2264200000,0\u2264k\u2264n\u221212\u2264n\u2264200000,0\u2264k\u2264n\u22121) \u2014 the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n\u22121n\u22121 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1\u2264r\u2264n\u221211\u2264r\u2264n\u22121). In the second line print n\u22121n\u22121 numbers c1,c2,\u2026,cn\u22121c1,c2,\u2026,cn\u22121 (1\u2264ci\u2264r1\u2264ci\u2264r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2\n1 4\n4 3\n3 5\n3 6\n5 2\nOutputCopy2\n1 2 1 1 2 InputCopy4 2\n3 1\n1 4\n1 2\nOutputCopy1\n1 1 1 InputCopy10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9\nOutputCopy3\n1 1 2 3 2 3 1 3 1 ","tags":["binary search","constructive algorithms","dfs and similar","graphs","greedy","trees"],"code":"\/*\n\n Author: Anthony Ngene\n\n Created: 06\/10\/2020 - 07:03\n\n*\/\n\n\n\nimport java.io.*;\n\nimport java.util.*;\n\n\n\npublic class G {\n\n\/\/ checks: 1. edge cases 2. overflow 3. possible errors (e.g 1\/0, arr[out]) 4. time\/space complexity\n\n void solver() throws IOException {\n\n int n = in.intNext(), k = in.intNext();\n\n int[] nodes = new int[n + 1];\n\n ArrayList[] adj = new ArrayList[n + 1];\n\n Tuple[] roads = new Tuple[n - 1];\n\n for (int i = 1; i < n + 1; i++) adj[i] = new ArrayList<>();\n\n for (int i = 0; i < n - 1; i++) {\n\n int a = in.intNext(), b = in.intNext();\n\n nodes[a]++;\n\n nodes[b]++;\n\n Tuple road = new Tuple(a, b);\n\n roads[i] = road;\n\n adj[a].add(road);\n\n adj[b].add(road);\n\n }\n\n\/\/ out.println(nodes);\n\n int lo = 0;\n\n int hi = n - 1;\n\n int valid = 0;\n\n while (lo <= hi) {\n\n int mid = (lo + hi) \/ 2;\n\n int over = 0;\n\n for (int i = 1; i < n + 1; i++) if (nodes[i] > mid) over++;\n\n if (over <= k) {\n\n valid = mid;\n\n hi = mid - 1;\n\n } else\n\n lo = mid + 1;\n\n }\n\n out.println(valid);\n\n boolean[] visited = new boolean[n + 1];\n\n Deque deque = new ArrayDeque<>();\n\n deque.addLast(1);\n\n nodes[1] = -1;\n\n int owner = 0;\n\n while (!deque.isEmpty()) {\n\n int idx = deque.pollFirst();\n\n visited[idx] = true;\n\n int prev = nodes[idx];\n\n for (Tuple child : adj[idx]) {\n\n int other = child.a == idx ? child.b : child.a;\n\n if (visited[other]) continue;\n\n if (owner == prev) owner = (owner + 1) % valid;\n\n nodes[other] = owner;\n\n child.c = owner;\n\n owner = (owner + 1) % valid;\n\n deque.addLast(other);\n\n }\n\n }\n\n for (int i = 0; i < n - 1; i++) out.p(roads[i].c + 1).p(\" \");\n\n }\n\n\n\n\n\n\/\/ Generated Code Below:\n\nprivate static final FastWriter out = new FastWriter();\n\nprivate static FastScanner in;\n\nstatic ArrayList[] adj;\n\nprivate static long e97 = (long)1e9 + 7;\n\npublic static void main(String[] args) throws IOException {\n\n in = new FastScanner();\n\n new G().solver();\n\n out.close();\n\n}\n\n\n\nstatic class FastWriter {\n\n private static final int IO_BUFFERS = 128 * 1024;\n\n private final StringBuilder out;\n\n public FastWriter() { out = new StringBuilder(IO_BUFFERS); }\n\n public FastWriter p(Object object) { out.append(object); return this; }\n\n public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; }\n\n public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(\" \"); } out.append(\"\\n\"); return this; }\n\n public FastWriter pp(int[] args) { for (int ob : args) { out.append(ob).append(\" \"); } out.append(\"\\n\"); return this; }\n\n public FastWriter pp(long[] args) { for (long ob : args) { out.append(ob).append(\" \"); } out.append(\"\\n\"); return this; }\n\n public FastWriter pp(char[] args) { for (char ob : args) { out.append(ob).append(\" \"); } out.append(\"\\n\"); return this; }\n\n public void println(long[] arr) { for(long e: arr) out.append(e).append(\" \"); out.append(\"\\n\"); }\n\n public void println(int[] arr) { for(int e: arr) out.append(e).append(\" \"); out.append(\"\\n\"); }\n\n public void println(char[] arr) { for(char e: arr) out.append(e).append(\" \"); out.append(\"\\n\"); }\n\n public void println(double[] arr) { for(double e: arr) out.append(e).append(\" \"); out.append(\"\\n\"); }\n\n public void println(boolean[] arr) { for(boolean e: arr) out.append(e).append(\" \"); out.append(\"\\n\"); }\n\n public void println(T[] arr) { for(T e: arr) out.append(e).append(\" \"); out.append(\"\\n\"); }\n\n public void println(long[][] arr) { for (long[] row: arr) out.append(Arrays.toString(row)).append(\"\\n\"); }\n\n public void println(int[][] arr) { for (int[] row: arr) out.append(Arrays.toString(row)).append(\"\\n\"); }\n\n public void println(char[][] arr) { for (char[] row: arr) out.append(Arrays.toString(row)).append(\"\\n\"); }\n\n public void println(double[][] arr) { for (double[] row: arr) out.append(Arrays.toString(row)).append(\"\\n\"); }\n\n public void println(T[][] arr) { for (T[] row: arr) out.append(Arrays.toString(row)).append(\"\\n\"); }\n\n public FastWriter println(Object object) { out.append(object).append(\"\\n\"); return this; }\n\n public void toFile(String fileName) throws IOException {\n\n BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));\n\n writer.write(out.toString());\n\n writer.close();\n\n }\n\n public void close() throws IOException { System.out.print(out); }\n\n}\n\nstatic class FastScanner {\n\n private InputStream sin = System.in;\n\n private final byte[] buffer = new byte[1024];\n\n private int ptr = 0;\n\n private int buflen = 0;\n\n public FastScanner(){}\n\n public FastScanner(String filename) throws FileNotFoundException {\n\n File file = new File(filename);\n\n sin = new FileInputStream(file);\n\n }\n\n private boolean hasNextByte() {\n\n if (ptr < buflen) {\n\n return true;\n\n }else{\n\n ptr = 0;\n\n try {\n\n buflen = sin.read(buffer);\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n if (buflen <= 0) {\n\n return false;\n\n }\n\n }\n\n return true;\n\n }\n\n private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}\n\n private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}\n\n public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}\n\n public String next() {\n\n if (!hasNext()) throw new NoSuchElementException();\n\n StringBuilder sb = new StringBuilder();\n\n int b = readByte();\n\n while(isPrintableChar(b)) {\n\n sb.appendCodePoint(b);\n\n b = readByte();\n\n }\n\n return sb.toString();\n\n }\n\n public long longNext() {\n\n if (!hasNext()) throw new NoSuchElementException();\n\n long n = 0;\n\n boolean minus = false;\n\n int b = readByte();\n\n if (b == '-') {\n\n minus = true;\n\n b = readByte();\n\n }\n\n if (b < '0' || '9' < b) {\n\n throw new NumberFormatException();\n\n }\n\n while(true){\n\n if ('0' <= b && b <= '9') {\n\n n *= 10;\n\n n += b - '0';\n\n }else if(b == -1 || !isPrintableChar(b) || b == ':'){\n\n return minus ? -n : n;\n\n }else{\n\n throw new NumberFormatException();\n\n }\n\n b = readByte();\n\n }\n\n }\n\n public int intNext() {\n\n long nl = longNext();\n\n if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();\n\n return (int) nl;\n\n }\n\n public double doubleNext() { return Double.parseDouble(next());}\n\n public long[] nextLongArray(final int n){\n\n final long[] a = new long[n];\n\n for (int i = 0; i < n; i++)\n\n a[i] = longNext();\n\n return a;\n\n }\n\n public int[] nextIntArray(final int n){\n\n final int[] a = new int[n];\n\n for (int i = 0; i < n; i++)\n\n a[i] = intNext();\n\n return a;\n\n }\n\n public double[] nextDoubleArray(final int n){\n\n final double[] a = new double[n];\n\n for (int i = 0; i < n; i++)\n\n a[i] = doubleNext();\n\n return a;\n\n }\n\n public ArrayList[] getAdj(int n) {\n\n ArrayList[] adj = new ArrayList[n + 1];\n\n for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();\n\n return adj;\n\n }\n\n public ArrayList[] adjacencyList(int nodes, int edges) throws IOException {\n\n return adjacencyList(nodes, edges, false);\n\n }\n\n public ArrayList[] adjacencyList(int nodes, int edges, boolean isDirected) throws IOException {\n\n adj = getAdj(nodes);\n\n for (int i = 0; i < edges; i++) {\n\n int a = intNext(), b = intNext();\n\n adj[a].add(b);\n\n if (!isDirected) adj[b].add(a);\n\n }\n\n return adj;\n\n }\n\n}\n\nstatic class u {\n\n public static int upperBound(long[] array, long obj) {\n\n int l = 0, r = array.length - 1;\n\n while (r - l >= 0) {\n\n int c = (l + r) \/ 2;\n\n if (obj < array[c]) {\n\n r = c - 1;\n\n } else {\n\n l = c + 1;\n\n }\n\n }\n\n return l;\n\n }\n\n public static int upperBound(ArrayList array, long obj) {\n\n int l = 0, r = array.size() - 1;\n\n while (r - l >= 0) {\n\n int c = (l + r) \/ 2;\n\n if (obj < array.get(c)) {\n\n r = c - 1;\n\n } else {\n\n l = c + 1;\n\n }\n\n }\n\n return l;\n\n }\n\n public static int lowerBound(long[] array, long obj) {\n\n int l = 0, r = array.length - 1;\n\n while (r - l >= 0) {\n\n int c = (l + r) \/ 2;\n\n if (obj <= array[c]) {\n\n r = c - 1;\n\n } else {\n\n l = c + 1;\n\n }\n\n }\n\n return l;\n\n }\n\n public static int lowerBound(ArrayList array, long obj) {\n\n int l = 0, r = array.size() - 1;\n\n while (r - l >= 0) {\n\n int c = (l + r) \/ 2;\n\n if (obj <= array.get(c)) {\n\n r = c - 1;\n\n } else {\n\n l = c + 1;\n\n }\n\n }\n\n return l;\n\n }\n\n static T[][] deepCopy(T[][] matrix) { return Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone()); }\n\n static int[][] deepCopy(int[][] matrix) { return Arrays.stream(matrix).map(int[]::clone).toArray($ -> matrix.clone()); }\n\n static long[][] deepCopy(long[][] matrix) { return Arrays.stream(matrix).map(long[]::clone).toArray($ -> matrix.clone()); }\n\n private static void sort(int[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }\n\n private static void sort(long[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }\n\n private static void rSort(T[] arr) { Arrays.sort(arr, Collections.reverseOrder()); }\n\n private static void customSort(int[][] arr) {\n\n Arrays.sort(arr, new Comparator() {\n\n public int compare(int[] a, int[] b) {\n\n if (a[0] == b[0]) return Integer.compare(a[1], b[1]);\n\n return Integer.compare(a[0], b[0]);\n\n }\n\n });\n\n }\n\n public static int[] swap(int[] arr, int left, int right) {\n\n int temp = arr[left];\n\n arr[left] = arr[right];\n\n arr[right] = temp;\n\n return arr;\n\n }\n\n public static char[] swap(char[] arr, int left, int right) {\n\n char temp = arr[left];\n\n arr[left] = arr[right];\n\n arr[right] = temp;\n\n return arr;\n\n }\n\n public static int[] reverse(int[] arr, int left, int right) {\n\n while (left < right) {\n\n int temp = arr[left];\n\n arr[left++] = arr[right];\n\n arr[right--] = temp;\n\n }\n\n return arr;\n\n }\n\n public static boolean findNextPermutation(int[] data) {\n\n if (data.length <= 1) return false;\n\n int last = data.length - 2;\n\n while (last >= 0) {\n\n if (data[last] < data[last + 1]) break;\n\n last--;\n\n }\n\n if (last < 0) return false;\n\n int nextGreater = data.length - 1;\n\n for (int i = data.length - 1; i > last; i--) {\n\n if (data[i] > data[last]) {\n\n nextGreater = i;\n\n break;\n\n }\n\n }\n\n data = swap(data, nextGreater, last);\n\n data = reverse(data, last + 1, data.length - 1);\n\n return true;\n\n }\n\n public static int biSearch(int[] dt, int target){\n\n int left=0, right=dt.length-1;\n\n int mid=-1;\n\n while(left<=right){\n\n mid = (right+left)\/2;\n\n if(dt[mid] == target) return mid;\n\n if(dt[mid] < target) left=mid+1;\n\n else right=mid-1;\n\n }\n\n return -1;\n\n }\n\n public static int biSearchMax(long[] dt, long target){\n\n int left=-1, right=dt.length;\n\n int mid=-1;\n\n\n\n while((right-left)>1){\n\n mid = left + (right-left)\/2;\n\n if(dt[mid] <= target) left=mid;\n\n else right=mid;\n\n }\n\n return left;\n\n }\n\n public static int biSearchMaxAL(ArrayList dt, long target){\n\n int left=-1, right=dt.size();\n\n int mid=-1;\n\n\n\n while((right-left)>1){\n\n mid = left + (right-left)\/2;\n\n if(dt.get(mid) <= target) left=mid;\n\n else right=mid;\n\n }\n\n return left;\n\n }\n\n private static void fill(T[][] ob, T res){for(int i=0;ivoid fill(T[][][] ob,T res){for(int i=0;i0; i--){ ans*=i; }\n\n return ans;\n\n }\n\n private static long facMod(int n, long mod) {\n\n long ans=1;\n\n for(long i=n; i>0; i--) ans = (ans * i) % mod;\n\n return ans;\n\n }\n\n private static long lcm(long m, long n){\n\n long ans = m\/gcd(m,n);\n\n ans *= n;\n\n return ans;\n\n }\n\n private static long gcd(long m, long n) {\n\n if(m < n) return gcd(n, m);\n\n if(n == 0) return m;\n\n return gcd(n, m % n);\n\n }\n\n private static boolean isPrime(long a){\n\n if(a==1) return false;\n\n for(int i=2; i<=Math.sqrt(a); i++){ if(a%i == 0) return false; }\n\n return true;\n\n }\n\n static long modInverse(long a, long mod) {\n\n \/* Fermat's little theorem: a^(MOD-1) => 1\n\n Therefore (divide both sides by a): a^(MOD-2) => a^(-1) *\/\n\n return binpowMod(a, mod - 2, mod);\n\n }\n\n static long binpowMod(long a, long b, long mod) {\n\n long res = 1;\n\n while (b > 0) {\n\n if (b % 2 == 1) res = (res * a) % mod;\n\n a = (a * a) % mod;\n\n b \/= 2;\n\n }\n\n return res;\n\n }\n\n private static int getDigit2(long num){\n\n long cf = 1; int d=0;\n\n while(num >= cf){ d++; cf = 1<= cf){ d++; cf*=10; }\n\n return d;\n\n }\n\n private static boolean isInArea(int y, int x, int h, int w){\n\n if(y<0) return false;\n\n if(x<0) return false;\n\n if(y>=h) return false;\n\n if(x>=w) return false;\n\n return true;\n\n }\n\n private static ArrayList generatePrimes(int n) {\n\n int[] lp = new int[n + 1];\n\n ArrayList pr = new ArrayList<>();\n\n for (int i = 2; i <= n; ++i) {\n\n if (lp[i] == 0) {\n\n lp[i] = i;\n\n pr.add(i);\n\n }\n\n for (int j = 0; j < pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= n; ++j) {\n\n lp[i * pr.get(j)] = pr.get(j);\n\n }\n\n }\n\n return pr;\n\n }\n\n static long nPrMod(int n, int r, long MOD) {\n\n long res = 1;\n\n for (int i = (n - r + 1); i <= n; i++) {\n\n res = (res * i) % MOD;\n\n }\n\n return res;\n\n }\n\n static long nCr(int n, int r) {\n\n if (r > (n - r))\n\n r = n - r;\n\n long ans = 1;\n\n for (int i = 1; i <= r; i++) {\n\n ans *= n;\n\n ans \/= i;\n\n n--;\n\n }\n\n return ans;\n\n }\n\n static long nCrMod(int n, int r, long MOD) {\n\n long rFactorial = nPrMod(r, r, MOD);\n\n long first = nPrMod(n, r, MOD);\n\n long second = binpowMod(rFactorial, MOD-2, MOD);\n\n return (first * second) % MOD;\n\n }\n\n static void printBitRepr(int n) {\n\n StringBuilder res = new StringBuilder();\n\n for (int i = 0; i < 32; i++) {\n\n int mask = (1 << i);\n\n res.append((mask & n) == 0 ? \"0\" : \"1\");\n\n }\n\n out.println(res);\n\n }\n\n static String bitString(int n) {return Integer.toBinaryString(n);}\n\n static int setKthBitToOne(int n, int k) { return (n | (1 << k)); } \/\/ zero indexed\n\n static int setKthBitToZero(int n, int k) { return (n & ~(1 << k)); }\n\n static int invertKthBit(int n, int k) { return (n ^ (1 << k)); }\n\n static boolean isPowerOfTwo(int n) { return (n & (n - 1)) == 0; }\n\n static HashMap counts(String word) {\n\n HashMap counts = new HashMap<>();\n\n for (int i = 0; i < word.length(); i++) counts.merge(word.charAt(i), 1, Integer::sum);\n\n return counts;\n\n }\n\n static HashMap counts(int[] arr) {\n\n HashMap counts = new HashMap<>();\n\n for (int value : arr) counts.merge(value, 1, Integer::sum);\n\n return counts;\n\n }\n\n static HashMap counts(long[] arr) {\n\n HashMap counts = new HashMap<>();\n\n for (long l : arr) counts.merge(l, 1, Integer::sum);\n\n return counts;\n\n }\n\n static HashMap counts(char[] arr) {\n\n HashMap counts = new HashMap<>();\n\n for (char c : arr) counts.merge(c, 1, Integer::sum);\n\n return counts;\n\n }\n\n static long hash(int x, int y) {\n\n return x* 1_000_000_000L +y;\n\n }\n\n static final Random random = new Random();\n\n static void sort(int[] a) {\n\n int n = a.length;\/\/ shuffle, then sort\n\n for (int i = 0; i < n; i++) {\n\n int oi = random.nextInt(n), temp = a[oi];\n\n a[oi] = a[i];\n\n a[i] = temp;\n\n }\n\n Arrays.sort(a);\n\n }\n\n static void sort(long[] arr) {\n\n shuffleArray(arr);\n\n Arrays.sort(arr);\n\n }\n\n static void shuffleArray(long[] arr) {\n\n int n = arr.length;\n\n for(int i=0; i {\n\n int a;\n\n int b;\n\n int c;\n\n public Tuple(int a, int b) {\n\n this.a = a;\n\n this.b = b;\n\n this.c = 0;\n\n }\n\n public Tuple(int a, int b, int c) {\n\n this.a = a;\n\n this.b = b;\n\n this.c = c;\n\n }\n\n public int getA() { return a; }\n\n public int getB() { return b; }\n\n public int getC() { return c; }\n\n public int compareTo(Tuple other) {\n\n if (this.a == other.a) {\n\n if (this.b == other.b) return Long.compare(this.c, other.c);\n\n return Long.compare(this.b, other.b);\n\n }\n\n return Long.compare(this.a, other.a);\n\n }\n\n @Override\n\n public int hashCode() { return Arrays.deepHashCode(new Integer[]{a, b, c}); }\n\n @Override\n\n public boolean equals(Object o) {\n\n if (!(o instanceof Tuple)) return false;\n\n Tuple pairo = (Tuple) o;\n\n return (this.a == pairo.a && this.b == pairo.b && this.c == pairo.c);\n\n }\n\n @Override\n\n public String toString() { return String.format(\"(%d %d %d) \", this.a, this.b, this.c); }\n\n}\n\nprivate static int abs(int a){ return (a>=0) ? a: -a; }\n\nprivate static int min(int... ins){ int min = ins[0]; for(int i=1; i max) max = ins[i]; } return max; }\n\nprivate static int sum(int... ins){ int total = 0; for (int v : ins) { total += v; } return total; }\n\nprivate static long abs(long a){ return (a>=0) ? a: -a; }\n\nprivate static long min(long... ins){ long min = ins[0]; for(int i=1; i max) max = ins[i]; } return max; }\n\nprivate static long sum(long... ins){ long total = 0; for (long v : ins) { total += v; } return total; }\n\nprivate static double abs(double a){ return (a>=0) ? a: -a; }\n\nprivate static double min(double... ins){ double min = ins[0]; for(int i=1; i max) max = ins[i]; } return max; }\n\nprivate static double sum(double... ins){ double total = 0; for (double v : ins) { total += v; } return total; }\n\n\n\n}\n\n","language":"java"} -{"contest_id":"1141","problem_id":"F2","statement":"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],\u2026,a[n].a[1],a[2],\u2026,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],\u2026,a[r]a[l],a[l+1],\u2026,a[r] (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),\u2026,(lk,rk)(l1,r1),(l2,r2),\u2026,(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\u2260ji\u2260j either rikk\u2032>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\u2264n\u226415001\u2264n\u22641500) \u2014 the length of the given array. The second line contains the sequence of elements a[1],a[2],\u2026,a[n]a[1],a[2],\u2026,a[n] (\u2212105\u2264ai\u2264105\u2212105\u2264ai\u2264105).OutputIn the first line print the integer kk (1\u2264k\u2264n1\u2264k\u2264n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1\u2264li\u2264ri\u2264n1\u2264li\u2264ri\u2264n) \u2014 the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7\n4 1 2 2 1 5 3\nOutputCopy3\n7 7\n2 3\n4 5\nInputCopy11\n-5 -4 -3 -2 -1 0 1 2 3 4 5\nOutputCopy2\n3 4\n1 1\nInputCopy4\n1 1 1 1\nOutputCopy4\n4 4\n1 1\n2 2\n3 3\n","tags":["data structures","greedy"],"code":"\n\nimport java.util.*;\n\nimport java.io.*;\n\n\n\npublic class Main {\n\n\n\n void solve() {\n\n int n = in.nextInt();\n\n int[] arr = new int[n + 1];\n\n for (int i = 1; i <= n; i++) {\n\n arr[i] = in.nextInt();\n\n }\n\n HashMap> map = new HashMap<>();\n\n for (int i = 1; i <= n; i++) {\n\n long sum = 0l;\n\n for (int j = i; j <= n; j++) {\n\n sum += arr[j];\n\n map.computeIfAbsent(sum, k -> new ArrayList<>()).add(new int[] {i, j});\n\n }\n\n }\n\n List ans = new ArrayList<>();\n\n for (Map.Entry> x : map.entrySet()) {\n\n List cur = x.getValue();\n\n Collections.sort(cur, Comparator.comparingInt(a -> a[1]));\n\n List temp = new LinkedList<>();\n\n int prev =0;\n\n for (int i = 0; i < cur.size(); i++) {\n\n if (cur.get(i)[0] > prev) {\n\n temp.add(cur.get(i));\n\n prev = cur.get(i)[1];\n\n }\n\n }\n\n if (temp.size() > ans.size()) {\n\n ans = temp;\n\n }\n\n }\n\n out.println(ans.size());\n\n for (int[] x : ans) {\n\n out.println(x[0]+\" \"+x[1]);\n\n }\n\n }\n\n\n\n FastScanner in;\n\n\n\n PrintWriter out;\n\n\n\n void run() {\n\n in = new FastScanner();\n\n out = new PrintWriter(System.out);\n\n solve();\n\n out.close();\n\n }\n\n\n\n class FastScanner {\n\n BufferedReader br;\n\n\n\n StringTokenizer st;\n\n\n\n public FastScanner() {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n\n\n public FastScanner(String s) {\n\n try {\n\n br = new BufferedReader(new FileReader(s));\n\n } catch (FileNotFoundException e) {\n\n \/\/ TODO Auto-generated catch block\n\n e.printStackTrace();\n\n }\n\n }\n\n\n\n public String nextToken() {\n\n while (st == null || !st.hasMoreTokens()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n public int nextInt() {\n\n return Integer.parseInt(nextToken());\n\n }\n\n\n\n public long nextLong() {\n\n return Long.parseLong(nextToken());\n\n }\n\n\n\n public double nextDouble() {\n\n return Double.parseDouble(nextToken());\n\n }\n\n }\n\n\n\n public static void main(String[] args) {\n\n new Main().run();\n\n }\n\n\n\n}","language":"java"} -{"contest_id":"1304","problem_id":"C","statement":"C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi \u2014 the time (in minutes) when the ii-th customer visits the restaurant, lili \u2014 the lower bound of their preferred temperature range, and hihi \u2014 the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1\u2264q\u22645001\u2264q\u2264500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1\u2264n\u22641001\u2264n\u2264100, \u2212109\u2264m\u2264109\u2212109\u2264m\u2264109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1\u2264ti\u22641091\u2264ti\u2264109, \u2212109\u2264li\u2264hi\u2264109\u2212109\u2264li\u2264hi\u2264109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print \"YES\" if it is possible to satisfy all customers. Otherwise, print \"NO\".You can print each letter in any case (upper or lower).ExampleInputCopy4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0\nOutputCopyYES\nNO\nYES\nNO\nNoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.","tags":["dp","greedy","implementation","sortings","two pointers"],"code":"import java.io.*;\n\nimport java.nio.file.FileStore;\n\nimport java.util.*;\n\n public class zia\n\n { \n\n\t\n\n \n\n\tstatic void BFS(ArrayList> adj,int s, boolean[] visited) \n\n\t{ \n\n \tQueue q=new LinkedList<>();\n\n \t\n\n \tvisited[s] = true; \n\n \tq.add(s); \n\n \n\n \twhile(q.isEmpty()==false) \n\n \t{ \n\n \t\tint u = q.poll(); \n\n \t\t \n\n \t\tfor(int v:adj.get(u)){\n\n \t\t if(visited[v]==false){\n\n \t\t visited[v]=true;\n\n \t\t q.add(v);\n\n \t\t }\n\n \t\t} \n\n \t} \n\n\t} \n\n\t\/\/ static int BFS(ArrayList> adj,pair s, boolean[] visited,int ar[],int m) \n\n\t\/\/ { \n\n \/\/ \tQueue q=new LinkedList<>();\n\n \t\n\n \/\/ \tvisited[s.a] = true; \n\n \/\/ \tq.add(s); \n\n \n\n\t\/\/ \tint count=0;\n\n \/\/ \twhile(q.isEmpty()==false) \n\n \/\/ \t{ \n\n \/\/ \t\tpair u = q.poll(); \n\n\t\/\/ \t\t\/\/ if(adj.get(u.a).size()==0)\n\n\t\/\/ \t\t\/\/ count++;\n\n\t \n\n\t\/\/ \t\tboolean end=true;\n\n \/\/ \t\tfor(int v:adj.get(u.a)){\n\n \/\/ \t\t if(visited[v]==false){\n\n \/\/ \t\t visited[v]=true;\n\n\t\/\/ \t\t\t\tend=false;\n\n\t\/\/ \t\t\t\tint cat=ar[v]==0?0:ar[v]+u.b;\n\n\t\/\/ \t\t\t\tif(cat>m)\n\n\t\/\/ \t\t\t\tcontinue;\n\n \/\/ \t\t q.add(new pair(v, cat));\n\n\t\/\/ \t\t\t\t\/\/ System.out.print(\"--\"+v+\" \"+cat+\"--\");\n\n \/\/ \t\t }\n\n \/\/ \t\t} \n\n\t\/\/ \t\tif(end)\n\n\t\/\/ \t\tcount++;\n\n\t\/\/ \t\t\/\/ System.out.println(u.a+\" \"+adj.get(u.a).size()+\" count \"+count);\n\n \/\/ \t} \n\n\t\/\/ \treturn count;\n\n\t\/\/ } \n\n\tstatic void addEdge(ArrayList> adj, int u, int v) \n\n\t{ \n\n\t\tadj.get(u).add(v); \n\n\t\tadj.get(v).add(u); \n\n\t} \n\n\tstatic void ruffleSort(long[] a) {\n\n int n=a.length;\n\n\t\tRandom random = new Random();\n\n for (int i=0; ix)\t\n\n\t\t\t{e=mid-1;res=mid;}\n\n\t\t\telse if(ar[mid]0&&ar[mid]==ar[mid-1])\n\n\t\t\t e=mid-1;\n\n\t\t\t else\n\n\t\t\t break;\n\n\t\t\t}\n\n \n\n\t\t}\n\n\t\treturn res;\n\n\t}\n\n\tpublic static long lowerbound(int s,int e, long ar[],long x)\n\n\t{\n\n\t\tlong res=-1;\n\n\t\twhile(s<=e)\n\n\t\t{ int mid=((s-e)\/2)+e;\n\n\t\t\tif(ar[mid]>x)\t\n\n\t\t\t{e=mid-1;}\n\n\t\t\telse if(ar[mid]ar[max])\n\n\t\t\t max=i;\n\n\t\t\t \n\n\t\t ar[max]=c++;\n\n\t\t tree(s,max-1,ar,c);\n\n\t\t tree(max+1,e,ar,c);\n\n\t }\n\n\t}\n\n\t\n\n static int resturant=0;\n\n static void DFS(ArrayList> al,boolean visited[],int s,int max,int curr,int ar[])\n\n {\n\n\t\n\n\tvisited[s]=true;\n\n\tif(al.get(s).size()==1&&visited[al.get(s).get(0)]==true)\n\n\t{resturant++;return;}\n\n\t\/\/ System.out.println(s+\" \"+curr);\n\n\tfor(int x:al.get(s))\n\n\t{\n\n\t\tif(visited[x]==false)\n\n\t\t{\n\n\t\t\tif(ar[x]==0)\n\n\t\t\tDFS(al, visited, x, max, 0, ar);\n\n\t\t\telse if(curr+ar[x]<=max)\n\n\t\t\tDFS(al, visited, x, max, curr+ar[x], ar);\n\n\t\t\t\n\n\t\t}\n\n\t}\n\n\t\n\n }\n\n\t\n\n\tpublic static void main(String[] args) throws Exception\n\n {\n\n\t\tFastIO sc = new FastIO();\n\n\t\t\n\n \n\n\t\t\/\/sc.println();\n\n\/\/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n\t\tint test=sc.nextInt();\n\n\t\t\n\n\t\t\/\/ \/\/ double c=Math.log(10);\n\n\t\t\/\/ boolean prime[]=new boolean[233334];\n\n\t\t\/\/ sieve(233334, prime);\n\n\t\t\/\/ HashMap hm=new HashMap<>(9);\n\n\t\t\/\/ char c='1';\n\n\t\t\/\/ for(int i=1;i<=9;i++)\n\n\t\t\/\/ hm.put(c++,i);\n\n \n\n\t\t\n\n \n\n\t\twhile(test-->0)\n\n\t\t{\n\n\t\t\n\n\t\t\n\n\t\t\tint n=sc.nextInt();\n\n\t\t\tlong in=sc.nextLong();\n\n\t\t\ttriplet ar[]=new triplet[n];\n\n\t\t\tfor(int i=0;iar[i].third||curre{\n\n\tint a;\n\n\tint b;\n\n\tpair(int a,int b)\n\n\t{this.a=a;\n\n\t\tthis.b=b;\n\n \n\n\t}\n\n\tpublic int compareTo(pair p)\n\n\t{\n\n\t\tif(this.a-p.a==0)\n\n\t\treturn this.b-p.b;\n\n\n\n\t\treturn (this.a-p.a);\n\n\t}\n\n}\n\nclass triplet implements Comparable{\n\n\tlong first,second,third;\n\n\ttriplet(long first,long second,long third)\n\n\t{this.first=first;\n\n\t\tthis.second=second;\n\n\t\tthis.third=third;\n\n \n\n\t}\n\n\tpublic int compareTo(triplet p)\n\n\t{ \n\n\t\treturn (int)(this.first-p.first);\n\n\t}\n\n}\n\n\/\/ class triplet\n\n\/\/ {\n\n\/\/ \tint x1,x2,i;\n\n\/\/ \ttriplet(int a,int b,int c)\n\n\/\/ \t{x1=a;x2=b;i=c;}\n\n\/\/ }\n\n class FastIO extends PrintWriter {\n\n\tprivate InputStream stream;\n\n\tprivate byte[] buf = new byte[1<<16];\n\n\tprivate int curChar, numChars;\n\n \n\n\t\/\/ standard input\n\n\tpublic FastIO() { this(System.in,System.out); }\n\n\tpublic FastIO(InputStream i, OutputStream o) {\n\n\t\tsuper(o);\n\n\t\tstream = i;\n\n\t}\n\n\t\/\/ file input\n\n\tpublic FastIO(String i, String o) throws IOException {\n\n\t\tsuper(new FileWriter(o));\n\n\t\tstream = new FileInputStream(i);\n\n\t}\n\n \n\n\t\/\/ throws InputMismatchException() if previously detected end of file\n\n\tprivate int nextByte() {\n\n\t\tif (numChars == -1) throw new InputMismatchException();\n\n\t\tif (curChar >= numChars) {\n\n\t\t\tcurChar = 0;\n\n\t\t\ttry {\n\n\t\t\t\tnumChars = stream.read(buf);\n\n\t\t\t} catch (IOException e) {\n\n\t\t\t\tthrow new InputMismatchException();\n\n\t\t\t}\n\n\t\t\tif (numChars == -1) return -1; \/\/ end of file\n\n\t\t}\n\n\t\treturn buf[curChar++];\n\n\t}\n\n \n\n\tpublic String nextLine() {\n\n\t\tint c; do { c = nextByte(); } while (c <= '\\n');\n\n\t\tStringBuilder res = new StringBuilder();\n\n\t\tdo { res.appendCodePoint(c); c = nextByte(); } while (c > '\\n');\n\n\t\treturn res.toString();\n\n\t}\n\n \n\n\tpublic String next() {\n\n\t\tint c; do { c = nextByte(); } while (c <= ' ');\n\n\t\tStringBuilder res = new StringBuilder();\n\n\t\tdo { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');\n\n\t\treturn res.toString();\n\n\t}\n\n \n\n\tpublic int nextInt() { \n\n\t\tint c; do { c = nextByte(); } while (c <= ' ');\n\n\t\tint sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }\n\n\t\tint res = 0;\n\n\t\tdo {\n\n\t\t\tif (c < '0' || c > '9')\n\n\t\t\t\tthrow new InputMismatchException();\n\n\t\t\tres = 10*res+c-'0';\n\n\t\t\tc = nextByte();\n\n\t\t} while (c > ' ');\n\n\t\treturn res * sgn;\n\n\t}\n\n \n\n public long nextLong() { \n\n\t\tint c; do { c = nextByte(); } while (c <= ' ');\n\n\t\tlong sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }\n\n\t\tlong res = 0;\n\n\t\tdo {\n\n\t\t\tif (c < '0' || c > '9')\n\n\t\t\t\tthrow new InputMismatchException();\n\n\t\t\tres = 10*res+c-'0';\n\n\t\t\tc = nextByte();\n\n\t\t} while (c > ' ');\n\n\t\treturn res * sgn;\n\n\t}\n\n \n\n\tpublic double nextDouble() { return Double.parseDouble(next()); }\n\n}","language":"java"} -{"contest_id":"1313","problem_id":"B","statement":"B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round\u00a0\u2014 yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1\u2264t\u22641001\u2264t\u2264100)\u00a0\u2014 the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1\u2264n\u22641091\u2264n\u2264109, 1\u2264x,y\u2264n1\u2264x,y\u2264n)\u00a0\u2014 the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers\u00a0\u2014 the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second\u00a0\u2014 third place.","tags":["constructive algorithms","greedy","implementation","math"],"code":"import java.util.Scanner;\n\n \n\npublic class IntTree {\n\n public static void main(String[] args) {\n\n \n\n Scanner s = new Scanner(System.in);\n\n int t = s.nextInt();\n\n while(t-->0){\n\n int n=s.nextInt();\n\n int x=s.nextInt();\n\n int y=s.nextInt();\n\n int min=Math.max(1,Math.min(n,x+y-n+1));\n\n int max=Math.min(n,x+y-1);\n\n System.out.println(min+\" \"+max);\n\n }\n\n \n\n }\n\n}","language":"java"} -{"contest_id":"1295","problem_id":"C","statement":"C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1\u2264T\u22641001\u2264T\u2264100) \u2014 the number of test cases.The first line of each testcase contains one string ss (1\u2264|s|\u22641051\u2264|s|\u2264105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1\u2264|t|\u22641051\u2264|t|\u2264105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2\u22c51052\u22c5105.OutputFor each testcase, print one integer \u2014 the minimum number of operations to turn string zz into string tt. If it's impossible print \u22121\u22121.ExampleInputCopy3\naabce\nace\nabacaba\naax\nty\nyyt\nOutputCopy1\n-1\n3\n","tags":["dp","greedy","strings"],"code":"import static java.lang.Math.max;\n\nimport static java.lang.Math.min;\n\nimport static java.lang.Math.abs;\n\n\n\nimport java.util.*;\n\nimport java.io.*;\n\nimport java.math.*;\n\n\n\n\n\npublic class C_Obtain_The_String {\n\n static long mod = Long.MAX_VALUE;\n\n static OutputStream outputStream = System.out;\n\n static PrintWriter out = new PrintWriter(outputStream);\n\n static FastReader f = new FastReader();\n\n\n\n public static void main(String[] args) {\n\n int t = f.nextInt();\n\n\n\n while(t-- > 0){\n\n solve();\n\n }\n\n\n\n\n\n\n\n out.close();\n\n }\n\n\n\n\n\n public static void solve() {\n\n String s = f.nextLine();\n\n int sl = s.length();\n\n String t = f.nextLine();\n\n int tl = t.length();\n\n\n\n ArrayList> arrli = new ArrayList<>();\n\n for(int i = 0; i < 26; i++) {\n\n arrli.add(new TreeSet<>());\n\n }\n\n for(int i = 0; i < sl; i++) {\n\n arrli.get(s.charAt(i)-'a').add(i);\n\n }\n\n\n\n int ops = 1;\n\n int ind = 0;\n\n for(int i = 0; i < tl; i++) {\n\n int c = t.charAt(i)-'a';\n\n if(arrli.get(c).isEmpty()) {\n\n out.println(-1);\n\n return;\n\n }\n\n Integer nextInd = arrli.get(c).ceiling(ind);\n\n if(nextInd == null) {\n\n ops++;\n\n ind = arrli.get(c).first()+1;\n\n } else {\n\n ind = nextInd+1;\n\n }\n\n }\n\n\n\n out.println(ops);\n\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n \/\/ Sort an array\n\n public static void sort(int arr[]) {\n\n ArrayList al = new ArrayList<>();\n\n for(int i: arr) {\n\n al.add(i);\n\n }\n\n Collections.sort(al);\n\n for(int i = 0; i < arr.length; i++) {\n\n arr[i] = al.get(i);\n\n }\n\n }\n\n\n\n \/\/ Find all divisors of n\n\n public static void allDivisors(int n) {\n\n for(int i = 1; i*i <= n; i++) {\n\n if(n%i == 0) {\n\n System.out.println(i + \" \");\n\n if(i != n\/i) {\n\n System.out.println(n\/i + \" \");\n\n }\n\n }\n\n }\n\n }\n\n\n\n \/\/ Check if n is prime or not\n\n public static boolean isPrime(int n) {\n\n if(n < 1) return false;\n\n if(n == 2 || n == 3) return true;\n\n if(n % 2 == 0 || n % 3 == 0) return false;\n\n for(int i = 5; i*i <= n; i += 6) {\n\n if(n % i == 0 || n % (i+2) == 0) {\n\n return false;\n\n }\n\n }\n\n return true;\n\n }\n\n\n\n \/\/ Find gcd of a and b\n\n public static long gcd(long a, long b) {\n\n long dividend = a > b ? a : b;\n\n long divisor = a < b ? a : b;\n\n \n\n while(divisor > 0) {\n\n long reminder = dividend % divisor;\n\n dividend = divisor;\n\n divisor = reminder;\n\n }\n\n return dividend;\n\n }\n\n\n\n \/\/ Find lcm of a and b\n\n public static long lcm(long a, long b) {\n\n long lcm = gcd(a, b);\n\n long hcf = (a * b) \/ lcm;\n\n return hcf;\n\n }\n\n\n\n \/\/ Find factorial in O(n) time\n\n public static long fact(int n) {\n\n long res = 1;\n\n for(int i = 2; i <= n; i++) {\n\n res = res * i;\n\n }\n\n return res;\n\n }\n\n\n\n \/\/ Find power in O(logb) time\n\n public static long power(long a, long b) {\n\n long res = 1;\n\n while(b > 0) {\n\n if((b&1) == 1) {\n\n res = (res * a)%mod;\n\n }\n\n a = (a * a)%mod;\n\n b >>= 1;\n\n }\n\n return res;\n\n }\n\n\n\n \/\/ Find nCr\n\n public static long nCr(int n, int r) {\n\n if(r < 0 || r > n) {\n\n return 0;\n\n }\n\n long ans = fact(n) \/ (fact(r) * fact(n-r));\n\n return ans;\n\n }\n\n\n\n \/\/ Find nPr\n\n public static long nPr(int n, int r) {\n\n if(r < 0 || r > n) {\n\n return 0;\n\n }\n\n long ans = fact(n) \/ fact(r);\n\n return ans;\n\n }\n\n\n\n\n\n \/\/ sort all characters of a string\n\n public static String sortString(String inputString) {\n\n char tempArray[] = inputString.toCharArray();\n\n Arrays.sort(tempArray);\n\n return new String(tempArray);\n\n }\n\n\n\n \/\/ User defined class for fast I\/O\n\n static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n \n\n public FastReader() {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n \n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n }\n\n catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n boolean hasNext() {\n\n if (st != null && st.hasMoreTokens()) {\n\n return true;\n\n }\n\n String tmp;\n\n try {\n\n br.mark(1000);\n\n tmp = br.readLine();\n\n if (tmp == null) {\n\n return false;\n\n }\n\n br.reset();\n\n } catch (IOException e) {\n\n return false;\n\n }\n\n return true;\n\n }\n\n \n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n \n\n long nextLong() {\n\n return Long.parseLong(next()); \n\n }\n\n \n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n \n\n float nextFloat() {\n\n return Float.parseFloat(next());\n\n }\n\n \n\n boolean nextBoolean() {\n\n return Boolean.parseBoolean(next());\n\n }\n\n \n\n String nextLine() {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n }\n\n catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n\n\n int[] nextArray(int n) {\n\n int[] a = new int[n];\n\n for(int i=0; i 94 ^ 126 ~\n\n 31 US (unit separator) 63 ? 95 _ 127 DEL\n\n *\/\n\n\n\n\n\n \n\n\/\/ (a\/b)%mod == (a * moduloInverse(b)) % mod;\n\n\/\/ moduloInverse(b) = power(b, mod-2);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","language":"java"} -{"contest_id":"1301","problem_id":"D","statement":"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\u22122n\u22122m)(4nm\u22122n\u22122m) 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\u22121,j)(i\u22121,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j\u22121)(i,j\u22121); 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\u2264n,m\u22645001\u2264n,m\u2264500, 1\u2264k\u22641091\u2264k\u2264109), 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\u2264a\u226430001\u2264a\u22643000)\u00a0\u2014 the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1\u2264f\u22641091\u2264f\u2264109) 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\nOutputCopyYES\n2\n2 R\n2 L\nInputCopy3 3 1000000000\nOutputCopyNO\nInputCopy3 3 8\nOutputCopyYES\n3\n2 R\n2 D\n1 LLRR\nInputCopy4 4 9\nOutputCopyYES\n1\n3 RLD\nInputCopy3 4 16\nOutputCopyYES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D\nNoteThe 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):","tags":["constructive algorithms","graphs","implementation"],"code":"\/**\n * @author derrick20\n *\/\nimport java.io.*;\nimport java.util.*;\n\npublic class TimeToRun {\n public static void main(String[] args) throws Exception {\n FastScanner sc = new FastScanner();\n PrintWriter out = new PrintWriter(System.out);\n\n int N = sc.nextInt();\n int M = sc.nextInt();\n int K = sc.nextInt();\n\n if (K > 4 * M * N - 2 * M - 2 * N) {\n out.println(\"NO\");\n }\n else {\n ArrayList f = new ArrayList<>();\n ArrayList dir = new ArrayList<>();\n for (int i = 0; i < M - 1; i++) {\n if (N > 1) {\n f.add(N - 1);\n dir.add('D');\n f.add(N - 1);\n dir.add('U');\n }\n f.add(1);\n dir.add('R');\n }\n for (int i = 0; i < N - 1; i++) {\n f.add(1);\n dir.add('D');\n if (M > 1) {\n f.add(M - 1);\n dir.add('L');\n f.add(M - 1);\n dir.add('R');\n }\n }\n if (N > 1) {\n f.add(N - 1);\n dir.add('U');\n }\n if (M > 1) {\n f.add(M - 1);\n dir.add('L');\n }\n\n int steps = 0;\n int ptr = 0;\n ArrayList ansSteps = new ArrayList<>();\n ArrayList ansDir = new ArrayList<>();\n while (ptr < f.size() && steps + f.get(ptr) <= K) {\n steps += f.get(ptr);\n ansSteps.add(f.get(ptr));\n ansDir.add(dir.get(ptr));\n ptr++;\n }\n if (steps < K) {\n ansSteps.add(K - steps);\n ansDir.add(dir.get(ptr));\n }\n out.println(\"YES\");\n out.println(ansSteps.size());\n for (int i = 0; i < ansSteps.size(); i++) {\n out.println(ansSteps.get(i) + \" \" + ansDir.get(i));\n }\n }\n\n out.close();\n }\n\n static class FastScanner {\n private int BS = 1<<16;\n private char NC = (char)0;\n private byte[] buf = new byte[BS];\n private int bId = 0, size = 0;\n private char c = NC;\n private double cnt = 1;\n private BufferedInputStream in;\n\n public FastScanner() {\n in = new BufferedInputStream(System.in, BS);\n }\n\n public FastScanner(String s) {\n try {\n in = new BufferedInputStream(new FileInputStream(new File(s)), BS);\n }\n catch (Exception e) {\n in = new BufferedInputStream(System.in, BS);\n }\n }\n\n private char getChar(){\n while(bId==size) {\n try {\n size = in.read(buf);\n }catch(Exception e) {\n return NC;\n }\n if(size==-1)return NC;\n bId=0;\n }\n return (char)buf[bId++];\n }\n\n public int nextInt() {\n return (int)nextLong();\n }\n\n public int[] nextInts(int N) {\n int[] res = new int[N];\n for (int i = 0; i < N; i++) {\n res[i] = (int) nextLong();\n }\n return res;\n }\n\n public long[] nextLongs(int N) {\n long[] res = new long[N];\n for (int i = 0; i < N; i++) {\n res[i] = nextLong();\n }\n return res;\n }\n\n public long nextLong() {\n cnt=1;\n boolean neg = false;\n if(c==NC)c=getChar();\n for(;(c<'0' || c>'9'); c = getChar()) {\n if(c=='-')neg=true;\n }\n long res = 0;\n for(; c>='0' && c <='9'; c=getChar()) {\n res = (res<<3)+(res<<1)+c-'0';\n cnt*=10;\n }\n return neg?-res:res;\n }\n\n public double nextDouble() {\n double cur = nextLong();\n return c!='.' ? cur:cur+nextLong()\/cnt;\n }\n\n public String next() {\n StringBuilder res = new StringBuilder();\n while(c<=32)c=getChar();\n while(c>32) {\n res.append(c);\n c=getChar();\n }\n return res.toString();\n }\n\n public String nextLine() {\n StringBuilder res = new StringBuilder();\n while(c<=32)c=getChar();\n while(c!='\\n') {\n res.append(c);\n c=getChar();\n }\n return res.toString();\n }\n\n public boolean hasNext() {\n if(c>32)return true;\n while(true) {\n c=getChar();\n if(c==NC)return false;\n else if(c>32)return true;\n }\n }\n }\n}","language":"java"} -{"contest_id":"1305","problem_id":"D","statement":"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 \u230an2\u230b\u230an2\u230b 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\u2264n\u226410002\u2264n\u22641000), the number of vertices of the tree.Then you will read n\u22121n\u22121 lines, the ii-th of them has two integers xixi and yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n, xi\u2260yixi\u2260yi), 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\u2264u,v\u2264n1\u2264u,v\u2264n) 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 \u230an2\u230b\u230an2\u230b queries, the program will print \u22121\u22121 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 \u230an2\u230b\u230an2\u230b 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\u2264n\u226410002\u2264n\u22641000, 1\u2264r\u2264n1\u2264r\u2264n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n\u22121n\u22121 lines should contain two integers xixi and yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n)\u00a0\u2014 denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4\n\nOutputCopy\n\n\n\n\n\n? 5 6\n\n? 3 1\n\n? 1 2\n\n! 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:","tags":["constructive algorithms","dfs and similar","interactive","trees"],"code":"import java.util.*;\n\nimport java.io.*;\n\n\n\npublic class OTCD {\n\n public static void main(String[] args) {\n\n MyScanner sc = new MyScanner();\n\n \/\/PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));\n\n int n = sc.nextInt();\n\n ArrayList [] adj = new ArrayList[n + 1];\n\n for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();\n\n for (int i = 0; i < n - 1; i++) {\n\n int x = sc.nextInt(); int y = sc.nextInt();\n\n adj[x].add(y); adj[y].add(x);\n\n }\n\n boolean [] bad = new boolean[n + 1];\n\n while (true) {\n\n ArrayList a = new ArrayList<>();\n\n for (int i = 1; i <= n; i++) {\n\n if (!bad[i] && adj[i].size() == 1) a.add(i);\n\n if (a.size() == 2) break;\n\n }\n\n if (a.size() == 0) {\n\n for (int i = 1; i <= n; i++) {\n\n if (adj[i].size() == 0) {\n\n System.out.println(\"! \" + i); return;\n\n }\n\n }\n\n }\n\n System.out.println(\"? \" + a.get(0) + \" \" + a.get(1));\n\n System.out.flush();\n\n int lca = sc.nextInt();\n\n if (lca == a.get(0) || lca == a.get(1)) {\n\n System.out.println(\"! \" + lca);\n\n return;\n\n } else {\n\n adj[adj[a.get(0)].get(0)].remove(a.get(0));\n\n adj[adj[a.get(1)].get(0)].remove(a.get(1));\n\n bad[a.get(0)] = true; bad[a.get(1)] = true;\n\n }\n\n }\n\n \/\/out.close();\n\n }\n\n\n\n\n\n \/\/-----------MyScanner class for faster input----------\n\n public static class MyScanner {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public MyScanner() {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n\n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n\n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n String nextLine() {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n\n\n\n\n }\n\n\n\n}","language":"java"} -{"contest_id":"1325","problem_id":"E","statement":"E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.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.InputThe first line contains an integer nn (1\u2264n\u22641051\u2264n\u2264105)\u00a0\u2014 the length of aa.The second line contains nn integers a1a1, a2a2, \u2026\u2026, anan (1\u2264ai\u22641061\u2264ai\u2264106)\u00a0\u2014 the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print \"-1\".ExamplesInputCopy3\n1 4 6\nOutputCopy1InputCopy4\n2 3 6 6\nOutputCopy2InputCopy3\n6 15 10\nOutputCopy3InputCopy4\n2 3 5 7\nOutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence.","tags":["brute force","dfs and similar","graphs","number theory","shortest paths"],"code":"\/\/created by Whiplash99\n\nimport java.io.*;\n\nimport java.util.*;\n\npublic class E\n\n{\n\n private static final int lim=(int)(1e6+5);\n\n private static int[] dist, parent, spf;\n\n private static ArrayList edge[], vis;\n\n\n\n private static void sieve()\n\n {\n\n for(int i=2;i1)\n\n {\n\n int f=spf[N];\n\n int c=0;\n\n\n\n while (spf[N]==f)\n\n {\n\n c^=1;\n\n N\/=f;\n\n }\n\n if(c==1) val*=f;\n\n }\n\n return val;\n\n }\n\n private static int cycleLength(int u)\n\n {\n\n vis.clear();\n\n vis.add(u);\n\n dist[u]=0;\n\n int ans=-1;\n\n\n\n ArrayDeque queue=new ArrayDeque<>();\n\n queue.add(u);\n\n\n\n while (ans==-1&&!queue.isEmpty())\n\n {\n\n int v=queue.poll();\n\n for(int child:edge[v])\n\n {\n\n if(dist[child]==-1)\n\n {\n\n dist[child]=dist[v]+1;\n\n parent[child]=v;\n\n\n\n vis.add(child);\n\n queue.add(child);\n\n }\n\n else if(parent[v]!=child)\n\n {\n\n ans=dist[v]+dist[child]+1;\n\n break;\n\n }\n\n }\n\n }\n\n\n\n for(int i:vis) dist[i]=-1;\n\n return ans;\n\n }\n\n public static void main(String[] args) throws IOException\n\n {\n\n Reader r=new Reader();\n\n int i,N;\n\n\n\n vis=new ArrayList<>();\n\n spf=new int[lim];\n\n dist=new int[lim];\n\n parent=new int[lim];\n\n edge=new ArrayList[lim];\n\n for(i=0;i();\n\n Arrays.fill(dist,-1);\n\n\n\n sieve();\n\n\n\n N=r.nextInt();\n\n int a[]=new int[N];\n\n for(i=0;i='0'&&c<='9');if(neg)return -ret;return ret;\n\n }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;\n\n }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;\n\n }private void fillBuffer() throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1;\n\n }private byte read() throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++];\n\n }public void close() throws IOException{if(din==null) return;din.close();}\n\n }\n\n}","language":"java"} -{"contest_id":"1290","problem_id":"B","statement":"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\u22652k\u22652 and 2k2k non-empty strings s1,t1,s2,t2,\u2026,sk,tks1,t1,s2,t2,\u2026,sk,tk that satisfy the following conditions: If we write the strings s1,s2,\u2026,sks1,s2,\u2026,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,\u2026,tkt1,t2,\u2026,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\u2264l\u2264r\u2264|s|1\u2264l\u2264r\u2264|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\u2264|s|\u22642\u22c51051\u2264|s|\u22642\u22c5105).The second line contains a single integer qq (1\u2264q\u22641051\u2264q\u2264105) \u00a0\u2014 the number of queries.Each of the following qq lines contain two integers ll and rr (1\u2264l\u2264r\u2264|s|1\u2264l\u2264r\u2264|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\n3\n1 1\n2 4\n5 5\nOutputCopyYes\nNo\nYes\nInputCopyaabbbbbbc\n6\n1 2\n2 4\n2 2\n1 9\n5 7\n3 5\nOutputCopyNo\nYes\nYes\nYes\nNo\nNo\nNoteIn 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.","tags":["binary search","constructive algorithms","data structures","strings","two pointers"],"code":"\/\/package round616;\n\nimport java.io.ByteArrayInputStream;\n\nimport java.io.IOException;\n\nimport java.io.InputStream;\n\nimport java.io.PrintWriter;\n\nimport java.util.Arrays;\n\nimport java.util.InputMismatchException;\n\n\n\npublic class B {\n\n\tInputStream is;\n\n\tPrintWriter out;\n\n\tString INPUT = \"\";\n\n\t\n\n\tvoid solve()\n\n\t{\n\n\t\tchar[] s = ns().toCharArray();\n\n\t\tint n = s.length;\n\n\t\tint[][] f = new int[26][n+1];\n\n\t\tfor(int i = 0;i < n;i++){\n\n\t\t\tf[s[i]-'a'][i+1]++;\n\n\t\t\tfor(int j = 0;j < 26;j++){\n\n\t\t\t\tf[j][i+1] += f[j][i];\n\n\t\t\t}\n\n\t\t}\n\n\t\tfor(int Q = ni();Q > 0;Q--){\n\n\t\t\tint l = ni()-1, r = ni()-1;\n\n\t\t\tint fr = 0;\n\n\t\t\tfor(int i = 0;i < 26;i++){\n\n\t\t\t\tif(f[i][r+1] - f[i][l] > 0){\n\n\t\t\t\t\tfr++;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif(l == r){\n\n\t\t\t\tout.println(\"Yes\");\n\n\t\t\t}else if(fr > 2){\n\n\t\t\t\tout.println(\"Yes\");\n\n\t\t\t}else if(fr == 1){\n\n\t\t\t\tout.println(\"No\");\n\n\t\t\t}else if(s[l] == s[r]){\n\n\t\t\t\tout.println(\"No\");\n\n\t\t\t}else{\n\n\t\t\t\tout.println(\"Yes\");\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t\n\n\tvoid run() throws Exception\n\n\t{\n\n\t\tis = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());\n\n\t\tout = new PrintWriter(System.out);\n\n\t\t\n\n\t\tlong s = System.currentTimeMillis();\n\n\t\tsolve();\n\n\t\tout.flush();\n\n\t\ttr(System.currentTimeMillis()-s+\"ms\");\n\n\t}\n\n\t\n\n\tpublic static void main(String[] args) throws Exception { new B().run(); }\n\n\t\n\n\tprivate byte[] inbuf = new byte[1024];\n\n\tpublic int lenbuf = 0, ptrbuf = 0;\n\n\t\n\n\tprivate int readByte()\n\n\t{\n\n\t\tif(lenbuf == -1)throw new InputMismatchException();\n\n\t\tif(ptrbuf >= lenbuf){\n\n\t\t\tptrbuf = 0;\n\n\t\t\ttry { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }\n\n\t\t\tif(lenbuf <= 0)return -1;\n\n\t\t}\n\n\t\treturn inbuf[ptrbuf++];\n\n\t}\n\n\t\n\n\tprivate boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }\n\n\tprivate int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }\n\n\t\n\n\tprivate double nd() { return Double.parseDouble(ns()); }\n\n\tprivate char nc() { return (char)skip(); }\n\n\t\n\n\tprivate String ns()\n\n\t{\n\n\t\tint b = skip();\n\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\twhile(!(isSpaceChar(b))){ \/\/ when nextLine, (isSpaceChar(b) && b != ' ')\n\n\t\t\tsb.appendCodePoint(b);\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t\treturn sb.toString();\n\n\t}\n\n\t\n\n\tprivate char[] ns(int n)\n\n\t{\n\n\t\tchar[] buf = new char[n];\n\n\t\tint b = skip(), p = 0;\n\n\t\twhile(p < n && !(isSpaceChar(b))){\n\n\t\t\tbuf[p++] = (char)b;\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t\treturn n == p ? buf : Arrays.copyOf(buf, p);\n\n\t}\n\n\t\n\n\tprivate char[][] nm(int n, int m)\n\n\t{\n\n\t\tchar[][] map = new char[n][];\n\n\t\tfor(int i = 0;i < n;i++)map[i] = ns(m);\n\n\t\treturn map;\n\n\t}\n\n\t\n\n\tprivate int[] na(int n)\n\n\t{\n\n\t\tint[] a = new int[n];\n\n\t\tfor(int i = 0;i < n;i++)a[i] = ni();\n\n\t\treturn a;\n\n\t}\n\n\t\n\n\tprivate int ni()\n\n\t{\n\n\t\tint num = 0, b;\n\n\t\tboolean minus = false;\n\n\t\twhile((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));\n\n\t\tif(b == '-'){\n\n\t\t\tminus = true;\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t\t\n\n\t\twhile(true){\n\n\t\t\tif(b >= '0' && b <= '9'){\n\n\t\t\t\tnum = num * 10 + (b - '0');\n\n\t\t\t}else{\n\n\t\t\t\treturn minus ? -num : num;\n\n\t\t\t}\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t}\n\n\t\n\n\tprivate long nl()\n\n\t{\n\n\t\tlong num = 0;\n\n\t\tint b;\n\n\t\tboolean minus = false;\n\n\t\twhile((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));\n\n\t\tif(b == '-'){\n\n\t\t\tminus = true;\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t\t\n\n\t\twhile(true){\n\n\t\t\tif(b >= '0' && b <= '9'){\n\n\t\t\t\tnum = num * 10 + (b - '0');\n\n\t\t\t}else{\n\n\t\t\t\treturn minus ? -num : num;\n\n\t\t\t}\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t}\n\n\t\n\n\tprivate boolean oj = System.getProperty(\"ONLINE_JUDGE\") != null;\n\n\tprivate void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }\n\n}\n\n","language":"java"} -{"contest_id":"1292","problem_id":"B","statement":"B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIV\u039b - \u6f02\u6d41 KIV\u039b & 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\u22c5xi\u22121+bx,ay\u22c5yi\u22121+by)(ax\u22c5xi\u22121+bx,ay\u22c5yi\u22121+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\u22121,y)(x\u22121,y), (x+1,y)(x+1,y), (x,y\u22121)(x,y\u22121) 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\u2264x0,y0\u226410161\u2264x0,y0\u22641016, 2\u2264ax,ay\u22641002\u2264ax,ay\u2264100, 0\u2264bx,by\u226410160\u2264bx,by\u22641016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1\u2264xs,ys,t\u226410161\u2264xs,ys,t\u22641016)\u00a0\u2013 the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer\u00a0\u2014 the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0\n2 4 20\nOutputCopy3InputCopy1 1 2 3 1 0\n15 27 26\nOutputCopy2InputCopy1 1 2 3 1 0\n2 2 1\nOutputCopy0NoteIn 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\u22122|+|3\u22124|=2|3\u22122|+|3\u22124|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1\u22123|+|1\u22123|=4|1\u22123|+|1\u22123|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7\u22121|+|9\u22121|=14|7\u22121|+|9\u22121|=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\u22127|+|27\u22129|=26|15\u22127|+|27\u22129|=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.","tags":["brute force","constructive algorithms","geometry","greedy","implementation"],"code":"import java.util.*;\n\nimport java.io.*;\n\npublic class Main\n\n{\n\n static class Reader \n\n { \n\n final private int BUFFER_SIZE = 1 << 16; \n\n private DataInputStream din; \n\n private byte[] buffer; \n\n private int bufferPointer, bytesRead; \n\n \n\n public Reader() \n\n { \n\n din = new DataInputStream(System.in); \n\n buffer = new byte[BUFFER_SIZE]; \n\n bufferPointer = bytesRead = 0; \n\n } \n\n \n\n public Reader(String file_name) throws IOException \n\n { \n\n din = new DataInputStream(new FileInputStream(file_name)); \n\n buffer = new byte[BUFFER_SIZE]; \n\n bufferPointer = bytesRead = 0; \n\n } \n\n \n\n public String readLine() throws IOException \n\n { \n\n byte[] buf = new byte[64]; \/\/ line length \n\n int cnt = 0, c; \n\n while ((c = read()) != -1) \n\n { \n\n if (c == '\\n') \n\n break; \n\n buf[cnt++] = (byte) c; \n\n } \n\n return new String(buf, 0, cnt); \n\n } \n\n \n\n public int nextInt() throws IOException \n\n { \n\n int ret = 0; \n\n byte c = read(); \n\n while (c <= ' ') \n\n c = read(); \n\n boolean neg = (c == '-'); \n\n if (neg) \n\n c = read(); \n\n do\n\n { \n\n ret = ret * 10 + c - '0'; \n\n } while ((c = read()) >= '0' && c <= '9'); \n\n \n\n if (neg) \n\n return -ret; \n\n return ret; \n\n } \n\n \n\n public long nextLong() throws IOException \n\n { \n\n long ret = 0; \n\n byte c = read(); \n\n while (c <= ' ') \n\n c = read(); \n\n boolean neg = (c == '-'); \n\n if (neg) \n\n c = read(); \n\n do { \n\n ret = ret * 10 + c - '0'; \n\n } \n\n while ((c = read()) >= '0' && c <= '9'); \n\n if (neg) \n\n return -ret; \n\n return ret; \n\n } \n\n \n\n public double nextDouble() throws IOException \n\n { \n\n double ret = 0, div = 1; \n\n byte c = read(); \n\n while (c <= ' ') \n\n c = read(); \n\n boolean neg = (c == '-'); \n\n if (neg) \n\n c = read(); \n\n \n\n do { \n\n ret = ret * 10 + c - '0'; \n\n } \n\n while ((c = read()) >= '0' && c <= '9'); \n\n \n\n if (c == '.') \n\n { \n\n while ((c = read()) >= '0' && c <= '9') \n\n { \n\n ret += (c - '0') \/ (div *= 10); \n\n } \n\n } \n\n \n\n if (neg) \n\n return -ret; \n\n return ret; \n\n } \n\n \n\n private void fillBuffer() throws IOException \n\n { \n\n bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); \n\n if (bytesRead == -1) \n\n buffer[0] = -1; \n\n } \n\n \n\n private byte read() throws IOException \n\n { \n\n if (bufferPointer == bytesRead) \n\n fillBuffer(); \n\n return buffer[bufferPointer++]; \n\n } \n\n \n\n public void close() throws IOException \n\n { \n\n if (din == null) \n\n return; \n\n din.close(); \n\n } \n\n }\n\n public static long gcd(long a,long b)\n\n { \n\n if(b%a==0)\n\n return a;\n\n return gcd(b%a,a);\n\n }\n\n public static void main(String args[])throws Exception\n\n {\n\n Reader sc=new Reader();\n\n \/\/Scanner sc=new Scanner(System.in);\n\n PrintWriter pw=new PrintWriter(System.out);\n\n int tc=1;\/\/sc.nextInt();\n\n while(tc-->0)\n\n {\n\n long x0=sc.nextLong();\n\n long y0=sc.nextLong();\n\n long ax=sc.nextLong();\n\n long ay=sc.nextLong();\n\n long bx=sc.nextLong();\n\n long by=sc.nextLong();\n\n long xs=sc.nextLong();\n\n long ys=sc.nextLong();\n\n long t=sc.nextLong();\n\n long x=x0,y=y0;\n\n long ans=0;\n\n while(x<=(long)1e17&&y<=(long)1e17)\n\n {\n\n \n\n long mindist=(long)Math.abs(xs-x)+(long)Math.abs(ys-y);\n\n if(mindist<=t)\n\n {\n\n long s=t-mindist;\n\n long moves=1;\n\n long minx=x,miny=y;\n\n while(minx>x0&&miny>y0)\n\n {\n\n mindist=minx-(minx-bx)\/ax+miny-(miny-by)\/ay;\n\n minx=(minx-bx)\/ax;\n\n miny=(miny-by)\/ay;\n\n if(s-mindist>=0)\n\n {\n\n moves++;\n\n s-=mindist;\n\n }\n\n else\n\n break;\n\n }\n\n if(minx==x0&&miny==y0)\n\n {\n\n minx=x*ax+bx;\n\n miny=y*ay+by;\n\n mindist=minx-x0+miny-y0;\n\n if(s>=mindist)\n\n {\n\n s-=mindist;\n\n moves++;\n\n while(s>0)\n\n {\n\n mindist=minx*ax+bx-minx+miny*ay+by-miny;\n\n minx=minx*ax+bx;\n\n miny=miny*ay+by;\n\n if(s-mindist>=0)\n\n {\n\n moves++;\n\n s-=mindist;\n\n }\n\n else\n\n break;\n\n }\n\n }\n\n }\n\n ans=Math.max(ans,moves);\n\n }\n\n x=ax*x+bx;\n\n y=ay*y+by;\n\n }\n\n pw.println(ans);\n\n }\n\n pw.flush();\n\n pw.close();\n\n }\n\n}","language":"java"} -{"contest_id":"1303","problem_id":"A","statement":"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\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1\u2264|s|\u22641001\u2264|s|\u2264100); 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\n010011\n0\n1111000\nOutputCopy2\n0\n0\nNoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).","tags":["implementation","strings"],"code":"import java.util.*;\n\npublic class ErasingZeros {\n\n\n\n\tpublic static void main(String[] args) {\n\n\t\tScanner sc = new Scanner(System.in);\n\n\t\tint n = sc.nextInt();\n\n\t\tfor(int i = 0 ; i 0){\n\n String S = sc.next();\n\n String G = sc.next();\n\n \/\/ now what \n\n ArrayList> A = new ArrayList<>();\n\n for(int i=0 ;i<27;i++){\n\n A.add(new TreeSet<>());\n\n }\n\n for(int i =0;i primes;\n\n\n\n public void setSieve() {\n\n primes = new ArrayList<>();\n\n sieve = new int[MAXN];\n\n int i, j;\n\n for (i = 2; i*i < MAXN; ++i)\n\n if (sieve[i] == 0) {\n\n primes.add(i);\n\n for (j = i*i; j < MAXN; j += i) {\n\n sieve[j] = i;\n\n }\n\n }\n\n }\n\n\n\n\n\n public static long[] factorial;\n\n\n\n public void setFactorial() {\n\n factorial = new long[MAXN];\n\n factorial[0] = 1;\n\n for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD;\n\n }\n\n\n\n public long getFactorial(int n) {\n\n if (factorial == null) setFactorial();\n\n return factorial[n];\n\n }\n\n\n\n public long ncr(int n, int r) {\n\n if (r > n) return 0;\n\n if (factorial == null) setFactorial();\n\n long numerator = factorial[n];\n\n long denominator = factorial[r] * factorial[n - r] % MOD;\n\n return numerator * pow(denominator, MOD - 2, MOD) % MOD;\n\n }\n\n\n\n\n\n public long[] getLongArray(int size) throws Exception {\n\n long[] ar = new long[size];\n\n for (int i = 0; i < size; ++i) ar[i] = nextLong();\n\n return ar;\n\n }\n\n\n\n public int[] getIntArray(int size) throws Exception {\n\n int[] ar = new int[size];\n\n for (int i = 0; i < size; ++i) ar[i] = nextInt();\n\n return ar;\n\n }\n\n\n\n public long gcd(long a, long b) {\n\n return b == 0 ? a : gcd(b, a % b);\n\n }\n\n\n\n public int gcd(int a, int b) {\n\n return b == 0 ? a : gcd(b, a % b);\n\n }\n\n\n\n\n\n public long max(long[] ar) {\n\n long ret = ar[0];\n\n for (long itr : ar) ret = Math.max(ret, itr);\n\n return ret;\n\n }\n\n\n\n public int max(int[] ar) {\n\n int ret = ar[0];\n\n for (int itr : ar) ret = Math.max(ret, itr);\n\n return ret;\n\n }\n\n\n\n public long min(long[] ar) {\n\n long ret = ar[0];\n\n for (long itr : ar) ret = Math.min(ret, itr);\n\n return ret;\n\n }\n\n\n\n public int min(int[] ar) {\n\n int ret = ar[0];\n\n for (int itr : ar) ret = Math.min(ret, itr);\n\n return ret;\n\n }\n\n\n\n\n\n public long sum(long[] ar) {\n\n long sum = 0;\n\n for (long itr : ar) sum += itr;\n\n return sum;\n\n }\n\n\n\n public long sum(int[] ar) {\n\n long sum = 0;\n\n for (int itr : ar) sum += itr;\n\n return sum;\n\n }\n\n\n\n public void shuffle(int[] ar) {\n\n int r;\n\n for (int i = 0; i < ar.length; ++i) {\n\n r = rnd.nextInt(ar.length);\n\n if (r != i) {\n\n ar[i] ^= ar[r];\n\n ar[r] ^= ar[i];\n\n ar[i] ^= ar[r];\n\n }\n\n }\n\n }\n\n\n\n public void shuffle(long[] ar) {\n\n int r;\n\n for (int i = 0; i < ar.length; ++i) {\n\n r = rnd.nextInt(ar.length);\n\n if (r != i) {\n\n ar[i] ^= ar[r];\n\n ar[r] ^= ar[i];\n\n ar[i] ^= ar[r];\n\n }\n\n }\n\n }\n\n\n\n public long pow(long base, long exp, long MOD) {\n\n base %= MOD;\n\n long ret = 1;\n\n while (exp > 0) {\n\n if ((exp & 1) == 1) ret = ret * base % MOD;\n\n base = base * base % MOD;\n\n exp >>= 1;\n\n }\n\n return ret;\n\n }\n\n\n\n\n\n static byte[] buf = new byte[1000_006];\n\n static int index, total;\n\n static InputStream in;\n\n static BufferedWriter bw;\n\n\n\n\n\n public void initIO(InputStream is, OutputStream os) {\n\n try {\n\n in = is;\n\n bw = new BufferedWriter(new OutputStreamWriter(os));\n\n } catch (Exception e) {\n\n }\n\n }\n\n\n\n public void initIO(String inputFile, String outputFile) {\n\n try {\n\n in = new FileInputStream(inputFile);\n\n bw = new BufferedWriter(new OutputStreamWriter(\n\n new FileOutputStream(outputFile)));\n\n } catch (Exception e) {\n\n }\n\n }\n\n\n\n private int scan() throws Exception {\n\n if (index >= total) {\n\n index = 0;\n\n total = in.read(buf);\n\n if (total <= 0)\n\n return -1;\n\n }\n\n return buf[index++];\n\n }\n\n\n\n public String nextLine() throws Exception {\n\n int c;\n\n for (c = scan(); c <= 32; c = scan()) ;\n\n StringBuilder sb = new StringBuilder();\n\n for (; c >= 32; c = scan())\n\n sb.append((char) c);\n\n return sb.toString();\n\n }\n\n\n\n public String next() throws Exception {\n\n int c;\n\n for (c = scan(); c <= 32; c = scan()) ;\n\n StringBuilder sb = new StringBuilder();\n\n for (; c > 32; c = scan())\n\n sb.append((char) c);\n\n return sb.toString();\n\n }\n\n\n\n public int nextInt() throws Exception {\n\n int c, val = 0;\n\n for (c = scan(); c <= 32; c = scan()) ;\n\n boolean neg = c == '-';\n\n if (c == '-' || c == '+')\n\n c = scan();\n\n for (; c >= '0' && c <= '9'; c = scan())\n\n val = (val << 3) + (val << 1) + (c & 15);\n\n return neg ? -val : val;\n\n }\n\n\n\n public long nextLong() throws Exception {\n\n int c;\n\n long val = 0;\n\n for (c = scan(); c <= 32; c = scan()) ;\n\n boolean neg = c == '-';\n\n if (c == '-' || c == '+')\n\n c = scan();\n\n for (; c >= '0' && c <= '9'; c = scan())\n\n val = (val << 3) + (val << 1) + (c & 15);\n\n return neg ? -val : val;\n\n }\n\n\n\n public void print(Object a) throws Exception {\n\n bw.write(a.toString());\n\n }\n\n\n\n public void printsp(Object a) throws Exception {\n\n print(a);\n\n print(\" \");\n\n }\n\n\n\n public void println() throws Exception {\n\n bw.write(\"\\n\");\n\n }\n\n\n\n public void printArray(int[] arr) throws Exception{\n\n for(int i = 0;i 0)\n\n {\n\n int arr[] = new int[3];\n\n arr[0] = input.nextInt();\n\n\t\t arr[1] = input.nextInt();\n\n\t\t arr[2] = input.nextInt();\n\n\t\t Arrays.sort(arr);\n\n\t\t int a = arr[0];\n\n\t\t int b = arr[1];\n\n\t\t int c = arr[2];\n\n\t\t int count = 0;\n\n\t\t if(a != 0){\n\n\t\t count++;\n\n\t\t a--;\n\n\t\t }\n\n\t\t if(b != 0){\n\n\t\t count++;\n\n\t\t b--;\n\n\t\t }\n\n\t\t if(c != 0){\n\n\t\t count++;\n\n\t\t c--;\n\n\t\t }\n\n\t\t if(c != 0 && b != 0){\n\n\t\t count++;\n\n\t\t c--;\n\n\t\t b--;\n\n\t\t }\n\n\t\t if(c != 0 && a != 0){\n\n\t\t count++;\n\n\t\t c--;\n\n\t\t a--;\n\n\t\t }\n\n\t\t if(b != 0 && a != 0){\n\n\t\t count++;\n\n\t\t a--;\n\n\t\t b--;\n\n\t\t }\n\n \n\n if(a > 0 && b > 0 && c > 0)\n\n {\n\n a--; b--; c--; count++;\n\n }\n\n System.out.println(count);\n\n }\n\n input.close();\n\n }\n\n}\n\n","language":"java"} -{"contest_id":"1303","problem_id":"E","statement":"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,\u2026,siksi1,si2,\u2026,sik where 1\u2264i1 0;T--) {\n\n\t\t\tchar[] s = ns().toCharArray();\n\n\t\t\tchar[] t = ns().toCharArray();\n\n\t\t\tif(ok(s, t)) {\n\n\t\t\t\tout.println(\"YES\");\n\n\t\t\t}else {\n\n\t\t\t\tout.println(\"NO\");\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t\n\n\tboolean ok(char[] s, char[] t)\n\n\t{\n\n\t\tint n = s.length, m = t.length;\n\n\t\tfor(int K = 0;K < m;K++) {\n\n\t\t\t\/\/ [0,K), [K,m)\n\n\t\t\tint[] dp = new int[K+1];\n\n\t\t\tArrays.fill(dp, -999999999);\n\n\t\t\tdp[0] = 0;\n\n\t\t\tfor(int i = 0;i < n;i++) {\n\n\t\t\t\tfor(int j = K;j >= 0;j--) {\n\n\t\t\t\t\tif(dp[j] >= 0) {\n\n\t\t\t\t\t\tif(j < K && s[i] == t[j]) {\n\n\t\t\t\t\t\t\tdp[j+1] = Math.max(dp[j+1], dp[j]);\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(dp[j] < m-K && s[i] == t[K+dp[j]]) {\n\n\t\t\t\t\t\t\tdp[j]++;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif(dp[K] == m-K)return true;\n\n\t\t}\n\n\t\treturn false;\n\n\t}\n\n\t\n\n\tvoid run() throws Exception\n\n\t{\n\n\t\tis = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());\n\n\t\tout = new PrintWriter(System.out);\n\n\t\t\n\n\t\tlong s = System.currentTimeMillis();\n\n\t\tsolve();\n\n\t\tout.flush();\n\n\t\ttr(System.currentTimeMillis()-s+\"ms\");\n\n\t}\n\n\t\n\n\tpublic static void main(String[] args) throws Exception { new E().run(); }\n\n\t\n\n\tprivate byte[] inbuf = new byte[1024];\n\n\tpublic int lenbuf = 0, ptrbuf = 0;\n\n\t\n\n\tprivate int readByte()\n\n\t{\n\n\t\tif(lenbuf == -1)throw new InputMismatchException();\n\n\t\tif(ptrbuf >= lenbuf){\n\n\t\t\tptrbuf = 0;\n\n\t\t\ttry { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }\n\n\t\t\tif(lenbuf <= 0)return -1;\n\n\t\t}\n\n\t\treturn inbuf[ptrbuf++];\n\n\t}\n\n\t\n\n\tprivate boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }\n\n\tprivate int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }\n\n\t\n\n\tprivate double nd() { return Double.parseDouble(ns()); }\n\n\tprivate char nc() { return (char)skip(); }\n\n\t\n\n\tprivate String ns()\n\n\t{\n\n\t\tint b = skip();\n\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\twhile(!(isSpaceChar(b))){ \/\/ when nextLine, (isSpaceChar(b) && b != ' ')\n\n\t\t\tsb.appendCodePoint(b);\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t\treturn sb.toString();\n\n\t}\n\n\t\n\n\tprivate char[] ns(int n)\n\n\t{\n\n\t\tchar[] buf = new char[n];\n\n\t\tint b = skip(), p = 0;\n\n\t\twhile(p < n && !(isSpaceChar(b))){\n\n\t\t\tbuf[p++] = (char)b;\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t\treturn n == p ? buf : Arrays.copyOf(buf, p);\n\n\t}\n\n\t\n\n\tprivate char[][] nm(int n, int m)\n\n\t{\n\n\t\tchar[][] map = new char[n][];\n\n\t\tfor(int i = 0;i < n;i++)map[i] = ns(m);\n\n\t\treturn map;\n\n\t}\n\n\t\n\n\tprivate int[] na(int n)\n\n\t{\n\n\t\tint[] a = new int[n];\n\n\t\tfor(int i = 0;i < n;i++)a[i] = ni();\n\n\t\treturn a;\n\n\t}\n\n\t\n\n\tprivate int ni()\n\n\t{\n\n\t\tint num = 0, b;\n\n\t\tboolean minus = false;\n\n\t\twhile((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));\n\n\t\tif(b == '-'){\n\n\t\t\tminus = true;\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t\t\n\n\t\twhile(true){\n\n\t\t\tif(b >= '0' && b <= '9'){\n\n\t\t\t\tnum = num * 10 + (b - '0');\n\n\t\t\t}else{\n\n\t\t\t\treturn minus ? -num : num;\n\n\t\t\t}\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t}\n\n\t\n\n\tprivate long nl()\n\n\t{\n\n\t\tlong num = 0;\n\n\t\tint b;\n\n\t\tboolean minus = false;\n\n\t\twhile((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));\n\n\t\tif(b == '-'){\n\n\t\t\tminus = true;\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t\t\n\n\t\twhile(true){\n\n\t\t\tif(b >= '0' && b <= '9'){\n\n\t\t\t\tnum = num * 10 + (b - '0');\n\n\t\t\t}else{\n\n\t\t\t\treturn minus ? -num : num;\n\n\t\t\t}\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t}\n\n\t\n\n\tprivate boolean oj = System.getProperty(\"ONLINE_JUDGE\") != null;\n\n\tprivate void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }\n\n}\n\n","language":"java"} -{"contest_id":"1324","problem_id":"B","statement":"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\u2212i\u22121ai=an\u2212i\u22121 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\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3\u2264n\u226450003\u2264n\u22645000) \u2014 the length of aa. The second line of the test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u2264n1\u2264ai\u2264n), 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 (\u2211n\u22645000\u2211n\u22645000).OutputFor each test case, print the answer \u2014 \"YES\" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and \"NO\" otherwise.ExampleInputCopy5\n3\n1 2 1\n5\n1 2 2 3 2\n3\n1 1 2\n4\n1 2 2 1\n10\n1 1 2 2 3 3 4 4 5 5\nOutputCopyYES\nYES\nNO\nYES\nNO\nNoteIn 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.","tags":["brute force","strings"],"code":"import java.util.*;\n\npublic class YetAnotherPalindromeProblem {\n\n public static void main(String args[]) {\n\n Scanner sr = new Scanner(System.in);\n\n int t = sr.nextInt();\n\n HashMap foundNums = new HashMap();\n\n int prevNum;\n\n int length;\n\n int currentNum;\n\n boolean check;\n\n int count;\n\n for (int u=0;uak+1>\u2026>anak>ak+1>\u2026>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1\u2264i\u2264n1\u2264i\u2264n) such that ai>0ai>0 and assign ai:=ai\u22121ai:=ai\u22121.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u226415\u00a00001\u2264t\u226415\u00a0000) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22643\u22c51051\u2264n\u22643\u22c5105).The second line of each test case contains a sequence of nn non-negative integers a1,\u2026,ana1,\u2026,an (0\u2264ai\u22641090\u2264ai\u2264109).It is guaranteed that the sum of nn over all test cases does not exceed 3\u22c51053\u22c5105.OutputFor each test case, output a single line containing \"Yes\" (without quotes) if it's possible to make the given array sharpened using the described operations, or \"No\" (without quotes) otherwise.ExampleInputCopy10\n1\n248618\n3\n12 10 8\n6\n100 11 15 9 7 8\n4\n0 1 1 0\n2\n0 0\n2\n0 1\n2\n1 0\n2\n1 1\n3\n0 1 0\n3\n1 0 1\nOutputCopyYes\nYes\nYes\nNo\nNo\nYes\nYes\nYes\nYes\nNo\nNoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.","tags":["greedy","implementation"],"code":"\n\nimport java.util.*;\n\nimport java.io.*;\n\n\n\npublic class Main {\n\n\tstatic StringBuilder sb;\n\n\tstatic dsu dsu;\n\n\tstatic long fact[];\n\n\tstatic int mod = (int) (1e9 + 7);\n\nstatic void build(int node, int start, int end,int[]tree,int[]arr) {\n\n if (start == end) {\n\n tree[node] = arr[start];\n\n } else {\n\n int mid = (start + end) \/ 2;\n\n int left = node * 2;\n\n int right = node * 2 + 1;\n\n build(left, start, mid,tree,arr);\n\n build(right, mid + 1, end,tree,arr);\n\n tree[node] = Math.max(tree[left], tree[right]);\n\n }\n\n }\n\n \n\n static int query(int node, int start, int end, int l, int r,int[]tree,int[]arr) {\n\n if (end < l || r < start)return Integer.MIN_VALUE;\n\n\n\n if (start == end) {\n\n return tree[node];\n\n } else if (l <= start && end <= r) {\n\n return tree[node];\n\n } else {\n\n int mid = (start + end) \/ 2;\n\n int left = query(node * 2, start, mid, l, r,tree,arr);\n\n int right = query(node * 2 + 1, mid + 1, end, l, r,tree,arr);\n\n\n\n return Math.max(left, right);\n\n }\n\n }\n\n static int get(int v,int k,int max){\n\n int lo=1;\n\n int hi=k;\n\n int ans=-1;\n\n while(lo<=hi){\n\n int mid=(lo+hi)\/2;\n\n if(v\/mid>max){\n\n lo=mid+1;\n\n }\n\n else{\n\n ans=mid;\n\n hi=mid-1;\n\n }\n\n \n\n \n\n \n\n }\n\n return ans;\n\n }\n\n static long solve( ArrayList ls,long time,long sx,long sy){\n\n \n\n long ans=0;\n\n \n\n for(int i=0;i=0;i--){\n\n\t if(i==n-1)ss[i]=arr[i]-(n-1-i);\n\n\t else ss[i]=Math.min(ss[i+1],arr[i]-(n-1-i));\n\n\t }\n\n\t int t=0;\n\n\t for(int i=0;i=0&&ss[i]>=0){\n\n\t sb.append(\"Yes\\n\");\n\n\t return;\n\n\t }\n\n\t }\n\n\t sb.append(\"No\\n\");\n\n\t \n\n\t}\n\n\tpublic static void main(String[] args) {\n\n\t\tsb = new StringBuilder();\n\n\t\tint test = i();\n\n\t\t\t fact=new long[(int)1e6+10];\n\n\t\t\t fact[0]=fact[1]=1; \n\n\t\t\t for(int i=2;i 0) {\n\n\t\t\tsolve(cnt);\n\n\t\t\tcnt++;\n\n\t\t}\n\n\t\tSystem.out.println(sb);\n\n\n\n\t}\n\n\n\n\t\n\n\n\n\t \n\n\/\/**************NCR%P******************\t \n\n\tstatic long ncr(int n, int r) {\n\n\t\tif (r > n)\n\n\t\t\treturn (long) 0;\n\n\n\n\t\tlong res = fact[n] % mod;\n\n\t\t\/\/ System.out.println(res);\n\n\t\tres = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;\n\n\t\tres = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;\n\n\t\t\/\/ System.out.println(res);\n\n\t\treturn res;\n\n\n\n\t}\n\n\n\n\tstatic long p(long x, long y)\/\/ POWER FXN \/\/\n\n\t{\n\n\t\tif (y == 0)\n\n\t\t\treturn 1;\n\n\n\n\t\tlong res = 1;\n\n\t\twhile (y > 0) {\n\n\t\t\tif (y % 2 == 1) {\n\n\t\t\t\tres = (res * x) ;\n\n\t\t\t\ty--;\n\n\t\t\t}\n\n\n\n\t\t\tx = (x * x);\n\n\t\t\ty = y \/ 2;\n\n\n\n\t\t}\n\n\t\treturn res;\n\n\t}\n\n\n\n\/\/**************END******************\n\n\n\n\t\/\/ *************Disjoint set\n\n\t\/\/ union*********\/\/\n\n\tstatic class dsu {\n\n\t\tint parent[];\n\n\n\n\t\tdsu(int n) {\n\n\t\t\tparent = new int[n];\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t\tparent[i] = i;\n\n\t\t}\n\n\n\n\t\tint find(int a) {\n\n\t\t\tif (parent[a] ==a)\n\n\t\t\t\treturn a;\n\n\t\t\telse {\n\n\t\t\t\tint x = find(parent[a]);\n\n\t\t\t\tparent[a] = x;\n\n\t\t\t\treturn x;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tvoid merge(int a, int b) {\n\n\t\t\ta = find(a);\n\n\t\t\tb = find(b);\n\n\t\t\tif (a == b)\n\n\t\t\t\treturn;\n\n\t\t\tparent[b] = a;\n\n\t\t}\n\n\t}\n\n\n\n\/\/**************PRIME FACTORIZE **********************************\/\/\n\n\tstatic TreeMap prime(long n) {\n\n\t\tTreeMap h = new TreeMap<>();\n\n\t\tlong num = n;\n\n\t\tfor (int i = 2; i <= Math.sqrt(num); i++) {\n\n\t\t\tif (n % i == 0) {\n\n\t\t\t\tint nt = 0;\n\n\t\t\t\twhile (n % i == 0) {\n\n\t\t\t\t\tn = n \/ i;\n\n\t\t\t\t\tnt++;\n\n\t\t\t\t}\n\n\t\t\t\th.put(i, nt);\n\n\t\t\t}\n\n\t\t}\n\n\t\tif (n != 1)\n\n\t\t\th.put((int) n, 1);\n\n\t\treturn h;\n\n\n\n\t}\n\n\n\n\/\/****CLASS PAIR ************************************************\n\n\tstatic class Pair implements Comparable {\n\n\t\tlong x;\n\n\t\tlong y;\n\n\n\n\t\tPair(long x, long y) {\n\n\t\t\tthis.x = x;\n\n\t\t\tthis.y = y;\n\n\t\t}\n\n\n\n\t\tpublic int compareTo(Pair o) {\n\n\t\t\treturn (int) (this.y - o.y);\n\n\n\n\t\t}\n\n\n\n\t}\n\n\/\/****CLASS PAIR **************************************************\n\n\n\n\tstatic class InputReader {\n\n\t\tprivate InputStream stream;\n\n\t\tprivate byte[] buf = new byte[1024];\n\n\t\tprivate int curChar;\n\n\t\tprivate int numChars;\n\n\t\tprivate SpaceCharFilter filter;\n\n\n\n\t\tpublic InputReader(InputStream stream) {\n\n\t\t\tthis.stream = stream;\n\n\t\t}\n\n\n\n\t\tpublic int read() {\n\n\t\t\tif (numChars == -1)\n\n\t\t\t\tthrow new InputMismatchException();\n\n\t\t\tif (curChar >= numChars) {\n\n\t\t\t\tcurChar = 0;\n\n\t\t\t\ttry {\n\n\t\t\t\t\tnumChars = stream.read(buf);\n\n\t\t\t\t} catch (IOException e) {\n\n\t\t\t\t\tthrow new InputMismatchException();\n\n\t\t\t\t}\n\n\t\t\t\tif (numChars <= 0)\n\n\t\t\t\t\treturn -1;\n\n\t\t\t}\n\n\t\t\treturn buf[curChar++];\n\n\t\t}\n\n\n\n\t\tpublic int Int() {\n\n\t\t\tint c = read();\n\n\t\t\twhile (isSpaceChar(c))\n\n\t\t\t\tc = read();\n\n\t\t\tint sgn = 1;\n\n\t\t\tif (c == '-') {\n\n\t\t\t\tsgn = -1;\n\n\t\t\t\tc = read();\n\n\t\t\t}\n\n\t\t\tint res = 0;\n\n\t\t\tdo {\n\n\t\t\t\tif (c < '0' || c > '9')\n\n\t\t\t\t\tthrow new InputMismatchException();\n\n\t\t\t\tres *= 10;\n\n\t\t\t\tres += c - '0';\n\n\t\t\t\tc = read();\n\n\t\t\t} while (!isSpaceChar(c));\n\n\t\t\treturn res * sgn;\n\n\t\t}\n\n\n\n\t\tpublic String String() {\n\n\t\t\tint c = read();\n\n\t\t\twhile (isSpaceChar(c))\n\n\t\t\t\tc = read();\n\n\t\t\tStringBuilder res = new StringBuilder();\n\n\t\t\tdo {\n\n\t\t\t\tres.appendCodePoint(c);\n\n\t\t\t\tc = read();\n\n\t\t\t} while (!isSpaceChar(c));\n\n\t\t\treturn res.toString();\n\n\t\t}\n\n\n\n\t\tpublic boolean isSpaceChar(int c) {\n\n\t\t\tif (filter != null)\n\n\t\t\t\treturn filter.isSpaceChar(c);\n\n\t\t\treturn c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n\n\t\t}\n\n\n\n\t\tpublic String next() {\n\n\t\t\treturn String();\n\n\t\t}\n\n\n\n\t\tpublic interface SpaceCharFilter {\n\n\t\t\tpublic boolean isSpaceChar(int ch);\n\n\t\t}\n\n\t}\n\n\n\n\tstatic class OutputWriter {\n\n\t\tprivate final PrintWriter writer;\n\n\n\n\t\tpublic OutputWriter(OutputStream outputStream) {\n\n\t\t\twriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n\n\t\t}\n\n\n\n\t\tpublic OutputWriter(Writer writer) {\n\n\t\t\tthis.writer = new PrintWriter(writer);\n\n\t\t}\n\n\n\n\t\tpublic void print(Object... objects) {\n\n\t\t\tfor (int i = 0; i < objects.length; i++) {\n\n\t\t\t\tif (i != 0)\n\n\t\t\t\t\twriter.print(' ');\n\n\t\t\t\twriter.print(objects[i]);\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tpublic void printLine(Object... objects) {\n\n\t\t\tprint(objects);\n\n\t\t\twriter.println();\n\n\t\t}\n\n\n\n\t\tpublic void close() {\n\n\t\t\twriter.close();\n\n\t\t}\n\n\n\n\t\tpublic void flush() {\n\n\t\t\twriter.flush();\n\n\t\t}\n\n\t}\n\n\n\n\tstatic InputReader in = new InputReader(System.in);\n\n\tstatic OutputWriter out = new OutputWriter(System.out);\n\n\n\n\tpublic static long[] sort(long[] a2) {\n\n\t\tint n = a2.length;\n\n\t\tArrayList l = new ArrayList<>();\n\n\t\tfor (long i : a2)\n\n\t\t\tl.add(i);\n\n\t\tCollections.sort(l);\n\n\t\tfor (int i = 0; i < l.size(); i++)\n\n\t\t\ta2[i] = l.get(i);\n\n\t\treturn a2;\n\n\t}\n\n\n\n\tpublic static char[] sort(char[] a2) {\n\n\t\tint n = a2.length;\n\n\t\tArrayList l = new ArrayList<>();\n\n\t\tfor (char i : a2)\n\n\t\t\tl.add(i);\n\n\t\tCollections.sort(l);\n\n\t\tfor (int i = 0; i < l.size(); i++)\n\n\t\t\ta2[i] = l.get(i);\n\n\t\treturn a2;\n\n\t}\n\n\n\n\tpublic static long pow(long x, long y) {\n\n\t\tlong res = 1;\n\n\t\twhile (y > 0) {\n\n\t\t\tif (y % 2 != 0) {\n\n\t\t\t\tres = (res * x);\/\/ % modulus;\n\n\t\t\t\ty--;\n\n\n\n\t\t\t}\n\n\t\t\tx = (x * x);\/\/ % modulus;\n\n\t\t\ty = y \/ 2;\n\n\t\t}\n\n\t\treturn res;\n\n\t}\n\n\n\n\/\/GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\tpublic static long gcd(long x, long y) {\n\n\t\tif (x == 0)\n\n\t\t\treturn y;\n\n\t\telse\n\n\t\t\treturn gcd(y % x, x);\n\n\t}\n\n\t\/\/ ******LOWEST COMMON MULTIPLE\n\n\t\/\/ *********************************************\n\n\n\n\tpublic static long lcm(long x, long y) {\n\n\t\treturn (x * (y \/ gcd(x, y)));\n\n\t}\n\n\n\n\/\/INPUT PATTERN********************************************************\n\n\tpublic static int i() {\n\n\t\treturn in.Int();\n\n\t}\n\n\n\n\tpublic static long l() {\n\n\t\tString s = in.String();\n\n\t\treturn Long.parseLong(s);\n\n\t}\n\n\n\n\tpublic static String s() {\n\n\t\treturn in.String();\n\n\t}\n\n\n\n\tpublic static int[] readArrayi(int n) {\n\n\t\tint A[] = new int[n];\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tA[i] = i();\n\n\t\t}\n\n\t\treturn A;\n\n\t}\n\n\n\n\tpublic static long[] readArray(long n) {\n\n\t\tlong A[] = new long[(int) n];\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tA[i] = l();\n\n\t\t}\n\n\t\treturn A;\n\n\t}\n\n\n\n}","language":"java"} -{"contest_id":"1304","problem_id":"E","statement":"E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3\u2264n\u22641053\u2264n\u2264105), the number of vertices of the tree.Next n\u22121n\u22121 lines contain two integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n, u\u2260vu\u2260v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1\u2264q\u22641051\u2264q\u2264105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1\u2264x,y,a,b\u2264n1\u2264x,y,a,b\u2264n, x\u2260yx\u2260y, 1\u2264k\u22641091\u2264k\u2264109) \u2013 the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print \"YES\" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print \"NO\".You can print each letter in any case (upper or lower).ExampleInputCopy5\n1 2\n2 3\n3 4\n4 5\n5\n1 3 1 2 2\n1 4 1 3 2\n1 4 1 3 3\n4 2 3 3 9\n5 2 3 3 9\nOutputCopyYES\nYES\nNO\nYES\nNO\nNoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with \"YES\" answers are: 11-st query: 11 \u2013 33 \u2013 22 22-nd query: 11 \u2013 22 \u2013 33 44-th query: 33 \u2013 44 \u2013 22 \u2013 33 \u2013 44 \u2013 22 \u2013 33 \u2013 44 \u2013 22 \u2013 33 ","tags":["data structures","dfs and similar","shortest paths","trees"],"code":"import java.io.BufferedOutputStream;\n\nimport java.io.Closeable;\n\nimport java.io.DataInputStream;\n\nimport java.io.Flushable;\n\nimport java.io.IOException;\n\nimport java.io.InputStream;\n\nimport java.io.OutputStream;\n\nimport java.util.ArrayList;\n\nimport java.util.InputMismatchException;\n\n\n\n\/**\n\n * Built using CHelper plug-in\n\n * Actual solution is at the top\n\n *\/\n\npublic class Main {\n\n\tstatic class TaskAdapter implements Runnable {\n\n\t\t@Override\n\n\t\tpublic void run() {\n\n\t\t\tInputStream inputStream = System.in;\n\n\t\t\tOutputStream outputStream = System.out;\n\n\t\t\tFastReader in = new FastReader(inputStream);\n\n\t\t\tOutput out = new Output(outputStream);\n\n\t\t\tE1TreesAndQueries solver = new E1TreesAndQueries();\n\n\t\t\tsolver.solve(1, in, out);\n\n\t\t\tout.close();\n\n\t\t}\n\n\t}\n\n\n\n\tpublic static void main(String[] args) throws Exception {\n\n\t\tThread thread = new Thread(null, new TaskAdapter(), \"\", 1<<29);\n\n\t\tthread.start();\n\n\t\tthread.join();\n\n\t}\n\n\tstatic class E1TreesAndQueries {\n\n\t\tArrayList[] graph;\n\n\t\tint time = 0;\n\n\t\tint[] tin;\n\n\t\tint[] tout;\n\n\t\tint[] rank;\n\n\t\tint[][] up;\n\n\n\n\t\tpublic E1TreesAndQueries() {\n\n\t\t}\n\n\n\n\t\tpublic void dfs(int u, int r) {\n\n\t\t\ttin[u] = time++;\n\n\t\t\trank[u] = r;\n\n\t\t\tfor(int v: graph[u]) {\n\n\t\t\t\tgraph[v].remove((Integer) u);\n\n\t\t\t\tup[0][v] = u;\n\n\t\t\t\tdfs(v, r+1);\n\n\t\t\t}\n\n\t\t\ttout[u] = time-1;\n\n\t\t}\n\n\n\n\t\tpublic boolean ancestor(int u, int v) {\n\n\t\t\treturn u==-1||(tin[u]<=tin[v]&&tout[u]>=tout[v]);\n\n\t\t}\n\n\n\n\t\tpublic int lca(int u, int v) {\n\n\t\t\tif(ancestor(u, v)) {\n\n\t\t\t\treturn u;\n\n\t\t\t}\n\n\t\t\tfor(int i = 17; i>=0; i--) {\n\n\t\t\t\tif(!ancestor(up[i][u], v)) {\n\n\t\t\t\t\tu = up[i][u];\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn up[0][u];\n\n\t\t}\n\n\n\n\t\tpublic int dist(int u, int v) {\n\n\t\t\treturn rank[u]+rank[v]-(rank[lca(u, v)]<<1);\n\n\t\t}\n\n\n\n\t\tpublic boolean valid(int dist, int length) {\n\n\t\t\treturn dist<=length&&(dist&1)==(length&1);\n\n\t\t}\n\n\n\n\t\tpublic void solve(int kase, InputReader in, Output pw) {\n\n\t\t\tint n = in.nextInt();\n\n\t\t\tgraph = in.nextUndirectedGraph(n, n-1);\n\n\t\t\tup = new int[18][n];\n\n\t\t\ttin = new int[n];\n\n\t\t\ttout = new int[n];\n\n\t\t\trank = new int[n];\n\n\t\t\tup[0][0] = -1;\n\n\t\t\tdfs(0, 0);\n\n\t\t\tfor(int i = 1; i<18; i++) {\n\n\t\t\t\tfor(int j = 0; j0) {\n\n\t\t\t\tint x = in.nextInt()-1, y = in.nextInt()-1, a = in.nextInt()-1, b = in.nextInt()-1, k = in.nextInt();\n\n\t\t\t\tif(valid(dist(a, b), k)||valid(dist(a, x)+dist(b, y)+1, k)||valid(dist(a, y)+dist(b, x)+1, k)) {\n\n\t\t\t\t\tpw.println(\"YES\");\n\n\t\t\t\t}else {\n\n\t\t\t\t\tpw.println(\"NO\");\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t}\n\n\n\n\tstatic class Output implements Closeable, Flushable {\n\n\t\tpublic StringBuilder sb;\n\n\t\tpublic OutputStream os;\n\n\t\tpublic int BUFFER_SIZE;\n\n\t\tpublic boolean autoFlush;\n\n\t\tpublic String LineSeparator;\n\n\n\n\t\tpublic Output(OutputStream os) {\n\n\t\t\tthis(os, 1<<16);\n\n\t\t}\n\n\n\n\t\tpublic Output(OutputStream os, int bs) {\n\n\t\t\tBUFFER_SIZE = bs;\n\n\t\t\tsb = new StringBuilder(BUFFER_SIZE);\n\n\t\t\tthis.os = new BufferedOutputStream(os, 1<<17);\n\n\t\t\tautoFlush = false;\n\n\t\t\tLineSeparator = System.lineSeparator();\n\n\t\t}\n\n\n\n\t\tpublic void println(String s) {\n\n\t\t\tsb.append(s);\n\n\t\t\tprintln();\n\n\t\t\tif(autoFlush) {\n\n\t\t\t\tflush();\n\n\t\t\t}else if(sb.length()>BUFFER_SIZE >> 1) {\n\n\t\t\t\tflushToBuffer();\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tpublic void println() {\n\n\t\t\tsb.append(LineSeparator);\n\n\t\t}\n\n\n\n\t\tprivate void flushToBuffer() {\n\n\t\t\ttry {\n\n\t\t\t\tos.write(sb.toString().getBytes());\n\n\t\t\t}catch(IOException e) {\n\n\t\t\t\te.printStackTrace();\n\n\t\t\t}\n\n\t\t\tsb = new StringBuilder(BUFFER_SIZE);\n\n\t\t}\n\n\n\n\t\tpublic void flush() {\n\n\t\t\ttry {\n\n\t\t\t\tflushToBuffer();\n\n\t\t\t\tos.flush();\n\n\t\t\t}catch(IOException e) {\n\n\t\t\t\te.printStackTrace();\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tpublic void close() {\n\n\t\t\tflush();\n\n\t\t\ttry {\n\n\t\t\t\tos.close();\n\n\t\t\t}catch(IOException e) {\n\n\t\t\t\te.printStackTrace();\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t}\n\n\n\n\tstatic interface InputReader {\n\n\t\tint nextInt();\n\n\n\n\t\tdefault ArrayList[] nextUndirectedGraph(int n, int m) {\n\n\t\t\tArrayList[] ret = new ArrayList[n];\n\n\t\t\tfor(int i = 0; i();\n\n\t\t\t}\n\n\t\t\tfor(int i = 0; i='0'&&c<='9');\n\n\t\t\tif(neg) {\n\n\t\t\t\treturn -ret;\n\n\t\t\t}\n\n\t\t\treturn ret;\n\n\t\t}\n\n\n\n\t\tprivate boolean isDigit(byte b) {\n\n\t\t\treturn b>='0'&&b<='9';\n\n\t\t}\n\n\n\n\t\tprivate byte skipToDigit() {\n\n\t\t\tbyte ret;\n\n\t\t\twhile(!isDigit(ret = read())&&ret!='-') ;\n\n\t\t\treturn ret;\n\n\t\t}\n\n\n\n\t\tprivate void fillBuffer() {\n\n\t\t\ttry {\n\n\t\t\t\tbytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);\n\n\t\t\t}catch(IOException e) {\n\n\t\t\t\te.printStackTrace();\n\n\t\t\t\tthrow new InputMismatchException();\n\n\t\t\t}\n\n\t\t\tif(bytesRead==-1) {\n\n\t\t\t\tbuffer[0] = -1;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tprivate byte read() {\n\n\t\t\tif(bytesRead==-1) {\n\n\t\t\t\tthrow new InputMismatchException();\n\n\t\t\t}else if(bufferPointer==bytesRead) {\n\n\t\t\t\tfillBuffer();\n\n\t\t\t}\n\n\t\t\treturn buffer[bufferPointer++];\n\n\t\t}\n\n\n\n\t}\n\n}\n\n\n\n\n\n","language":"java"} -{"contest_id":"1324","problem_id":"A","statement":"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\u00d712\u00d71 (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\u00d712\u00d71 (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\u22121ai\u22121. 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\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1\u2264n\u22641001\u2264n\u2264100) \u2014 the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641001\u2264ai\u2264100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer \u2014 \"YES\" (without quotes) if you can clear the whole Tetris field and \"NO\" otherwise.ExampleInputCopy4\n3\n1 1 3\n4\n1 1 2 1\n2\n11 11\n1\n100\nOutputCopyYES\nNO\nYES\nYES\nNoteThe 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.","tags":["implementation","number theory"],"code":"\n\n\n\nimport java.util.*;\n\nimport java.io.*;\n\n\n\npublic class YetAnotherTetrisProblem {\n\n public static void main(String[] args){\n\n FastReader sc = new FastReader();\n\n int t = sc.nextInt();\n\n while (t-- > 0) {\n\n int n = sc.nextInt();\n\n boolean par = true;\n\n boolean res = true;\n\n for (int i = 0; i < n; i++){\n\n int a = sc.nextInt();\n\n if(i == 0 && a % 2 == 0) par = true;\n\n else if(i == 0 && a % 2 == 1) par = false;\n\n if(par && i != 0){\n\n if(a % 2 == 1) res = false;\n\n }\n\n else if(!par && i != 0){\n\n if(a % 2 == 0) res = false;\n\n }\n\n } \n\n System.out.println(res ? \"YES\":\"NO\");\n\n }\n\n }\n\n\n\n static class Maths {\n\n public static int gcd(int a, int b) {\n\n if (b == 0)\n\n return a;\n\n return gcd(b, a % b);\n\n }\n\n\n\n public static int lcm(int a, int b) {\n\n return a * b \/ gcd(a, b);\n\n }\n\n }\n\n\n\n static class NextPermutation {\n\n\n\n \/\/ Function to swap the data\n\n \/\/ present in the left and right indices\n\n public static int[] swap(int data[], int left, int right)\n\n {\n\n\n\n \/\/ Swap the data\n\n int temp = data[left];\n\n data[left] = data[right];\n\n data[right] = temp;\n\n\n\n \/\/ Return the updated array\n\n return data;\n\n }\n\n\n\n \/\/ Function to reverse the sub-array\n\n \/\/ starting from left to the right\n\n \/\/ both inclusive\n\n public static int[] reverse(int data[], int left, int right)\n\n {\n\n\n\n \/\/ Reverse the sub-array\n\n while (left < right) {\n\n int temp = data[left];\n\n data[left++] = data[right];\n\n data[right--] = temp;\n\n }\n\n\n\n \/\/ Return the updated array\n\n return data;\n\n }\n\n\n\n \/\/ Function to find the next permutation\n\n \/\/ of the given integer array\n\n public static boolean findNextPermutation(int data[])\n\n {\n\n\n\n \/\/ If the given dataset is empty\n\n \/\/ or contains only one element\n\n \/\/ next_permutation is not possible\n\n if (data.length <= 1)\n\n return false;\n\n\n\n int last = data.length - 2;\n\n\n\n \/\/ find the longest non-increasing suffix\n\n \/\/ and find the pivot\n\n while (last >= 0) {\n\n if (data[last] < data[last + 1]) {\n\n break;\n\n }\n\n last--;\n\n }\n\n\n\n \/\/ If there is no increasing pair\n\n \/\/ there is no higher order permutation\n\n if (last < 0)\n\n return false;\n\n\n\n int nextGreater = data.length - 1;\n\n\n\n \/\/ Find the rightmost successor to the pivot\n\n for (int i = data.length - 1; i > last; i--) {\n\n if (data[i] > data[last]) {\n\n nextGreater = i;\n\n break;\n\n }\n\n }\n\n\n\n \/\/ Swap the successor and the pivot\n\n data = swap(data, nextGreater, last);\n\n\n\n \/\/ Reverse the suffix\n\n data = reverse(data, last + 1, data.length - 1);\n\n\n\n \/\/ Return true as the next_permutation is done\n\n return true;\n\n }\n\n }\n\n static class UnionFind { \/\/ OOP style\n\n private ArrayList p, rank, setSize;\n\n private int numSets;\n\n\n\n public UnionFind(int N) {\n\n p = new ArrayList(N);\n\n rank = new ArrayList(N);\n\n setSize = new ArrayList(N);\n\n numSets = N;\n\n for (int i = 0; i < N; i++) {\n\n p.add(i);\n\n rank.add(0);\n\n setSize.add(1);\n\n }\n\n }\n\n\n\n public int findSet(int i) {\n\n if (p.get(i) == i)\n\n return i;\n\n else {\n\n int ret = findSet(p.get(i));\n\n p.set(i, ret);\n\n return ret;\n\n }\n\n }\n\n\n\n public Boolean isSameSet(int i, int j) {\n\n return findSet(i) == findSet(j);\n\n }\n\n\n\n public void unionSet(int i, int j) {\n\n if (!isSameSet(i, j)) {\n\n numSets--;\n\n int x = findSet(i), y = findSet(j);\n\n \/\/ rank is used to keep the tree short\n\n if (rank.get(x) > rank.get(y)) {\n\n p.set(y, x);\n\n setSize.set(x, setSize.get(x) + setSize.get(y));\n\n } else {\n\n p.set(x, y);\n\n setSize.set(y, setSize.get(y) + setSize.get(x));\n\n if (rank.get(x) == rank.get(y))\n\n rank.set(y, rank.get(y) + 1);\n\n }\n\n }\n\n }\n\n\n\n public int numDisjointSets() {\n\n return numSets;\n\n }\n\n\n\n public int sizeOfSet(int i) {\n\n return setSize.get(findSet(i));\n\n }\n\n }\n\n\n\n static class Pair {\n\n A first;\n\n B second;\n\n\n\n \/\/ Constructor\n\n public Pair(A first, B second) {\n\n this.first = first;\n\n this.second = second;\n\n }\n\n }\n\n\n\n static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public FastReader() {\n\n br = new BufferedReader(\n\n new InputStreamReader(System.in));\n\n }\n\n\n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n\n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n String nextLine() {\n\n String str = \"\";\n\n try {\n\n if (st.hasMoreTokens()) {\n\n str = st.nextToken(\"\\n\");\n\n } else {\n\n str = br.readLine();\n\n }\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n\n\n boolean hasNext() {\n\n if (st != null && st.hasMoreTokens()) {\n\n return true;\n\n }\n\n String tmp;\n\n try {\n\n br.mark(1000);\n\n tmp = br.readLine();\n\n if (tmp == null) {\n\n return false;\n\n }\n\n br.reset();\n\n } catch (IOException e) {\n\n return false;\n\n }\n\n return true;\n\n }\n\n }\n\n}\n\n","language":"java"} -{"contest_id":"1324","problem_id":"D","statement":"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 (ibi+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\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the number of topics.The second line of the input contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u22641091\u2264bi\u2264109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer \u2014 the number of good pairs of topic.ExamplesInputCopy5\n4 8 2 6 2\n4 5 4 1 3\nOutputCopy7\nInputCopy4\n1 3 2 4\n1 3 2 4\nOutputCopy0\n","tags":["binary search","data structures","sortings","two pointers"],"code":"import java.io.DataInputStream;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class App {\n static class Reader {\n final private int BUFFER_SIZE = 1 << 16;\n private DataInputStream din;\n private byte[] buffer;\n private int bufferPointer, bytesRead;\n \n public Reader()\n {\n din = new DataInputStream(System.in);\n buffer = new byte[BUFFER_SIZE];\n bufferPointer = bytesRead = 0;\n }\n \n public Reader(String file_name) throws IOException\n {\n din = new DataInputStream(\n new FileInputStream(file_name));\n buffer = new byte[BUFFER_SIZE];\n bufferPointer = bytesRead = 0;\n }\n \n public String readLine() throws IOException\n {\n byte[] buf = new byte[64]; \/\/ line length\n int cnt = 0, c;\n while ((c = read()) != -1) {\n if (c == '\\n') {\n if (cnt != 0) {\n break;\n }\n else {\n continue;\n }\n }\n buf[cnt++] = (byte)c;\n }\n return new String(buf, 0, cnt);\n }\n \n public int nextInt() throws IOException\n {\n int ret = 0;\n byte c = read();\n while (c <= ' ') {\n c = read();\n }\n boolean neg = (c == '-');\n if (neg)\n c = read();\n do {\n ret = ret * 10 + c - '0';\n } while ((c = read()) >= '0' && c <= '9');\n \n if (neg)\n return -ret;\n return ret;\n }\n \n public long nextLong() throws IOException\n {\n long ret = 0;\n byte c = read();\n while (c <= ' ')\n c = read();\n boolean neg = (c == '-');\n if (neg)\n c = read();\n do {\n ret = ret * 10 + c - '0';\n } while ((c = read()) >= '0' && c <= '9');\n if (neg)\n return -ret;\n return ret;\n }\n \n public double nextDouble() throws IOException\n {\n double ret = 0, div = 1;\n byte c = read();\n while (c <= ' ')\n c = read();\n boolean neg = (c == '-');\n if (neg)\n c = read();\n \n do {\n ret = ret * 10 + c - '0';\n } while ((c = read()) >= '0' && c <= '9');\n \n if (c == '.') {\n while ((c = read()) >= '0' && c <= '9') {\n ret += (c - '0') \/ (div *= 10);\n }\n }\n \n if (neg)\n return -ret;\n return ret;\n }\n \n private void fillBuffer() throws IOException\n {\n bytesRead = din.read(buffer, bufferPointer = 0,\n BUFFER_SIZE);\n if (bytesRead == -1)\n buffer[0] = -1;\n }\n \n private byte read() throws IOException\n {\n if (bufferPointer == bytesRead)\n fillBuffer();\n return buffer[bufferPointer++];\n }\n \n public void close() throws IOException\n {\n if (din == null)\n return;\n din.close();\n }\n }\n\n public static void main(String[] args) throws Exception {\n Reader in = new Reader();\n int opt = in.nextInt();\n int[] arr1 = new int[opt];\n Integer[] arr2 = new Integer[opt];\n\n for(int i = 0; i < opt; i++) {\n arr1[i] = in.nextInt();\n }\n\n for(int i = 0; i < opt; i++) {\n arr2[i] = arr1[i] - in.nextInt();\n } \n Arrays.sort(arr2); \n\n long cnt = 0;\n int right = opt - 1;\n int left = 0;\n while(arr2[right] > 0 && left < right) {\n if(arr2[right] + arr2[left] > 0) {\n cnt += right - left;\n right--;\n } else {\n left++;\n }\n }\n\n System.out.println(cnt);\n in.close();\n }\n}","language":"java"} -{"contest_id":"1321","problem_id":"A","statement":"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 \u2014 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 \u2014 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\u2264n\u22641001\u2264n\u2264100) \u2014 the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0\u2264ri\u226410\u2264ri\u22641). 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\u2264bi\u226410\u2264bi\u22641). 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 \u22121\u22121.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\n1 1 1 0 0\n0 1 1 1 1\nOutputCopy3\nInputCopy3\n0 0 0\n0 0 0\nOutputCopy-1\nInputCopy4\n1 1 1 1\n1 1 1 1\nOutputCopy-1\nInputCopy9\n1 0 0 0 0 0 0 0 1\n0 1 1 0 1 1 1 1 0\nOutputCopy4\nNoteIn 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\" \u2014 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.","tags":["greedy"],"code":"import java.util.*;\n\nimport java.lang.*;\n\nimport java.io.*;\n\n\n\npublic class Main\n\n{\n\n static long mod = (int)1e9+7;\n\n static PrintWriter out=new PrintWriter(new BufferedOutputStream(System.out));\n\n public static void main (String[] args) throws java.lang.Exception\n\n {\n\n FastReader sc =new FastReader();\n\n\n\n \/\/ int t=sc.nextInt();\n\n \n\n int t=1;\n\n \n\n O : while(t-->0)\n\n {\n\n int n = sc.nextInt();\n\n int a[]=sc.readArray(n);\n\n int b[]=sc.readArray(n);\n\n int ca = 0, cb = 0;\n\n for (int i = 0; i < n; i++) \n\n {\n\n if (a[i] == b[i]) \n\n continue;\n\n if (a[i] == 1) \n\n ca++;\n\n else \n\n cb++;\n\n }\n\n if (ca == 0) \n\n {\n\n System.out.println(\"-1\");\n\n }\n\n else\n\n {\n\n int ans = cb \/ ca + 1;\n\n System.out.println(ans);\n\n }\n\n }\n\n out.flush();\n\n }\n\n \n\nstatic void printN()\n\n{\n\n System.out.println(\"NO\");\n\n}\n\nstatic void printY()\n\n{\n\n System.out.println(\"YES\");\n\n}\n\n\n\nstatic int findfrequencies(int a[],int n)\n\n{\n\n int count=0;\n\n for(int i=0;i>>8&0xff)+1]++;\n\nc2[(v>>>16&0xff)+1]++;\n\nc3[(v>>>24^0x80)+1]++;\n\n}\n\nfor(int i = 0;i < 0xff;i++) {\n\nc0[i+1] += c0[i];\n\nc1[i+1] += c1[i];\n\nc2[i+1] += c2[i];\n\nc3[i+1] += c3[i];\n\n}\n\nint[] t = new int[n];\n\nfor(int v : a)t[c0[v&0xff]++] = v;\n\nfor(int v : t)a[c1[v>>>8&0xff]++] = v;\n\nfor(int v : a)t[c2[v>>>16&0xff]++] = v;\n\nfor(int v : t)a[c3[v>>>24^0x80]++] = v;\n\nreturn a;\n\n}\n\n\n\nstatic int[] EvenOddArragement(int a[])\n\n{\n\n ArrayList list=new ArrayList<>();\n\n for(int i=0;i sortByValue(HashMap hm)\n\n {\n\n \/\/ Create a list from elements of HashMap\n\n List > list =\n\n new LinkedList >(hm.entrySet());\n\n \n\n \/\/ Sort the list\n\n Collections.sort(list, new Comparator >() {\n\n public int compare(Map.Entry o1,\n\n Map.Entry o2)\n\n {\n\n return (o1.getValue()).compareTo(o2.getValue());\n\n }\n\n });\n\n \n\n \/\/ put data from sorted list to hashmap\n\n HashMap temp = new LinkedHashMap();\n\n for (Map.Entry aa : list) {\n\n temp.put(aa.getKey(), aa.getValue());\n\n }\n\n return temp;\n\n }\n\n static int DigitSum(int n)\n\n {\n\n int r=0,sum=0;\n\n while(n>=0)\n\n {\n\n r=n%10;\n\n sum=sum+r;\n\n n=n\/10;\n\n }\n\n return sum;\n\n }\n\n static boolean checkPerfectSquare(int number) \n\n { \n\n double sqrt=Math.sqrt(number); \n\n return ((sqrt - Math.floor(sqrt)) == 0); \n\n } \n\n static boolean isPowerOfTwo(int n)\n\n {\n\n if(n==0)\n\n return false;\n\n \n\n return (int)(Math.ceil((Math.log(n) \/ Math.log(2)))) == (int)(Math.floor(((Math.log(n) \/ Math.log(2)))));\n\n }\n\n static boolean isPrime2(int n) \n\n {\n\n if (n <= 1) \n\n {\n\n return false;\n\n }\n\n if (n == 2) \n\n {\n\n return true;\n\n }\n\n if (n % 2 == 0) \n\n {\n\n return false;\n\n }\n\n for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) \n\n {\n\n if (n % i == 0)\n\n {\n\n return false;\n\n }\n\n }\n\n return true;\n\n }\n\n static String minLexRotation(String str)\n\n {\n\n int n = str.length();\n\n String arr[] = new String[n];\n\n String concat = str + str;\n\n for(int i=0;i {\n\n\t\tint i, j;\n\n\t\tpublic P(int i, int j) {\n\n\t\t\tthis.i=i;\n\n\t\t\tthis.j=j;\n\n\t\t}\n\n\t\tpublic int compareTo(P o) {\n\n\t\t\treturn Integer.compare(i, o.i);\n\n\t\t}\n\n\t}\n\n\tstatic int binary_search(int a[],int value)\n\n\t{\n\n\t int start=0;\n\n\t int end=a.length-1;\n\n\t int mid=start+(end-start)\/2;\n\n\t while(start<=end)\n\n\t {\n\n\t if(a[mid]==value)\n\n\t {\n\n\t return mid;\n\n\t }\n\n\t if(a[mid]>value)\n\n\t {\n\n\t end=mid-1;\n\n\t }\n\n\t else\n\n\t {\n\n\t start=mid+1;\n\n\t }\n\n\t mid=start+(end-start)\/2;\n\n\t }\n\n\t return -1;\n\n\t}\n\n}","language":"java"} -{"contest_id":"1307","problem_id":"B","statement":"B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,\u2026,ana1,a2,\u2026,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi\u2212xj)2+(yi\u2212yj)2\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u221a(xi\u2212xj)2+(yi\u2212yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) \u2192\u2192 (2,\u22125\u2013\u221a)(2,\u22125) \u2192\u2192 (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1\u2264t\u226410001\u2264t\u22641000) \u00a0\u2014 the number of test cases. Next 2t2t lines contain test cases \u2014 two lines per test case.The first line of each test case contains two integers nn and xx (1\u2264n\u22641051\u2264n\u2264105, 1\u2264x\u22641091\u2264x\u2264109) \u00a0\u2014 the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109) \u00a0\u2014 Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer\u00a0\u2014 the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2\n3\n1\n2\nNoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5\u2013\u221a)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) \u2192\u2192 (4,0)(4,0) \u2192\u2192 (8,0)(8,0) \u2192\u2192 (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) \u2192\u2192 (5,102\u2013\u221a)(5,102) \u2192\u2192 (10,0)(10,0).","tags":["geometry","greedy","math"],"code":"import java.io.*;\n\nimport java.util.*;\n\nimport java.text.*;\n\nimport java.math.*;\n\nimport java.util.regex.*;\n\n\n\npublic class JaiShreeRam{\n\n\tstatic Scanner in=new Scanner();\n\n\tstatic long mod = 1000000007;\n\n\tstatic ArrayList> adj;\n\n\tstatic ArrayList ans;\n\n\tpublic static void main(String[] args) throws Exception{\n\n\t\tint z=in.readInt();\n\n\t\twhile(z-->0) {\n\n\t\t\tsolve();\n\n\t\t}\n\n\t}\t\n\n\tstatic void solve() {\n\n\t\tint n=in.readInt();\n\n\t\tint x=in.readInt();\n\n\t\tint a[]=nia(n);\n\n\t\tSet st=new HashSet<>();\n\n\t\tint max=a[0];\n\n\t\tfor(int i=0;i int to long conversion needed\n\n -> while loop mein break case shi ho\n\n -> extra kuch output na ho rha free fund mein\n\n\n\n\n\n*\/\n\n\n\n\/\/update this bad boi too\n\npublic class Main{\n\n\n\n static int mod = (int) (Math.pow(10, 9)+7);\n\n\tstatic final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };\n\n\tstatic final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };\n\n\tstatic final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };\n\n\n\n\tstatic final double eps = 1e-10;\n\n\tstatic Set primeNumbers = new HashSet<>();\n\n\n\n public static void main(String[] args) throws IOException{\n\n MyScanner sc = new MyScanner();\n\n \/\/changes in this line of code\n\n out = new PrintWriter(new BufferedOutputStream(System.out));\n\n \/\/ out = new PrintWriter(new BufferedWriter(new FileWriter(\"output.out\"))); \n\n \n\n \/\/Write Code Below (let's try to code it down bois) (if bigger then remove them first)\n\n \/\/keep on making new stringbuilder again and again for sure (n is very less)\n\n int n = sc.nextInt();\n\n char[] inp = sc.nextLine().toCharArray();\n\n\n\n \/\/since these strings are \n\n int[] pos = new int[n];\n\n\n\n for(int i = 26; i >= 1; i--){\n\n char curr = (char)('a' + i);\n\n char prev = (char)('a' + (i-1));\n\n\n\n while(true){\n\n boolean terminate = true;\n\n for(int j = 0; j < n; j++){\n\n if(pos[j] == -1) continue;\n\n \n\n if(inp[j] == curr){\n\n \/\/we found some bad boi\n\n \/\/we find recent left and recent right\n\n int l = j-1;\n\n int r = j+1;\n\n\n\n boolean bingo = false;\n\n while(l >= 0){\n\n if(pos[l] != -1) break;\n\n l--;\n\n }\n\n if( l >= 0 && inp[l] == prev) bingo = true;\n\n\n\n while(r < n){\n\n if(pos[r] != -1) break;\n\n r++;\n\n }\n\n if(r < n && inp[r] == prev) bingo = true;\n\n\n\n if(bingo){\n\n terminate = false;\n\n pos[j] = -1;\n\n }\n\n }\n\n\n\n }\n\n\n\n if(terminate) break;\n\n }\n\n }\n\n\n\n int count = 0;\n\n for(int i : pos) if(i == -1) count++;\n\n out.println(count);\n\n \n\n out.close();\n\n }\n\n\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n\n\n \/\/Updation Required\n\n \/\/Fenwick Tree (customisable)\n\n \/\/Segment Tree (customisable)\n\n\n\n \/\/-----CURRENTLY PRESENT-------\/\/\n\n \/\/Graph\n\n \/\/DSU\n\n \/\/powerMODe\n\n \/\/power\n\n \/\/Segment Tree (work on this one) \n\n \/\/Prime Sieve\n\n \/\/Count Divisors\n\n \/\/Next Permutation \n\n \/\/Get NCR \n\n \/\/isVowel\n\n \/\/Sort (int)\n\n \/\/Sort (long)\n\n \/\/Binomial Coefficient\n\n \/\/Pair\n\n \/\/Triplet\n\n \/\/lcm (int & long)\n\n \/\/gcd (int & long)\n\n \/\/gcd (for binomial coefficient)\n\n \/\/swap (int & char)\n\n \/\/reverse\n\n\n\n \/\/SOME LATEST UPDATIONS!!!\n\n \/\/mod_mul\n\n \/\/mod_div\n\n\n\n \/\/Fast input and output \n\n\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n\n\n \/\/finding combinations in O(1) (basically the most basic logic you can think of)\n\n \/\/not that complicated as i though it of\n\n\n\n\n\n \/\/GRAPH (basic structure)\n\n public static class Graph{\n\n public int V;\n\n public ArrayList> edges;\n\n\n\n \/\/2 -> [0,1,2] (current)\n\n Graph(int V){\n\n this.V = V;\n\n edges = new ArrayList<>(V+1);\n\n for(int i= 0; i <= V; i++){\n\n edges.add(new ArrayList<>());\n\n }\n\n }\n\n\n\n public void addEdge(int from , int to){\n\n edges.get(from).add(to);\n\n }\n\n }\n\n\n\n \/\/DSU (path and rank optimised)\n\n public static class DisjointUnionSets {\n\n int[] rank, parent;\n\n int n;\n\n \n\n public DisjointUnionSets(int n)\n\n {\n\n rank = new int[n];\n\n parent = new int[n];\n\n Arrays.fill(rank, 1);\n\n Arrays.fill(parent,-1);\n\n this.n = n;\n\n }\n\n \n\n public int find(int curr){\n\n if(parent[curr] == -1)\n\n return curr;\n\n \n\n \/\/path compression optimisation\n\n return parent[curr] = find(parent[curr]);\n\n }\n\n \n\n public void union(int a, int b){\n\n int s1 = find(a);\n\n int s2 = find(b);\n\n \n\n if(s1 != s2){\n\n if(rank[s1] < rank[s2]){\n\n parent[s1] = s2;\n\n rank[s2] += rank[s1];\n\n }else{\n\n parent[s2] = s1;\n\n rank[s1] += rank[s2];\n\n }\n\n }\n\n }\n\n }\n\n\n\n \/\/with mod\n\n public static long powerMOD(long x, long y)\n\n {\n\n long res = 1L; \n\n while (y > 0)\n\n {\n\n \/\/ If y is odd, multiply x with result\n\n if ((y & 1) != 0){\n\n x %= mod;\n\n res %= mod;\n\n res = (res * x)%mod;\n\n }\n\n \/\/ y must be even now\n\n y = y >> 1; \/\/ y = y\/2\n\n x%= mod;\n\n x = (x * x)%mod; \/\/ Change x to x^2\n\n }\n\n return res%mod;\n\n }\n\n\n\n \/\/without mod\n\n public static long power(long x, long y)\n\n {\n\n long res = 1L; \n\n while (y > 0)\n\n {\n\n \/\/ If y is odd, multiply x with result\n\n if ((y & 1) != 0){\n\n res = (res * x);\n\n }\n\n \/\/ y must be even now\n\n y = y >> 1; \/\/ y = y\/\n\n x = (x * x);\n\n }\n\n return res;\n\n }\n\n\n\n public static class segmentTree{\n\n\n\n public long[] arr;\n\n public long[] tree;\n\n public long[] lazy;\n\n\n\n segmentTree(long[] array){\n\n int n = array.length;\n\n arr = new long[n];\n\n for(int i= 0; i < n; i++) arr[i] = array[i];\n\n tree = new long[4*n + 1];\n\n lazy = new long[4*n + 1];\n\n }\n\n\n\n public void build(int[]arr, int s, int e, int[] tree, int index){\n\n\n\n if(s == e){\n\n tree[index] = arr[s];\n\n return;\n\n }\n\n \n\n \/\/otherwise divide in two parts and fill both sides simply\n\n int mid = (s+e)\/2;\n\n build(arr, s, mid, tree, 2*index);\n\n build(arr, mid+1, e, tree, 2*index+1);\n\n \n\n \/\/who will build the current position dude\n\n tree[index] = Math.min(tree[2*index], tree[2*index+1]);\n\n }\n\n \n\n public int query(int sr, int er, int sc, int ec, int index, int[] tree){\n\n \n\n if(lazy[index] != 0){\n\n tree[index] += lazy[index];\n\n \n\n if(sc != ec){\n\n lazy[2*index+1] += lazy[index];\n\n lazy[2*index] += lazy[index];\n\n }\n\n \n\n lazy[index] = 0;\n\n }\n\n \n\n \/\/no overlap\n\n if(sr > ec || sc > er) return Integer.MAX_VALUE;\n\n \n\n \/\/found the index baby\n\n if(sr <= sc && ec <= er) return tree[index];\n\n \n\n \/\/finding the index on both sides hehehehhe\n\n int mid = (sc + ec)\/2;\n\n int left = query(sr, er, sc, mid, 2*index, tree);\n\n int right = query(sr, er, mid+1, ec, 2*index + 1, tree);\n\n \n\n return Integer.min(left, right);\n\n }\n\n \n\n \/\/now we will do point update implementation\n\n \/\/it should be simple then we expected for sure\n\n public void update(int index, int indexr, int increment, int[] tree, int s, int e){\n\n \n\n if(lazy[index] != 0){\n\n tree[index] += lazy[index];\n\n \n\n if(s != e){\n\n lazy[2*index+1] = lazy[index];\n\n lazy[2*index] = lazy[index];\n\n }\n\n \n\n lazy[index] = 0;\n\n }\n\n \n\n \/\/no overlap\n\n if(indexr < s || indexr > e) return;\n\n \n\n \/\/found the required index\n\n if(s == e){\n\n tree[index] += increment;\n\n return;\n\n } \n\n \n\n \/\/search for the index on both sides\n\n int mid = (s+e)\/2;\n\n update(2*index, indexr, increment, tree, s, mid);\n\n update(2*index+1, indexr, increment, tree, mid+1, e);\n\n \n\n \/\/now update the current range simply\n\n tree[index] = Math.min(tree[2*index+1], tree[2*index]);\n\n }\n\n \n\n public void rangeUpdate(int[] tree , int index, int s, int e, int sr, int er, int increment){\n\n \n\n \/\/if not at all in the same range\n\n if(e < sr || er < s) return;\n\n \n\n \/\/complete then also move forward\n\n if(s == e){\n\n tree[index] += increment;\n\n return;\n\n }\n\n \n\n \/\/otherwise move in both subparts\n\n int mid = (s+e)\/2;\n\n rangeUpdate(tree, 2*index, s, mid, sr, er, increment);\n\n rangeUpdate(tree, 2*index + 1, mid+1, e, sr, er, increment);\n\n \n\n \/\/update current range too na\n\n \/\/i always forget this step for some reasons hehehe, idiot\n\n tree[index] = Math.min(tree[2*index], tree[2*index + 1]);\n\n }\n\n \n\n public void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment){\n\n \n\n \/\/update lazy values\n\n \/\/resolve lazy value before going down\n\n if(lazy[index] != 0){\n\n tree[index] += lazy[index];\n\n \n\n if(s != e){\n\n lazy[2*index+1] += lazy[index];\n\n lazy[2*index] += lazy[index];\n\n }\n\n \n\n lazy[index] = 0;\n\n }\n\n \n\n \/\/no overlap case\n\n if(sr > e || s > er) return;\n\n \n\n \/\/complete overlap\n\n if(sr <= s && er >= e){\n\n tree[index] += increment;\n\n \n\n if(s != e){\n\n lazy[2*index+1] += increment;\n\n lazy[2*index] += increment;\n\n }\n\n return;\n\n }\n\n \n\n \/\/otherwise go on both left and right side and do your shit\n\n int mid = (s + e)\/2;\n\n rangeUpdateLazy(tree, 2*index, s, mid, sr, er, increment);\n\n rangeUpdateLazy(tree, 2*index + 1, mid+1, e, sr, er, increment);\n\n \n\n tree[index] = Math.min(tree[2*index+1], tree[2*index]);\n\n return;\n\n \n\n }\n\n \n\n }\n\n\n\n \/\/prime sieve\n\n public static void primeSieve(int n){\n\n BitSet bitset = new BitSet(n+1);\n\n for(long i = 0; i < n ; i++){\n\n if (i == 0 || i == 1) {\n\n bitset.set((int) i);\n\n continue;\n\n }\n\n if(bitset.get((int) i)) continue;\n\n primeNumbers.add((int)i);\n\n for(long j = i; j <= n ; j+= i)\n\n bitset.set((int)j);\n\n }\n\n }\n\n\n\n \/\/number of divisors\n\n \/\/ public static int countDivisors(long number){\n\n \/\/ if(number == 1) return 1;\n\n \/\/ List primeFactors = new ArrayList<>();\n\n \/\/ int index = 0;\n\n \/\/ long curr = primeNumbers.get(index);\n\n \/\/ while(curr * curr <= number){\n\n \/\/ while(number % curr == 0){\n\n \/\/ number = number\/curr;\n\n \/\/ primeFactors.add((int) curr);\n\n \/\/ } \n\n \/\/ index++;\n\n \/\/ curr = primeNumbers.get(index);\n\n \/\/ }\n\n\n\n \/\/ if(number != 1) primeFactors.add((int) number);\n\n \/\/ int current = primeFactors.get(0);\n\n \/\/ int totalDivisors = 1;\n\n \/\/ int currentCount = 2;\n\n \/\/ for (int i = 1; i < primeFactors.size(); i++) {\n\n \/\/ if (primeFactors.get(i) == current) {\n\n \/\/ currentCount++;\n\n \/\/ } else {\n\n \/\/ totalDivisors *= currentCount;\n\n \/\/ currentCount = 2;\n\n \/\/ current = primeFactors.get(i);\n\n \/\/ }\n\n \/\/ }\n\n \/\/ totalDivisors *= currentCount;\n\n \/\/ return totalDivisors;\n\n \/\/ }\n\n\n\n \/\/now adding next permutation function to java hehe\n\n public static boolean next_permutation(int[] p) {\n\n for (int a = p.length - 2; a >= 0; --a)\n\n if (p[a] < p[a + 1])\n\n for (int b = p.length - 1;; --b)\n\n if (p[b] > p[a]) {\n\n int t = p[a];\n\n p[a] = p[b];\n\n p[b] = t;\n\n for (++a, b = p.length - 1; a < b; ++a, --b) {\n\n t = p[a];\n\n p[a] = p[b];\n\n p[b] = t;\n\n }\n\n return true;\n\n }\n\n return false;\n\n }\n\n\n\n \/\/is vowel function \n\n public static boolean isVowel(char c)\n\n {\n\n return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U');\n\n } \n\n\n\n \/\/to sort the array with better method\n\n\tpublic static void sort(int[] a) {\n\n\t\tArrayList l=new ArrayList<>();\n\n\t\tfor (int i:a) l.add(i);\n\n\t\tCollections.sort(l);\n\n\t\tfor (int i=0; i l=new ArrayList<>();\n\n\t\tfor (long i:a) l.add(i);\n\n\t\tCollections.sort(l);\n\n\t\tfor (int i=0; i 0; j--)\n\n C[j] = C[j] + C[j - 1];\n\n }\n\n return C[k];\n\n }\n\n\n\n \/\/Pair with int int \n\n public static class Pair{\n\n public int a;\n\n public int b;\n\n\n\n Pair(int a , int b){\n\n this.a = a;\n\n this.b = b;\n\n }\n\n\n\n @Override\n\n public String toString(){\n\n return a + \" -> \" + b; \n\n }\n\n }\n\n\n\n \/\/Triplet with int int int\n\n public static class Triplet{\n\n\n\n public int a;\n\n public int b;\n\n public int c;\n\n\n\n Triplet(int a , int b, int c){\n\n this.a = a;\n\n this.b = b;\n\n this.c = c;\n\n }\n\n\n\n @Override\n\n public String toString(){\n\n return a + \" -> \" + b; \n\n }\n\n }\n\n\n\n \/\/Shortcut function\n\n public static long lcm(long a , long b){\n\n return a * (b\/gcd(a,b));\n\n }\n\n\n\n \/\/let's make one for calculating lcm basically\n\n public static int lcm(int a , int b){\n\n return (a * b)\/gcd(a,b);\n\n }\n\n\n\n \/\/int version for gcd\n\n public static int gcd(int a, int b){\n\n if(b == 0)\n\n return a;\n\n \n\n return gcd(b , a%b);\n\n }\n\n\n\n \/\/long version for gcd\n\n public static long gcd(long a, long b){\n\n if(b == 0)\n\n return a;\n\n\n\n return gcd(b , a%b);\n\n }\n\n\n\n \/\/for ncr calculator(ignore this code)\n\n public static long __gcd(long n1, long n2)\n\n {\n\n long gcd = 1;\n\n for (int i = 1; i <= n1 && i <= n2; ++i) {\n\n \/\/ Checks if i is factor of both integers\n\n if (n1 % i == 0 && n2 % i == 0) {\n\n gcd = i;\n\n }\n\n }\n\n return gcd;\n\n }\n\n\n\n \/\/swapping two elements in an array\n\n public static void swap(int[] arr, int left , int right){\n\n int temp = arr[left];\n\n arr[left] = arr[right];\n\n arr[right] = temp;\n\n }\n\n\n\n \/\/for char array\n\n public static void swap(char[] arr, int left , int right){\n\n char temp = arr[left];\n\n arr[left] = arr[right];\n\n arr[right] = temp;\n\n }\n\n\n\n \/\/reversing an array\n\n public static void reverse(int[] arr){\n\n int left = 0;\n\n int right = arr.length-1;\n\n\n\n while(left <= right){\n\n swap(arr, left,right);\n\n left++;\n\n right--;\n\n }\n\n }\n\n \n\n public static long expo(long a, long b, long mod) {\n\n long res = 1; \n\n while (b > 0) {\n\n if ((b & 1) == 1L) res = (res * a) % mod; \/\/think about this one for a second\n\n a = (a * a) % mod;\n\n b = b >> 1;\n\n } \n\n return res;\n\n }\n\n\n\n \/\/SOME EXTRA DOPE FUNCTIONS \n\n public static long mminvprime(long a, long b) {\n\n return expo(a, b - 2, b);\n\n }\n\n\n\n public static long mod_add(long a, long b, long m) {\n\n a = a % m;\n\n b = b % m;\n\n return (((a + b) % m) + m) % m;\n\n }\n\n\n\n public static long mod_sub(long a, long b, long m) {\n\n a = a % m; \n\n b = b % m; \n\n return (((a - b) % m) + m) % m;\n\n }\n\n \n\n public static long mod_mul(long a, long b, long m) {\n\n a = a % m;\n\n b = b % m;\n\n return (((a * b) % m) + m) % m;\n\n }\n\n\n\n public static long mod_div(long a, long b, long m) {\n\n a = a % m;\n\n b = b % m;\n\n return (mod_mul(a, mminvprime(b, m), m) + m) % m;\n\n }\n\n\n\n \/\/O(n) every single time remember that\n\n public static long nCr(long N, long K , long mod){\n\n long upper = 1L;\n\n long lower = 1L;\n\n long lowerr = 1L;\n\n\n\n for(long i = 1; i <= N; i++){\n\n upper = mod_mul(upper, i, mod);\n\n }\n\n\n\n for(long i = 1; i <= K; i++){\n\n lower = mod_mul(lower, i, mod);\n\n }\n\n\n\n for(long i = 1; i <= (N - K); i++){\n\n lowerr = mod_mul(lowerr, i, mod);\n\n }\n\n\n\n \/\/ out.println(upper + \" \" + lower + \" \" + lowerr);\n\n long answer = mod_mul(lower, lowerr, mod);\n\n answer = mod_div(upper, answer, mod);\n\n\n\n return answer;\n\n }\n\n\n\n \/\/ ll *fact = new ll[2 * n + 1];\n\n\t\/\/ ll *ifact = new ll[2 * n + 1];\n\n\t\/\/ fact[0] = 1;\n\n\t\/\/ ifact[0] = 1;\n\n\t\/\/ for (ll i = 1; i <= 2 * n; i++)\n\n\t\/\/ {\n\n\t\/\/ \tfact[i] = mod_mul(fact[i - 1], i, MOD1);\n\n\t\/\/ \tifact[i] = mminvprime(fact[i], MOD1);\n\n\t\/\/ }\n\n \/\/ifact is basically inverse factorial in here!!!!!(imp)\n\n public static long combination(long n, long r, long m, long[] fact, long[] ifact) {\n\n long val1 = fact[(int)n];\n\n long val2 = ifact[(int)(n - r)];\n\n long val3 = ifact[(int)r];\n\n return (((val1 * val2) % m) * val3) % m;\n\n }\n\n\n\n \n\n \n\n \/\/-----------PrintWriter for faster output---------------------------------\n\n public static PrintWriter out;\n\n \n\n \/\/-----------MyScanner class for faster input----------\n\n public static class MyScanner {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public MyScanner() {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n\n\n \/\/ public MyScanner() throws FileNotFoundException {\n\n \/\/ br = new BufferedReader(new FileReader(\"input.in\"));\n\n \/\/ }\n\n \n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n \n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n \n\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n \n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n \n\n String nextLine(){\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n\n\n }\n\n \/\/--------------------------------------------------------\n\n}","language":"java"} -{"contest_id":"1311","problem_id":"B","statement":"B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,\u2026,pmp1,p2,\u2026,pm, where 1\u2264pi 0) {\n\n\t\t\tArrays.fill(c,false);\n\n\t\t\tboolean flag = true;\n\n\t\t\tint n = sc.nextInt();\n\n\t\t\tint m = sc.nextInt();\n\n\t\t\tfor(int i = 1; i <= n; i++) {\n\n\t\t\t\ta[i] = sc.nextInt();\n\n\t\t\t}\n\n\t\t\tfor(int j = 1; j <= m; j++) {\n\n\t\t\t\tp[j] = sc.nextInt();\n\n\t\t\t\tc[p[j]] = true;\n\n\t\t\t}\n\n\t\t\tint k = 0; \n\n\t\t\tfor(int i1 = 1; i1 <= n; i1++) {\n\n\t\t\t\tfor(int j = 1; j <= n - i1; j++) {\n\n\t\t\t\t\tif(a[j] > a[j + 1]) {\n\n\t\t\t\t\t\tif(c[j]) {\n\n\t\t\t\t\t\t\tk = a[j];\n\n\t\t\t\t\t\t\ta[j] = a[j + 1];\n\n\t\t\t\t\t\t\ta[j + 1] = k;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse {\n\n\t\t\t\t\t\t\tflag = false;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif(!flag) {\n\n\t\t\t\tSystem.out.println(\"NO\");\n\n\t\t\t}else {\n\n\t\t\t\tSystem.out.println(\"YES\");\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n }\n\n\n\n","language":"java"} -{"contest_id":"1305","problem_id":"B","statement":"B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1\u2264|s|\u226410001\u2264|s|\u22641000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk \u00a0\u2014 the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm \u00a0\u2014 the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1\u2264a1> ans = new ArrayList<>();\n\n\t\twhile (true) {\n\n\t\t\tchar a[] = s.toCharArray();\n\n\t\t\tList o = new ArrayList<>();\n\n\t\t\tList c = new ArrayList<>();\n\n\t\t\tfor (int i = 0; i < a.length; i++) {\n\n\t\t\t\tif (a[i] == '(')\n\n\t\t\t\t\to.add(i + 1);\n\n\t\t\t\telse\n\n\t\t\t\t\tc.add(i + 1);\n\n\t\t\t}\n\n\t\t\tint pref[] = new int[a.length];\n\n\t\t\tint suff[] = new int[a.length];\n\n\t\t\tif (a[0] == '(')\n\n\t\t\t\tpref[0]++;\n\n\t\t\tif (a[a.length - 1] == ')')\n\n\t\t\t\tsuff[a.length - 1]++;\n\n\t\t\tfor (int i = 1; i < a.length; i++) {\n\n\t\t\t\tpref[i] += pref[i - 1] + (a[i] == '(' ? 1 : 0);\n\n\t\t\t}\n\n\t\t\tfor (int i = a.length - 2; i >= 0; i--) {\n\n\t\t\t\tsuff[i] += suff[i + 1] + (a[i] == ')' ? 1 : 0);\n\n\t\t\t}\n\n\/\/\t\t\tSystem.out.println(Arrays.toString(pref));\n\n\/\/\t\t\tSystem.out.println(Arrays.toString(suff));\n\n\/\/\t\t\tSystem.out.println(\"xxxxxxxxxxxxx\");\n\n\t\t\tint max = 0;\n\n\t\t\tint ind = -1;\n\n\t\t\tfor (int i = 0; i < a.length - 1; i++) {\n\n\t\t\t\tif (a[i] == '(') {\n\n\t\t\t\t\tif (max < Math.min(pref[i], suff[i + 1])) {\n\n\t\t\t\t\t\tmax = Math.min(pref[i], suff[i + 1]);\n\n\t\t\t\t\t\tind = i + 1;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif (max == 0) {\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\tint temp = max;\n\n\t\t\tboolean t[] = new boolean[a.length + 1];\n\n\t\t\tStringBuilder sb = new StringBuilder();\n\n\t\t\tfor (int i : o) {\n\n\t\t\t\tif (i <= ind && temp > 0) {\n\n\t\t\t\t\tt[i] = true;\n\n\t\t\t\t\ttemp--;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\ttemp = max;\n\n\t\t\tfor (int i = c.size() - 1; i >= 0; i--) {\n\n\t\t\t\tif (c.get(i) > ind && temp > 0) {\n\n\t\t\t\t\tt[c.get(i)] = true;\n\n\t\t\t\t\ttemp--;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < a.length; i++) {\n\n\t\t\t\tif (!t[i + 1])\n\n\t\t\t\t\tsb.append(a[i]);\n\n\t\t\t}\n\n\t\t\tList al = new ArrayList<>();\n\n\t\t\tfor (int i = 1; i <= a.length; i++) {\n\n\t\t\t\tif (t[i])\n\n\t\t\t\t\tal.add(i);\n\n\t\t\t}\n\n\t\t\tans.add(al);\n\n\t\t\ts = sb.toString();\n\n\t\t\tif (s.length() == 0)\n\n\t\t\t\tbreak;\n\n\t\t}\n\n\t\tSystem.out.println(ans.size());\n\n\t\tfor (List x : ans) {\n\n\t\t\tSystem.out.println(x.size());\n\n\t\t\tfor (int i : x) {\n\n\t\t\t\tSystem.out.print(i + \" \");\n\n\t\t\t}\n\n\t\t\tSystem.out.println();\n\n\t\t}\n\n\t}\n\n\n\n\t\/\/ SOLUTION ENDS HERE\n\n\t\/\/ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n\tstatic long binPow(long a, long b, long mod) {\n\n\t\tlong ans = 1;\n\n\t\twhile (b != 0) {\n\n\t\t\tif ((b & 1) == 1)\n\n\t\t\t\tans = (ans * a) % mod;\n\n\t\t\ta = (a * a) % mod;\n\n\t\t\tb >>= 1;\n\n\t\t}\n\n\t\treturn ans;\n\n\t}\n\n\n\n\tstatic class DSU {\n\n\t\tint rank[];\n\n\t\tint parent[];\n\n\n\n\t\tDSU(int n) {\n\n\t\t\trank = new int[n + 1];\n\n\t\t\tparent = new int[n + 1];\n\n\t\t\tfor (int i = 1; i <= n; i++) {\n\n\t\t\t\tparent[i] = i;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tint findParent(int node) {\n\n\t\t\tif (parent[node] == node)\n\n\t\t\t\treturn node;\n\n\t\t\treturn parent[node] = findParent(parent[node]);\n\n\t\t}\n\n\n\n\t\tboolean union(int x, int y) {\n\n\t\t\tint px = findParent(x);\n\n\t\t\tint py = findParent(y);\n\n\t\t\tif (px == py)\n\n\t\t\t\treturn false;\n\n\t\t\tif (rank[px] < rank[py]) {\n\n\t\t\t\tparent[px] = py;\n\n\t\t\t} else if (rank[px] > rank[py]) {\n\n\t\t\t\tparent[py] = px;\n\n\t\t\t} else {\n\n\t\t\t\tparent[px] = py;\n\n\t\t\t\trank[py]++;\n\n\t\t\t}\n\n\t\t\treturn true;\n\n\t\t}\n\n\t}\n\n\n\n\tstatic void sort(int[] a) {\n\n\t\tArrayList l = new ArrayList<>();\n\n\t\tfor (int i : a)\n\n\t\t\tl.add(i);\n\n\t\tCollections.sort(l);\n\n\t\tfor (int i = 0; i < a.length; i++)\n\n\t\t\ta[i] = l.get(i);\n\n\t}\n\n\n\n\tstatic boolean[] seiveOfEratosthenes(int n) {\n\n\t\tboolean[] isPrime = new boolean[n + 1];\n\n\t\tArrays.fill(isPrime, true);\n\n\t\tfor (int i = 2; i * i <= n; i++) {\n\n\t\t\tfor (int j = i * i; j <= n; j += i) {\n\n\t\t\t\tisPrime[j] = false;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn isPrime;\n\n\t}\n\n\n\n\tstatic int gcd(int a, int b) {\n\n\t\tif (b == 0)\n\n\t\t\treturn a;\n\n\t\treturn gcd(b, a % b);\n\n\t}\n\n\n\n\tstatic boolean isPrime(long n) {\n\n\t\tif (n < 2)\n\n\t\t\treturn false;\n\n\t\tfor (int i = 2; i * i <= n; i++) {\n\n\t\t\tif (n % i == 0)\n\n\t\t\t\treturn false;\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\n\n\tstatic class FastScanner {\n\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n\t\tStringTokenizer st = new StringTokenizer(\"\");\n\n\n\n\t\tString next() {\n\n\t\t\twhile (!st.hasMoreTokens())\n\n\t\t\t\ttry {\n\n\t\t\t\t\tst = new StringTokenizer(br.readLine());\n\n\t\t\t\t} catch (IOException e) {\n\n\t\t\t\t\te.printStackTrace();\n\n\t\t\t\t}\n\n\t\t\treturn st.nextToken();\n\n\t\t}\n\n\n\n\t\tint nextInt() {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\n\n\t\tint[] readIntArray(int n) {\n\n\t\t\tint[] a = new int[n];\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t\ta[i] = nextInt();\n\n\t\t\treturn a;\n\n\t\t}\n\n\n\n\t\tlong[] readLongArray(int n) {\n\n\t\t\tlong[] a = new long[n];\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t\ta[i] = nextLong();\n\n\t\t\treturn a;\n\n\t\t}\n\n\n\n\t\tlong nextLong() {\n\n\t\t\treturn Long.parseLong(next());\n\n\t\t}\n\n\t}\n\n\n\n\tprivate static final FastScanner sc = new FastScanner();\n\n\tprivate static PrintWriter out = new PrintWriter(System.out);\n\n}\n\n","language":"java"} -{"contest_id":"1288","problem_id":"D","statement":"D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1\u2264i,j\u2264n1\u2264i,j\u2264n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k\u2208[1,m]k\u2208[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1\u2264n\u22643\u22c51051\u2264n\u22643\u22c5105, 1\u2264m\u226481\u2264m\u22648) \u2014 the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0\u2264ax,y\u22641090\u2264ax,y\u2264109).OutputPrint two integers ii and jj (1\u2264i,j\u2264n1\u2264i,j\u2264n, it is possible that i=ji=j) \u2014 the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5\n5 0 3 1 2\n1 8 9 1 3\n1 2 3 4 5\n9 1 0 3 7\n2 3 0 6 3\n6 4 1 7 0\nOutputCopy1 5\n","tags":["binary search","bitmasks","dp"],"code":"import java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.TreeSet;\nimport java.util.Objects;\nimport java.util.StringTokenizer;\nimport java.io.Writer;\nimport java.io.OutputStreamWriter;\nimport java.io.BufferedReader;\nimport java.io.InputStream;\n\n\/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n *\/\npublic class Main {\n public static void main(String[] args) {\n InputStream inputStream = System.in;\n OutputStream outputStream = System.out;\n InputReader in = new InputReader(inputStream);\n OutputWriter out = new OutputWriter(outputStream);\n DMinimaxProblem solver = new DMinimaxProblem();\n solver.solve(1, in, out);\n out.close();\n }\n\n static class DMinimaxProblem {\n int n;\n int m;\n int[][] arr;\n int id1;\n int id2;\n int p;\n\n public void solve(int testNumber, InputReader in, OutputWriter out) {\n n = in.nextInt();\n m = in.nextInt();\n arr = in.nextIntMatrix(n, m);\n p = (int) Math.pow(2, m) - 1;\n int lo = 0;\n int hi = (int) 1e9;\n id1 = -1;\n id2 = -1;\n int ans = 0;\n while (lo <= hi) {\n int mid = (lo + hi) \/ 2;\n if (check(mid)) {\n ans = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n out.println(id1, id2);\n }\n\n boolean check(int mid) {\n TreeSet set = new TreeSet<>();\n for (int i = 0; i < n; i++) {\n int mask = 0;\n for (int j = 0; j < m; j++) {\n if (arr[i][j] >= mid) mask |= (1 << j);\n }\n set.add(new Pair(mask, i));\n }\n for (Pair a : set) {\n for (Pair b : set) {\n if ((a.a | b.a) == p) {\n id1 = a.b + 1;\n id2 = b.b + 1;\n return true;\n }\n }\n }\n return false;\n }\n\n class Pair implements Comparable {\n int a;\n int b;\n\n Pair(int a, int b) {\n this.a = a;\n this.b = b;\n }\n\n public int hashCode() {\n return Objects.hash(a, b);\n }\n\n public boolean equals(Object obj) {\n Pair that = (Pair) obj;\n return a == that.a && b == that.b;\n }\n\n public String toString() {\n return \"[\" + a + \", \" + b + \"]\";\n }\n\n public int compareTo(Pair v) {\n return a - v.a;\n }\n\n }\n\n }\n\n static class OutputWriter {\n private final PrintWriter writer;\n\n public OutputWriter(OutputStream outputStream) {\n writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n }\n\n public OutputWriter(Writer writer) {\n this.writer = new PrintWriter(writer);\n }\n\n public void print(Object... objects) {\n for (int i = 0; i < objects.length; i++) {\n if (i != 0) {\n writer.print(' ');\n }\n writer.print(objects[i]);\n }\n }\n\n public void println(Object... objects) {\n print(objects);\n writer.println();\n }\n\n public void close() {\n writer.close();\n }\n\n }\n\n static class InputReader {\n BufferedReader reader;\n StringTokenizer tokenizer;\n\n public InputReader(InputStream stream) {\n reader = new BufferedReader(new InputStreamReader(stream), 32768);\n tokenizer = null;\n }\n\n public String next() {\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n try {\n tokenizer = new StringTokenizer(reader.readLine());\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n return tokenizer.nextToken();\n }\n\n public int nextInt() {\n return Integer.parseInt(next());\n }\n\n public int[][] nextIntMatrix(int rows, int cols) {\n int[][] matrix = new int[rows][cols];\n for (int i = 0; i < rows; i++)\n for (int j = 0; j < cols; j++)\n matrix[i][j] = nextInt();\n return matrix;\n }\n\n }\n}\n\n","language":"java"} -{"contest_id":"1285","problem_id":"A","statement":"A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x\u22121x:=x\u22121; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands \"LRLR\", then here are some possible outcomes (underlined commands are sent successfully): \"LRLR\" \u2014 Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; \"LRLR\" \u2014 Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; \"LRLR\" \u2014 Zoma moves to the left, then to the left again and ends up in position \u22122\u22122. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1\u2264n\u2264105)(1\u2264n\u2264105) \u2014 the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer \u2014 the number of different positions Zoma may end up at.ExampleInputCopy4\nLRLR\nOutputCopy5\nNoteIn the example; Zoma may end up anywhere between \u22122\u22122 and 22.","tags":["math"],"code":"import java.util.*;\n\n\n\npublic class java {\n\n public static void main(String[] args) {\n\n Scanner scan = new Scanner(System.in);\n\n int x = scan.nextInt();\n\n String g = scan.next();\n\n int c = 0, q = 0;\n\n for (int i = 0; i < x; i++) {\n\n if(g.charAt(i)=='R'){\n\n c++;\n\n }\n\n else{\n\n q++;\n\n }\n\n }\n\n System.out.println(c+q+1);\n\n }\n\n}","language":"java"} -{"contest_id":"1288","problem_id":"B","statement":"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\u2264a\u2264A1\u2264a\u2264A, 1\u2264b\u2264B1\u2264b\u2264B, and the equation a\u22c5b+a+b=conc(a,b)a\u22c5b+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\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.Each test case contains two integers AA and BB (1\u2264A,B\u2264109)(1\u2264A,B\u2264109).OutputPrint one integer \u2014 the number of pairs (a,b)(a,b) such that 1\u2264a\u2264A1\u2264a\u2264A, 1\u2264b\u2264B1\u2264b\u2264B, and the equation a\u22c5b+a+b=conc(a,b)a\u22c5b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1\n0\n1337\nNoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1\u22c59=191+9+1\u22c59=19).","tags":["math"],"code":"import java.io.OutputStreamWriter;\n\n\n\n\n\nimport java.util.Scanner;\n\nimport java.io.BufferedWriter;\n\nimport java.io.BufferedOutputStream;\n\nimport java.io.BufferedReader;\n\nimport java.io.IOException;\n\npublic class math {\n\n\n\n\tpublic static void main(String[] args) throws IOException {\n\n\t\t\n\n\tScanner in = new Scanner(System.in);\n\nBufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));\n\n\t\t\n\n\t\tint tt = in.nextInt();\n\n\t\t\n\n\t\tfor(int w = 0; w 0)\n\n {\n\n \/\/ bitwise left shift\n\n \/\/ 'rev' by 1\n\n rev <<= 1;\n\n \n\n \/\/ if current bit is '1'\n\n if ((int)(n & 1) == 1)\n\n rev ^= 1;\n\n \n\n \/\/ bitwise right shift\n\n \/\/'n' by 1\n\n n >>= 1;\n\n }\n\n \/\/ required number\n\n return rev;\n\n }\n\n \n\n public static ArrayList getSequence(String str)\n\n\n\n {\n\n \n\n\n\n \/\/ If 1\n\n\/\/ \tstring is empty\n\n\n\n if (str.length() == 0) {\n\n \n\n\n\n \/\/ Return an empty arraylist\n\n\n\n ArrayList empty = new ArrayList<>();\n\n\n\n empty.add(\"\");\n\n\n\n return empty;\n\n\n\n }\n\n \n\n\n\n \/\/ Take first character of str\n\n\n\n char ch = str.charAt(0);\n\n \n\n\n\n \/\/ Take sub-string starting from the\n\n\n\n \/\/ second character\n\n\n\n String subStr = str.substring(1);\n\n \n\n\n\n \/\/ Recursive call for all the sub-sequences \n\n\n\n \/\/ starting from the second character\n\n\n\n ArrayList subSequences = \n\n\n\n getSequence(subStr);\n\n \n\n\n\n \/\/ Add first character from str in the beginning\n\n\n\n \/\/ of every character from the sub-sequences\n\n\n\n \/\/ and then store it into the resultant arraylist\n\n\n\n ArrayList res = new ArrayList<>();\n\n\n\n for (String val : subSequences) {\n\n\n\n res.add(val);\n\n\n\n res.add(ch + val);\n\n\n\n }\n\n return res;\n\n\n\n }\n\n static int fact(int n)\n\n {\n\n \tint fact=1;\n\n \twhile(n>=1)\n\n \t{\n\n \t\tfact=fact*n;\n\n \t\tn--;\n\n \t}\n\n \treturn fact;\n\n }\n\n static long __gcd(long a, long b)\n\n {\n\n if (a == 0 || b == 0)\n\n return 0;\n\n \n\n if (a == b)\n\n return a;\n\n \n\n if (a > b)\n\n return __gcd(a-b, b);\n\n \n\n return __gcd(a, b-a);\n\n }\n\n \n\n static boolean coprime(long a, long b) {\n\n \n\n if ( __gcd(a, b) == 1)\n\n return true;\n\n else\n\n return false; \n\n }\n\n static int xor(int n,int a,int b)\n\n {\n\n\t\tif(n>0)\n\n\t\t{\n\n\t\t\txor(n-1,b,a^b);\n\n\t\t\treturn a^b;\n\n\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\treturn a^b;\n\n\t\t}\n\n }\n\n static ArrayList> printSubArrays(int[] arr, int start, int end,ArrayList> x)\n\n {\n\n if (end == arr.length)\n\n {\n\n return x;\n\n }\n\n else if (start > end)\n\n {\n\n printSubArrays(arr, 0, end + 1,x);\n\n }\n\n else \n\n {\n\n ArrayList x1=new ArrayList();\n\n for (int i = start; i < end; i++)\n\n {\n\n x1.add(arr[i]);\n\n }\n\n x1.add(arr[end]);\n\n x.add(x1);\n\n printSubArrays(arr, start + 1, end,x);\n\n }\n\n return x;\n\n }\n\n \n\n public static ArrayList> printSubsequences(int[] arr, int index,\n\n ArrayList path)\n\n{\n\n\n\n\/\/ Print the subsequence when reach\n\n\/\/ the leaf of recursion tree\n\n\t\tArrayList> x=new ArrayList>(); \n\nif (index == arr.length)\n\n{\n\n\n\n\/\/ Condition to avoid printing\n\n\/\/ empty subsequence\n\nif (path.size() > 0)\n\nx.add(path);\n\nreturn x;\n\n}\n\n\n\nelse\n\n{\n\n\n\n\/\/ Subsequence without including\n\n\/\/ the element at current index\n\nprintSubsequences(arr, index + 1, path);\n\n\n\npath.add(arr[index]);\n\nx.add(path);\n\n\/\/ Subsequence including the element\n\n\/\/ at current index\n\nprintSubsequences(arr, index + 1, path);\n\nx.add(path);\n\n\n\n\/\/ Backtrack to remove the recently\n\n\/\/ inserted element\n\npath.remove(path.size() - 1);\n\nx.add(path);\n\n}\n\nreturn x;\n\n}\n\n\tpublic static void main(String[] args) \n\n\t{\n\n\t\tMyScanner sc = new MyScanner();\n\n out = new PrintWriter(new BufferedOutputStream(System.out));\n\n\t\tint t=sc.nextInt();\n\n\t\twhile(t-->0)\n\n\t\t{\n\n\/\/\t\t\tint n=sc.nextInt();\n\n\/\/\t\t\tint k=sc.nextInt();\n\n\/\/\t\t\tint i=1,s=0;\n\n\/\/\t\t\twhile(s 1) seg.update(1, where[val] - 1, c);\n\n if (where[val] < n) seg.update(where[val], n - 1, -c);\n\n ans = Math.min(ans, seg.minQuery(1, n - 1));\n\n }\n\n out.println(ans);\n\n out.close();\n\n }\n\n\n\n static class RangeTree {\n\n private long[] max;\n\n private long[] min;\n\n private long[] lazy;\n\n private long[] sum;\n\n private int size;\n\n public RangeTree(int size) {\n\n this.size = size;\n\n max = new long[4*size];\n\n min = new long[4*size];\n\n sum = new long[4*size];\n\n lazy = new long[4*size];\n\n }\n\n public void update(int l, int r, long inc) {\n\n update(1, 0, size-1, l, r, inc);\n\n }\n\n private void pushDown(int index, int l, int r) {\n\n min[index] += lazy[index];\n\n max[index] += lazy[index];\n\n sum[index] += lazy[index] * (r-l+1);\n\n if(l != r) {\n\n lazy[2*index] += lazy[index];\n\n lazy[2*index+1] += lazy[index];\n\n }\n\n lazy[index] = 0;\n\n }\n\n private void pullUp(int index, int l, int r) {\n\n int m = (l+r)\/2;\n\n min[index] = Math.min(evaluateMin(2*index, l, m), evaluateMin(2*index+1, m+1, r));\n\n max[index] = Math.max(evaluateMax(2*index, l, m), evaluateMax(2*index+1, m+1, r));\n\n sum[index] = evaluateSum(2*index, l, m) + evaluateSum(2*index+1, m+1, r);\n\n }\n\n private long evaluateSum(int index, int l, int r) {\n\n return sum[index] + (r-l+1)*lazy[index];\n\n }\n\n private long evaluateMin(int index, int l, int r) {\n\n return min[index] + lazy[index];\n\n }\n\n private long evaluateMax(int index, int l, int r) {\n\n return max[index] + lazy[index];\n\n }\n\n private void update(int index, int l, int r, int left, int right, long inc) {\n\n if(r < left || l > right) return;\n\n if(l >= left && r <= right) {\n\n lazy[index] += inc;\n\n return;\n\n }\n\n pushDown(index, l, r);\n\n int m = (l+r)\/2;\n\n update(2*index, l, m, left, right, inc);\n\n update(2*index+1, m+1, r, left, right, inc);\n\n pullUp(index, l, r);\n\n }\n\n public long minQuery(int l, int r) {\n\n return minQuery(1, 0, size-1, l, r);\n\n }\n\n private long minQuery(int index, int l, int r, int left, int right) {\n\n if(r < left || l > right) return Long.MAX_VALUE;\n\n if(l >= left && r <= right) {\n\n return evaluateMin(index, l, r);\n\n }\n\n pushDown(index, l, r);\n\n int m = (l+r)\/2;\n\n long ret = Long.MAX_VALUE;\n\n ret = Math.min(ret, minQuery(2*index, l, m, left, right));\n\n ret = Math.min(ret, minQuery(2*index+1, m+1, r, left, right));\n\n pullUp(index, l, r);\n\n return ret;\n\n }\n\n public long maxQuery(int l, int r) {\n\n return maxQuery(1, 0, size-1, l, r);\n\n }\n\n private long maxQuery(int index, int l, int r, int left, int right) {\n\n if(r < left || l > right) return Long.MIN_VALUE;\n\n if(l >= left && r <= right) {\n\n return evaluateMax(index, l, r);\n\n }\n\n pushDown(index, l, r);\n\n int m = (l+r)\/2;\n\n long ret = Long.MIN_VALUE;\n\n ret = Math.max(ret, maxQuery(2*index, l, m, left, right));\n\n ret = Math.max(ret, maxQuery(2*index+1, m+1, r, left, right));\n\n pullUp(index, l, r);\n\n return ret;\n\n }\n\n public long sumQuery(int l, int r) {\n\n return sumQuery(1, 0, size-1, l, r);\n\n }\n\n private long sumQuery(int index, int l, int r, int left, int right) {\n\n if(r < left || l > right) return 0;\n\n if(l >= left && r <= right) {\n\n return evaluateSum(index, l, r);\n\n }\n\n pushDown(index, l, r);\n\n int m = (l+r)\/2;\n\n long ret = 0;\n\n ret += sumQuery(2*index, l, m, left, right);\n\n ret += sumQuery(2*index+1, m+1, r, left, right);\n\n pullUp(index, l, r);\n\n return ret;\n\n }\n\n }\n\n\n\n\n\n \/\/-----------MyScanner class for faster input----------\n\n public static class MyScanner {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public MyScanner() {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n\n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n\n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n String nextLine() {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n\n\n\n\n }\n\n\n\n}","language":"java"} -{"contest_id":"1292","problem_id":"A","statement":"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#\u03a6\u03c9\u03a6 has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2\u00d7n2\u00d7n 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\u2264n\u22641052\u2264n\u2264105, 1\u2264q\u22641051\u2264q\u2264105).The ii-th of qq following lines contains two integers riri, cici (1\u2264ri\u226421\u2264ri\u22642, 1\u2264ci\u2264n1\u2264ci\u2264n), 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\n2 3\n1 4\n2 4\n2 3\n1 4\nOutputCopyYes\nNo\nNo\nNo\nYes\nNoteWe'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)\u2192(1,2)\u2192(1,3)\u2192(1,4)\u2192(1,5)\u2192(2,5)(1,1)\u2192(1,2)\u2192(1,3)\u2192(1,4)\u2192(1,5)\u2192(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. ","tags":["data structures","dsu","implementation"],"code":"import java.util.*;\n\nimport java.io.*;\n\n\n\npublic class Main {\n\n\tstatic StringBuilder sb;\n\n\tstatic dsu dsu;\n\n\tstatic long fact[];\n\n\tstatic int mod = (int) (1e9 + 7);\n\n \n\n\tstatic void solve() \n\n\t{\n\n\t int n=i();\n\n\t int q=i();\n\n\t boolean[][]arr=new boolean[2][n];\n\n\t HashSet full=new HashSet<>();\n\n\t HashSet dg=new HashSet<>();\n\n\t for(int i=0;i0&&arr[1][y-1]){\n\n dg.remove(\"\"+1+\"#\"+(y-1));\n\n }\n\n \n\n \n\n \n\n \n\n }\n\n \n\n \n\n else{\n\n if(y>0&&arr[0][y-1]){\n\n dg.remove(\"\"+0+\"#\"+(y-1));\n\n } \n\n \n\n \n\n \n\n \n\n }\n\n\t \n\n\t \n\n\t }\n\n\t else{\n\n if(x==0){\n\n if(y>0&&arr[1][y-1]){\n\n dg.add(\"\"+1+\"#\"+(y-1));\n\n }\n\n if(y0&&arr[0][y-1]){\n\n dg.add(\"\"+0+\"#\"+(y-1));\n\n } \n\n if(y0||dg.size()>0){\n\n\t sb.append(\"No\\n\");\n\n\t } \n\n\t else{\n\n\t sb.append(\"Yes\\n\");\n\n\t }\n\n\t \n\n\t }\n\n\t}\n\n\tpublic static void main(String[] args) {\n\n\t\tsb = new StringBuilder();\n\n\t\tint test = 1;\n\n\t\t\t fact=new long[(int)1e6+10];\n\n\t\t\t fact[0]=fact[1]=1; \n\n\t\t\t for(int i=2;i 0) {\n\n\t\t\tsolve();\n\n\t\t}\n\n\t\tSystem.out.println(sb);\n\n\n\n\t}\n\n\n\n\t\n\n\n\n\t \n\n\/\/**************NCR%P******************\t \n\n\tstatic long ncr(int n, int r) {\n\n\t\tif (r > n)\n\n\t\t\treturn (long) 0;\n\n\n\n\t\tlong res = fact[n] % mod;\n\n\t\t\/\/ System.out.println(res);\n\n\t\tres = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;\n\n\t\tres = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;\n\n\t\t\/\/ System.out.println(res);\n\n\t\treturn res;\n\n\n\n\t}\n\n\n\n\tstatic long p(long x, long y)\/\/ POWER FXN \/\/\n\n\t{\n\n\t\tif (y == 0)\n\n\t\t\treturn 1;\n\n\n\n\t\tlong res = 1;\n\n\t\twhile (y > 0) {\n\n\t\t\tif (y % 2 == 1) {\n\n\t\t\t\tres = (res * x);\n\n\t\t\t\ty--;\n\n\t\t\t}\n\n\n\n\t\t\tx = (x * x) ;\n\n\t\t\ty = y \/ 2;\n\n\n\n\t\t}\n\n\t\treturn res;\n\n\t}\n\n\n\n\/\/**************END******************\n\n\n\n\t\/\/ *************Disjoint set\n\n\t\/\/ union*********\/\/\n\n\tstatic class dsu {\n\n\t\tint parent[];\n\n\n\n\t\tdsu(int n) {\n\n\t\t\tparent = new int[n];\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t\tparent[i] = i;\n\n\t\t}\n\n\n\n\t\tint find(int a) {\n\n\t\t\tif (parent[a] ==a)\n\n\t\t\t\treturn a;\n\n\t\t\telse {\n\n\t\t\t\tint x = find(parent[a]);\n\n\t\t\t\tparent[a] = x;\n\n\t\t\t\treturn x;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tvoid merge(int a, int b) {\n\n\t\t\ta = find(a);\n\n\t\t\tb = find(b);\n\n\t\t\tif (a == b)\n\n\t\t\t\treturn;\n\n\t\t\tparent[b] = a;\n\n\t\t}\n\n\t}\n\n\n\n\/\/**************PRIME FACTORIZE **********************************\/\/\n\n\tstatic TreeMap prime(long n) {\n\n\t\tTreeMap h = new TreeMap<>();\n\n\t\tlong num = n;\n\n\t\tfor (int i = 2; i <= Math.sqrt(num); i++) {\n\n\t\t\tif (n % i == 0) {\n\n\t\t\t\tint nt = 0;\n\n\t\t\t\twhile (n % i == 0) {\n\n\t\t\t\t\tn = n \/ i;\n\n\t\t\t\t\tnt++;\n\n\t\t\t\t}\n\n\t\t\t\th.put(i, nt);\n\n\t\t\t}\n\n\t\t}\n\n\t\tif (n != 1)\n\n\t\t\th.put((int) n, 1);\n\n\t\treturn h;\n\n\n\n\t}\n\n\n\n\/\/****CLASS PAIR ************************************************\n\n\tstatic class Pair implements Comparable {\n\n\t\tint x;\n\n\t\tlong y;\n\n\n\n\t\tPair(int x, long y) {\n\n\t\t\tthis.x = x;\n\n\t\t\tthis.y = y;\n\n\t\t}\n\n\n\n\t\tpublic int compareTo(Pair o) {\n\n\t\t\treturn (int) (this.y - o.y);\n\n\n\n\t\t}\n\n\n\n\t}\n\n\/\/****CLASS PAIR **************************************************\n\n\n\n\tstatic class InputReader {\n\n\t\tprivate InputStream stream;\n\n\t\tprivate byte[] buf = new byte[1024];\n\n\t\tprivate int curChar;\n\n\t\tprivate int numChars;\n\n\t\tprivate SpaceCharFilter filter;\n\n\n\n\t\tpublic InputReader(InputStream stream) {\n\n\t\t\tthis.stream = stream;\n\n\t\t}\n\n\n\n\t\tpublic int read() {\n\n\t\t\tif (numChars == -1)\n\n\t\t\t\tthrow new InputMismatchException();\n\n\t\t\tif (curChar >= numChars) {\n\n\t\t\t\tcurChar = 0;\n\n\t\t\t\ttry {\n\n\t\t\t\t\tnumChars = stream.read(buf);\n\n\t\t\t\t} catch (IOException e) {\n\n\t\t\t\t\tthrow new InputMismatchException();\n\n\t\t\t\t}\n\n\t\t\t\tif (numChars <= 0)\n\n\t\t\t\t\treturn -1;\n\n\t\t\t}\n\n\t\t\treturn buf[curChar++];\n\n\t\t}\n\n\n\n\t\tpublic int Int() {\n\n\t\t\tint c = read();\n\n\t\t\twhile (isSpaceChar(c))\n\n\t\t\t\tc = read();\n\n\t\t\tint sgn = 1;\n\n\t\t\tif (c == '-') {\n\n\t\t\t\tsgn = -1;\n\n\t\t\t\tc = read();\n\n\t\t\t}\n\n\t\t\tint res = 0;\n\n\t\t\tdo {\n\n\t\t\t\tif (c < '0' || c > '9')\n\n\t\t\t\t\tthrow new InputMismatchException();\n\n\t\t\t\tres *= 10;\n\n\t\t\t\tres += c - '0';\n\n\t\t\t\tc = read();\n\n\t\t\t} while (!isSpaceChar(c));\n\n\t\t\treturn res * sgn;\n\n\t\t}\n\n\n\n\t\tpublic String String() {\n\n\t\t\tint c = read();\n\n\t\t\twhile (isSpaceChar(c))\n\n\t\t\t\tc = read();\n\n\t\t\tStringBuilder res = new StringBuilder();\n\n\t\t\tdo {\n\n\t\t\t\tres.appendCodePoint(c);\n\n\t\t\t\tc = read();\n\n\t\t\t} while (!isSpaceChar(c));\n\n\t\t\treturn res.toString();\n\n\t\t}\n\n\n\n\t\tpublic boolean isSpaceChar(int c) {\n\n\t\t\tif (filter != null)\n\n\t\t\t\treturn filter.isSpaceChar(c);\n\n\t\t\treturn c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n\n\t\t}\n\n\n\n\t\tpublic String next() {\n\n\t\t\treturn String();\n\n\t\t}\n\n\n\n\t\tpublic interface SpaceCharFilter {\n\n\t\t\tpublic boolean isSpaceChar(int ch);\n\n\t\t}\n\n\t}\n\n\n\n\tstatic class OutputWriter {\n\n\t\tprivate final PrintWriter writer;\n\n\n\n\t\tpublic OutputWriter(OutputStream outputStream) {\n\n\t\t\twriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n\n\t\t}\n\n\n\n\t\tpublic OutputWriter(Writer writer) {\n\n\t\t\tthis.writer = new PrintWriter(writer);\n\n\t\t}\n\n\n\n\t\tpublic void print(Object... objects) {\n\n\t\t\tfor (int i = 0; i < objects.length; i++) {\n\n\t\t\t\tif (i != 0)\n\n\t\t\t\t\twriter.print(' ');\n\n\t\t\t\twriter.print(objects[i]);\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tpublic void printLine(Object... objects) {\n\n\t\t\tprint(objects);\n\n\t\t\twriter.println();\n\n\t\t}\n\n\n\n\t\tpublic void close() {\n\n\t\t\twriter.close();\n\n\t\t}\n\n\n\n\t\tpublic void flush() {\n\n\t\t\twriter.flush();\n\n\t\t}\n\n\t}\n\n\n\n\tstatic InputReader in = new InputReader(System.in);\n\n\tstatic OutputWriter out = new OutputWriter(System.out);\n\n\n\n\tpublic static long[] sort(long[] a2) {\n\n\t\tint n = a2.length;\n\n\t\tArrayList l = new ArrayList<>();\n\n\t\tfor (long i : a2)\n\n\t\t\tl.add(i);\n\n\t\tCollections.sort(l);\n\n\t\tfor (int i = 0; i < l.size(); i++)\n\n\t\t\ta2[i] = l.get(i);\n\n\t\treturn a2;\n\n\t}\n\n\n\n\tpublic static char[] sort(char[] a2) {\n\n\t\tint n = a2.length;\n\n\t\tArrayList l = new ArrayList<>();\n\n\t\tfor (char i : a2)\n\n\t\t\tl.add(i);\n\n\t\tCollections.sort(l);\n\n\t\tfor (int i = 0; i < l.size(); i++)\n\n\t\t\ta2[i] = l.get(i);\n\n\t\treturn a2;\n\n\t}\n\n\n\n\tpublic static long pow(long x, long y) {\n\n\t\tlong res = 1;\n\n\t\twhile (y > 0) {\n\n\t\t\tif (y % 2 != 0) {\n\n\t\t\t\tres = (res * x);\/\/ % modulus;\n\n\t\t\t\ty--;\n\n\n\n\t\t\t}\n\n\t\t\tx = (x * x);\/\/ % modulus;\n\n\t\t\ty = y \/ 2;\n\n\t\t}\n\n\t\treturn res;\n\n\t}\n\n\n\n\/\/GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\tpublic static long gcd(long x, long y) {\n\n\t\tif (x == 0)\n\n\t\t\treturn y;\n\n\t\telse\n\n\t\t\treturn gcd(y % x, x);\n\n\t}\n\n\t\/\/ ******LOWEST COMMON MULTIPLE\n\n\t\/\/ *********************************************\n\n\n\n\tpublic static long lcm(long x, long y) {\n\n\t\treturn (x * (y \/ gcd(x, y)));\n\n\t}\n\n\n\n\/\/INPUT PATTERN********************************************************\n\n\tpublic static int i() {\n\n\t\treturn in.Int();\n\n\t}\n\n\t\n\n\tpublic static long l() {\n\n\t\tString s = in.String();\n\n\t\treturn Long.parseLong(s);\n\n\t}\n\n\n\n\tpublic static String s() {\n\n\t\treturn in.String();\n\n\t}\n\n\n\n\tpublic static int[] readArrayi(int n) {\n\n\t\tint A[] = new int[n];\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tA[i] = i();\n\n\t\t}\n\n\t\treturn A;\n\n\t}\n\n\n\n\tpublic static long[] readArray(long n) {\n\n\t\tlong A[] = new long[(int) n];\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tA[i] = l();\n\n\t\t}\n\n\t\treturn A;\n\n\t}\n\n\n\n}","language":"java"} -{"contest_id":"1307","problem_id":"D","statement":"D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105, n\u22121\u2264m\u22642\u22c5105n\u22121\u2264m\u22642\u22c5105, 2\u2264k\u2264n2\u2264k\u2264n) \u00a0\u2014 the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,\u2026,aka1,a2,\u2026,ak (1\u2264ai\u2264n1\u2264ai\u2264n) \u00a0\u2014 the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n, xi\u2260yixi\u2260yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3\n1 3 5\n1 2\n2 3\n3 4\n3 5\n2 4\nOutputCopy3\nInputCopy5 4 2\n2 4\n1 2\n2 3\n3 4\n4 5\nOutputCopy3\nNoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33. ","tags":["binary search","data structures","dfs and similar","graphs","greedy","shortest paths","sortings"],"code":"import java.util.*;\n\nimport java.io.*;\n\npublic class Main\n\n{\n\n static class FastReader \n\n { \n\n BufferedReader br; \n\n StringTokenizer st; \n\n \n\n public FastReader() \n\n { \n\n br = new BufferedReader(new\n\n InputStreamReader(System.in)); \n\n } \n\n \n\n String next() \n\n { \n\n while (st == null || !st.hasMoreElements()) \n\n { \n\n try\n\n { \n\n st = new StringTokenizer(br.readLine()); \n\n } \n\n catch (IOException e) \n\n { \n\n e.printStackTrace(); \n\n } \n\n } \n\n return st.nextToken(); \n\n } \n\n \n\n int nextInt() \n\n { \n\n return Integer.parseInt(next()); \n\n } \n\n \n\n long nextLong() \n\n { \n\n return Long.parseLong(next()); \n\n } \n\n \n\n double nextDouble() \n\n { \n\n return Double.parseDouble(next()); \n\n } \n\n \n\n String nextLine() \n\n { \n\n String str = \"\"; \n\n try\n\n { \n\n str = br.readLine(); \n\n } \n\n catch (IOException e) \n\n { \n\n e.printStackTrace(); \n\n } \n\n return str; \n\n } \n\n }\n\n static class Pair implements Comparable\n\n {\n\n int f,s;\n\n Pair(int f,int s)\n\n {\n\n this.f=f;\n\n this.s=s;\n\n }\n\n \n\n public int compareTo(Pair p)\n\n {\n\n return this.s-p.s;\n\n }\n\n }\n\n static ArrayList edge[];\n\n public static void main(String args[])throws Exception\n\n {\n\n FastReader fs=new FastReader();\n\n PrintWriter pw=new PrintWriter(System.out);\n\n int n=fs.nextInt();\n\n int m=fs.nextInt();\n\n int k=fs.nextInt();\n\n int arr[]=new int[k];\n\n boolean s[]=new boolean[n+1];\n\n for(int i=0;i();\n\n for(int i=0;i queue=new LinkedList<>();\n\n boolean pres=false;\n\n boolean vis[]=new boolean[n+1];\n\n vis[1]=true;\n\n queue.add(1);\n\n ArrayList p=new ArrayList<>();\n\n if(s[1])p.add(new Pair(0,1));\n\n while(!queue.isEmpty())\n\n {\n\n int node=queue.poll();\n\n for(int v:edge[node])\n\n {\n\n if(s[v]&&s[node])pres=true;\n\n if(!vis[v])\n\n {\n\n d1[v]=d1[node]+1;\n\n vis[v]=true;\n\n queue.add(v);\n\n if(s[v])p.add(new Pair(d1[v],v));\n\n }\n\n }\n\n }\n\n if(pres)\n\n {\n\n System.out.println(d1[n]);\n\n return;\n\n }\n\n Arrays.fill(vis,false);\n\n vis[n]=true;\n\n queue.add(n);\n\n while(!queue.isEmpty())\n\n {\n\n int node=queue.poll();\n\n for(int v:edge[node])\n\n {\n\n if(!vis[v])\n\n {\n\n dn[v]=dn[node]+1;\n\n vis[v]=true;\n\n queue.add(v);\n\n }\n\n }\n\n }\n\n int ans=0,curr=dn[p.get(k-1).s];\n\n for(int i=k-2;i>=0;i--)\n\n {\n\n ans=Math.max(ans,d1[p.get(i).s]+curr+1);\n\n curr=Math.max(curr,dn[p.get(i).s]);\n\n }\n\n ans=Math.min(ans,d1[n]);\n\n pw.println(ans);\n\n pw.flush();\n\n pw.close();\n\n }\n\n}","language":"java"} -{"contest_id":"1294","problem_id":"C","statement":"C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2\u2264a,b,c2\u2264a,b,c and a\u22c5b\u22c5c=na\u22c5b\u22c5c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2\u2264n\u22641092\u2264n\u2264109).OutputFor each test case, print the answer on it. Print \"NO\" if it is impossible to represent nn as a\u22c5b\u22c5ca\u22c5b\u22c5c for some distinct integers a,b,ca,b,c such that 2\u2264a,b,c2\u2264a,b,c.Otherwise, print \"YES\" and any possible such representation.ExampleInputCopy5\n64\n32\n97\n2\n12345\nOutputCopyYES\n2 4 8 \nNO\nNO\nNO\nYES\n3 5 823 \n","tags":["greedy","math","number theory"],"code":"import java.io.*;\n\n\n\npublic class Main {\n\n public static void productTriplet(int num) {\n\n int a, b;\n\n int c = 0;\n\n for (a = 2; a * a * a <= num; a++) {\n\n if(num % a == 0) {\n\n break;\n\n }\n\n }\n\n int rem = num \/ a;\n\n for (b = a + 1; b * b <= rem; b++) {\n\n if(rem % b == 0) {\n\n c = rem \/ b;\n\n if(b >= c) {\n\n c = 0;\n\n }\n\n break;\n\n }\n\n }\n\n if(a * b * c == num) {\n\n out.println(\"YES\");\n\n out.println(a + \" \" + b + \" \" + c);\n\n }\n\n else\n\n out.println(\"NO\");\n\n }\n\n\n\n static PrintWriter out = new PrintWriter(System.out);\n\n public static void main(String[] args) throws IOException {\n\n BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n\n\n\n int q = Integer.parseInt(read.readLine());\n\n while(q-- > 0) {\n\n int num = Integer.parseInt(read.readLine());\n\n productTriplet(num);\n\n }\n\n out.close();\n\n }\n\n}","language":"java"} -{"contest_id":"1322","problem_id":"A","statement":"A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting \"+\" and \"1\" you can get a well-formed mathematical expression from it. For example; sequences \"(())()\", \"()\" and \"(()(()))\" are correct, while \")(\", \"(()\" and \"(()))(\" are not.The teacher gave Dmitry's class a very strange task\u00a0\u2014 she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word \"correct\" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for \"))((\" he can choose the substring \")(\" and do reorder \")()(\" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1\u2264n\u22641061\u2264n\u2264106)\u00a0\u2014 the length of Dima's sequence.The second line contains string of length nn, consisting of characters \"(\" and \")\" only.OutputPrint a single integer\u00a0\u2014 the minimum number of nanoseconds to make the sequence correct or \"-1\" if it is impossible to do so.ExamplesInputCopy8\n))((())(\nOutputCopy6\nInputCopy3\n(()\nOutputCopy-1\nNoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with \"()()\"; the whole sequence will be \"()()())(\". And then reorder the segment from the seventh to eighth character; replacing it with \"()\". In the end the sequence will be \"()()()()\"; while the total time spent is 4+2=64+2=6 nanoseconds.","tags":["greedy"],"code":"import java.io.*;\n\nimport java.util.*;\n\n\n\npublic class cf {\n\n\n\n static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public FastReader() {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n\n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n\n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n float nextFloat() {\n\n return Float.parseFloat(next());\n\n }\n\n\n\n String nextLine() {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n\n\n void readArr(int[] ar, int n) {\n\n for (int i = 0; i < n; i++) {\n\n ar[i] = nextInt();\n\n }\n\n }\n\n }\n\n\n\n public static long gcd(long a, long b) {\n\n if (b == 0) {\n\n return a;\n\n }\n\n return gcd(b, a % b);\n\n }\n\n\n\n public static boolean binary_search(long[] a, long k) {\n\n long low = 0;\n\n long high = a.length - 1;\n\n long mid = 0;\n\n while (low <= high) {\n\n mid = low + (high - low) \/ 2;\n\n if (a[(int) mid] == k) {\n\n return true;\n\n } else if (a[(int) mid] < k) {\n\n low = mid + 1;\n\n } else {\n\n high = mid - 1;\n\n }\n\n }\n\n return false;\n\n }\n\n\n\n public static int bSearchDiff(long[] a, int low, int high) {\n\n int mid = low + ((high - low) \/ 2);\n\n int hight = high;\n\n int lowt = low;\n\n while (lowt < hight) {\n\n mid = lowt + (hight - lowt) \/ 2;\n\n if (a[high] - a[mid] <= 5) {\n\n hight = mid;\n\n } else {\n\n lowt = mid + 1;\n\n }\n\n }\n\n return lowt;\n\n }\n\n\n\n public static long lowerbound(long a[], long ddp) {\n\n long low = 0;\n\n long high = a.length;\n\n long mid = 0;\n\n while (low < high) {\n\n mid = low + (high - low) \/ 2;\n\n \/\/ if (a[(int) mid] == ddp) {\n\n \/\/ return mid;\n\n \/\/ }\n\n if (a[(int) mid] <= ddp) {\n\n low = mid + 1;\n\n } else {\n\n high = mid;\n\n }\n\n }\n\n \/\/ if(low + 1 < a.length && a[(int)low + 1] <= ddp){\n\n \/\/ low++;\n\n \/\/ }\n\n if (low == a.length && low != 0) {\n\n low--;\n\n return low;\n\n }\n\n if (a[(int) low] > ddp && low != 0) {\n\n low--;\n\n }\n\n return low;\n\n }\n\n\n\n public static long lowerbound(long a[], long ddp, long factor) {\n\n long low = 0;\n\n long high = a.length;\n\n long mid = 0;\n\n while (low < high) {\n\n mid = low + (high - low) \/ 2;\n\n if ((a[(int) mid] + (mid * factor)) == ddp) {\n\n return mid;\n\n }\n\n if ((a[(int) mid] + (mid * factor)) < ddp) {\n\n low = mid + 1;\n\n } else {\n\n high = mid;\n\n }\n\n }\n\n \/\/ if(low + 1 < a.length && a[(int)low + 1] <= ddp){\n\n \/\/ low++;\n\n \/\/ }\n\n if (low == a.length && low != 0) {\n\n low--;\n\n return low;\n\n }\n\n if (a[(int) low] > ddp - (low * factor) && low != 0) {\n\n low--;\n\n }\n\n return low;\n\n }\n\n\n\n public static long lowerbound(List a, long ddp) {\n\n long low = 0;\n\n long high = a.size();\n\n long mid = 0;\n\n while (low < high) {\n\n mid = low + (high - low) \/ 2;\n\n if (a.get((int) mid) == ddp) {\n\n return mid;\n\n }\n\n if (a.get((int) mid) < ddp) {\n\n low = mid + 1;\n\n } else {\n\n high = mid;\n\n }\n\n }\n\n \/\/ if(low + 1 < a.length && a[(int)low + 1] <= ddp){\n\n \/\/ low++;\n\n \/\/ }\n\n if (low == a.size() && low != 0) {\n\n low--;\n\n return low;\n\n }\n\n if (a.get((int) low) > ddp && low != 0) {\n\n low--;\n\n }\n\n return low;\n\n }\n\n\n\n public static long lowerboundforpairs(pair a[], double pr) {\n\n long low = 0;\n\n long high = a.length;\n\n long mid = 0;\n\n while (low < high) {\n\n mid = low + (high - low) \/ 2;\n\n if (a[(int) mid].w <= pr) {\n\n low = mid + 1;\n\n } else {\n\n high = mid;\n\n }\n\n }\n\n \/\/ if(low + 1 < a.length && a[(int)low + 1] <= ddp){\n\n \/\/ low++;\n\n \/\/ }\n\n \/\/ if(low == a.length && low != 0){\n\n \/\/ low--;\n\n \/\/ return low;\n\n \/\/ }\n\n \/\/ if(a[(int)low].w > pr && low != 0){\n\n \/\/ low--;\n\n \/\/ }\n\n return low;\n\n }\n\n\n\n public static long upperbound(long a[], long ddp) {\n\n long low = 0;\n\n long high = a.length;\n\n long mid = 0;\n\n while (low < high) {\n\n mid = low + (high - low) \/ 2;\n\n if (a[(int) mid] <= ddp) {\n\n low = mid + 1;\n\n } else {\n\n high = mid;\n\n }\n\n }\n\n if (low == a.length) {\n\n return a.length - 1;\n\n }\n\n return low;\n\n }\n\n\n\n public static long upperbound(ArrayList a, long ddp) {\n\n long low = 0;\n\n long high = a.size();\n\n long mid = 0;\n\n while (low < high) {\n\n mid = low + (high - low) \/ 2;\n\n if (a.get((int) mid) <= ddp) {\n\n low = mid + 1;\n\n } else {\n\n high = mid;\n\n }\n\n }\n\n return low;\n\n }\n\n\n\n \/\/ public static class pair implements Comparable {\n\n \/\/ long w;\n\n \/\/ long h;\n\n\n\n \/\/ public pair(long w, long h) {\n\n \/\/ this.w = w;\n\n \/\/ this.h = h;\n\n \/\/ }\n\n\n\n \/\/ public int compareTo(pair b) {\n\n \/\/ if (this.w != b.w)\n\n \/\/ return (int) (this.w - b.w);\n\n \/\/ else\n\n \/\/ return (int) (this.h - b.h);\n\n \/\/ }\n\n \/\/ }\n\n\n\n public static class pairs {\n\n char w;\n\n int h;\n\n\n\n public pairs(char w, int h) {\n\n this.w = w;\n\n this.h = h;\n\n }\n\n }\n\n\n\n public static class pair {\n\n long w;\n\n long h;\n\n\n\n public pair(long w, long h) {\n\n this.w = w;\n\n this.h = h;\n\n }\n\n\n\n @Override\n\n public int hashCode() {\n\n return Objects.hash(w, h);\n\n }\n\n\n\n @Override\n\n public boolean equals(Object o) {\n\n if (o == this) {\n\n return true;\n\n }\n\n if (!(o instanceof pair)) {\n\n return false;\n\n }\n\n pair c = (pair) o;\n\n return Long.compare(this.w, c.w) == 0 && Long.compare(this.h, h) == 0;\n\n }\n\n }\n\n\n\n public static class trinary {\n\n long a;\n\n long b;\n\n long c;\n\n\n\n public trinary(long a, long b, long c) {\n\n this.a = a;\n\n this.b = b;\n\n this.c = c;\n\n }\n\n }\n\n\n\n public static pair[] sortpair(pair[] a) {\n\n Arrays.sort(a, new Comparator() {\n\n public int compare(pair p1, pair p2) {\n\n if (p1.w != p2.w) {\n\n return (int) (p1.w - p2.w);\n\n }\n\n return (int) (p1.h - p2.h);\n\n }\n\n });\n\n return a;\n\n }\n\n\n\n public static trinary[] sortpair(trinary[] a) {\n\n Arrays.sort(a, new Comparator() {\n\n public int compare(trinary p1, trinary p2) {\n\n if (p1.b != p2.b) {\n\n return (int) (p1.b - p2.b);\n\n } else if (p1.c != p2.c) {\n\n return (int) (p1.c - p2.c);\n\n }\n\n return (int) (p1.a - p2.a);\n\n }\n\n });\n\n return a;\n\n }\n\n\n\n public static void sort(long[] arr) {\n\n ArrayList a = new ArrayList<>();\n\n for (long i : arr) {\n\n a.add(i);\n\n }\n\n Collections.sort(a);\n\n for (int i = 0; i < a.size(); i++) {\n\n arr[i] = a.get(i);\n\n }\n\n }\n\n\n\n public static void sortForObjecttypes(pair[] arr) {\n\n ArrayList a = new ArrayList<>();\n\n for (pair i : arr) {\n\n a.add(i);\n\n }\n\n Collections.sort(a, new Comparator() {\n\n @Override\n\n public int compare(pair a, pair b) {\n\n\n\n return (int) (a.h - b.h);\n\n }\n\n });\n\n for (int i = 0; i < a.size(); i++) {\n\n arr[i] = a.get(i);\n\n }\n\n }\n\n\n\n public static boolean ispalindrome(String s) {\n\n long i = 0;\n\n long j = s.length() - 1;\n\n boolean is = false;\n\n while (i < j) {\n\n if (s.charAt((int) i) == s.charAt((int) j)) {\n\n is = true;\n\n i++;\n\n j--;\n\n } else {\n\n is = false;\n\n return is;\n\n }\n\n }\n\n return is;\n\n }\n\n\n\n public static long power(long base, long pow, long mod) {\n\n long result = base;\n\n long temp = 1;\n\n while (pow > 1) {\n\n if (pow % 2 == 0) {\n\n result = ((result % mod) * (result % mod)) % mod;\n\n pow \/= 2;\n\n } else {\n\n temp = temp * base;\n\n pow--;\n\n }\n\n }\n\n result = ((result % mod) * (temp % mod));\n\n \/\/ System.out.println(result);\n\n return result;\n\n }\n\n\n\n public static long sqrt(long n) {\n\n long res = 1;\n\n long l = 1, r = (long) 10e9;\n\n while (l <= r) {\n\n long mid = (l + r) \/ 2;\n\n if (mid * mid <= n) {\n\n res = mid;\n\n l = mid + 1;\n\n } else\n\n r = mid - 1;\n\n }\n\n return res;\n\n }\n\n\n\n public static boolean is[] = new boolean[10001];\n\n public static int a[] = new int[10001];\n\n\n\n public static Vector seiveOfEratosthenes() {\n\n Vector listA = new Vector<>();\n\n for (int i = 2; i * i <= a.length; i++) {\n\n if (a[i] != 1) {\n\n for (long j = i * i; j < a.length; j += i) {\n\n a[(int) j] = 1;\n\n }\n\n }\n\n }\n\n for (int i = 2; i < a.length; i++) {\n\n if (a[i] == 0) {\n\n is[i] = true;\n\n listA.add(i);\n\n }\n\n }\n\n return listA;\n\n }\n\n\n\n public static Vector ans = seiveOfEratosthenes();\n\n\n\n public static long sumOfDigits(long n) {\n\n long ans = 0;\n\n while (n != 0) {\n\n ans += n % 10;\n\n n \/= 10;\n\n }\n\n return ans;\n\n }\n\n\n\n public static long gcdTotal(long a[]) {\n\n long t = a[0];\n\n for (int i = 1; i < a.length; i++) {\n\n t = gcd(t, a[i]);\n\n }\n\n return t;\n\n }\n\n\n\n public static ArrayList al = new ArrayList<>();\n\n\n\n public static void makeArr() {\n\n long t = 1;\n\n while (t <= 10e17) {\n\n al.add(t);\n\n t *= 2;\n\n }\n\n }\n\n\n\n public static boolean isBalancedBrackets(String s) {\n\n if (s.length() == 1) {\n\n return false;\n\n }\n\n Stack sO = new Stack<>();\n\n int id = 0;\n\n while (id < s.length()) {\n\n if (s.charAt(id) == '(') {\n\n sO.add('(');\n\n }\n\n if (s.charAt(id) == ')') {\n\n if (!sO.isEmpty()) {\n\n sO.pop();\n\n } else {\n\n return false;\n\n }\n\n }\n\n id++;\n\n }\n\n if (sO.isEmpty()) {\n\n return true;\n\n }\n\n return false;\n\n }\n\n\n\n public static void solve(FastReader sc, PrintWriter w, StringBuilder sb) throws Exception {\n\n int n = sc.nextInt();\n\n String s = sc.nextLine();\n\n int openings[] = new int[n + 1];\n\n int closings[] = new int[n + 1];\n\n for (int i = 0; i < n; i++) {\n\n if (s.charAt(i) == ')') {\n\n closings[i + 1] = closings[i] + 1;\n\n openings[i + 1] = openings[i];\n\n } else {\n\n openings[i + 1] = openings[i] + 1;\n\n closings[i + 1] = closings[i];\n\n }\n\n }\n\n if (openings[n] != closings[n]) {\n\n sb.append(-1);\n\n return;\n\n }\n\n int ans = 0;\n\n int prev = 0;\n\n for (int i = 0; i < n; i++) {\n\n if (openings[i + 1] == closings[i + 1]) {\n\n if (!isBalancedBrackets(s.substring(prev, i + 1))) {\n\n ans += i - prev + 1;\n\n prev = i + 1;\n\n } else {\n\n prev = i + 1;\n\n }\n\n }\n\n }\n\n sb.append(ans);\n\n }\n\n\n\n public static void main(String[] args) throws Exception {\n\n FastReader sc = new FastReader();\n\n PrintWriter w = new PrintWriter(System.out);\n\n StringBuilder sb = new StringBuilder();\n\n \/\/ long o = sc.nextLong();\n\n \/\/ \/\/ makeArr();\n\n \/\/ while (o > 0) {\n\n solve(sc, w, sb);\n\n \/\/ o--;\n\n \/\/ }\n\n System.out.print(sb.toString());\n\n w.close();\n\n }\n\n}","language":"java"} -{"contest_id":"1324","problem_id":"C","statement":"C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2\u2026sns=s1s2\u2026sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i\u2212d);i\u22121][max(0,i\u2212d);i\u22121], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2\u22c51052\u22c5105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2\u22c51052\u22c5105 (\u2211|s|\u22642\u22c5105\u2211|s|\u22642\u22c5105).OutputFor each test case, print the answer \u2014 the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6\nLRLRRLL\nL\nLLR\nRRRR\nLLLLLL\nR\nOutputCopy3\n2\n3\n1\n7\n1\nNoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.","tags":["binary search","data structures","dfs and similar","greedy","implementation"],"code":"\/***** ---> :) Vijender Srivastava (: <--- *****\/\n\nimport java.util.*;\n\nimport java.lang.*;\n\nimport java.io.*;\n\npublic class Main \n\n{\n\n static FastReader sc =new FastReader();\n\n static PrintWriter out=new PrintWriter(System.out);\n\n static long mod=(long)998244353;\n\n static StringBuilder sb = new StringBuilder();\n\n\n\n\n\n\n\n \/* start *\/\n\n \n\n public static void main(String [] args)\n\n {\n\n int testcases = 1;\n\n testcases = i();\n\n \/\/ calc();\n\n while(testcases-->0)\n\n {\n\n \n\n solve();\n\n }\n\n out.flush();\n\n out.close();\n\n }\n\n static void solve()\n\n { \n\n String s = \"R\"+sc.next()+\"R\";\n\n int i=0,max = 0;\n\n for(int j=1;j0){\n\n if((b&1)==1) res=mul_mod(res,a);\n\n a=mul_mod(a,a);\n\n b\/=2;\n\n }\n\n return res;\n\n }\n\n public static long fac_mod(long n){\n\n if(n==0)return 1;\n\n return mul_mod(fac_mod(n-1),n);\n\n }\n\n\n\n static long mul_mod(long x,long y)\n\n {\n\n return mod(mod(x)*mod(y));\n\n }\n\n static long power(long x, long y)\n\n {\n\n\n\n\tif(y==0)\n\n\t\treturn 1;\n\n\tif(x==0)\n\n\t\treturn 0;\n\n long res = 1;\n\n while (y > 0) {\n\n\n\n if (y % 2 == 1)\n\n res = (res * x) ;\n\n\n\n y = y >> 1; \n\n x = (x * x);\n\n }\n\n\n\n return res;\n\n }\n\n\n\n static boolean prime(int n) \n\n\t { \n\n\t if (n <= 1) \n\n\t return false; \n\n\t if (n <= 3) \n\n\t return true; \n\n\t if (n % 2 == 0 || n % 3 == 0) \n\n\t return false; \n\n\t double sq=Math.sqrt(n);\n\n\t \n\n\t for (int i = 5; i <= sq; i = i + 6) \n\n\t if (n % i == 0 || n % (i + 2) == 0) \n\n\t return false; \n\n\t return true; \n\n\t } \n\n\n\n static boolean prime(long n) \n\n\t { \n\n\t if (n <= 1) \n\n\t return false; \n\n\t if (n <= 3) \n\n\t return true; \n\n\t if (n % 2 == 0 || n % 3 == 0) \n\n\t return false; \n\n\t double sq=Math.sqrt(n);\n\n\t \n\n\t for (int i = 5; i <= sq; i = i + 6) \n\n\t if (n % i == 0 || n % (i + 2) == 0) \n\n\t return false; \n\n\t return true; \n\n\t } \n\n\n\n static long[] sort(long a[]) {\n\n ArrayList arr = new ArrayList<>();\n\n for(long i : a) {\n\n arr.add(i);\n\n }\n\n Collections.sort(arr);\n\n for(int i = 0; i < arr.size(); i++) {\n\n a[i] = arr.get(i);\n\n }\n\n return a;\n\n }\n\n \n\n static int[] sort(int a[])\n\n {\n\n ArrayList arr = new ArrayList<>();\n\n for(Integer i : a) {\n\n arr.add(i);\n\n }\n\n Collections.sort(arr);\n\n for(int i = 0; i < arr.size(); i++) {\n\n a[i] = arr.get(i);\n\n }\n\n return a;\n\n }\n\n\n\n static int[] sortInd(int a[])\n\n {\n\n int n = a.length;\n\n int ii[] = new int[n];\n\n for(int i=0;ia[i]-a[j]).mapToInt($->$).toArray();\n\n\n\n return ii;\n\n }\n\n \/\/pair class\n\n private static class Pair implements Comparable {\n\n long first, second;\n\n public Pair(long f, long s) {\n\n first = f;\n\n second = s;\n\n }\n\n @Override\n\n public int compareTo(Pair p) {\n\n if (first < p.first)\n\n return 1;\n\n else if (first > p.first)\n\n return -1;\n\n else {\n\n if (second > p.second)\n\n return 1;\n\n else if (second < p.second)\n\n return -1;\n\n else\n\n return 0;\n\n }\n\n }\n\n \n\n }\n\n \n\n}","language":"java"} -{"contest_id":"1313","problem_id":"A","statement":"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\u2264t\u22645001\u2264t\u2264500)\u00a0\u2014 the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0\u2264a,b,c\u2264100\u2264a,b,c\u226410)\u00a0\u2014 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\u00a0\u2014 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.","tags":["brute force","greedy","implementation"],"code":"import java.util.Scanner;\n\npublic class CF0712{\n\n\tpublic static void main(String[] args) {\n\n\t\tScanner scan = new Scanner(System.in);\n\n\t\tint testCases = scan.nextInt();\n\n\t\twhile(testCases>0){\n\n\t\t\tint a = scan.nextInt();\n\n\t\t\tint b = scan.nextInt();\n\n\t\t\tint c = scan.nextInt();\n\n\t\t\tint counter = 0;\n\n\t\t\tif(b>a){\n\n\t\t\t\tint temp = a;\n\n\t\t\t\ta = b;\n\n\t\t\t\tb = temp;\n\n\t\t\t}\n\n\t\t\tif(c>b){\n\n\t\t\t\tint temp = b;\n\n\t\t\t\tb = c;\n\n\t\t\t\tc = temp;\n\n\t\t\t}\n\n\t\t\tif(b>a){\n\n\t\t\t\tint temp = a;\n\n\t\t\t\ta = b;\n\n\t\t\t\tb = temp;\n\n\t\t\t}\n\n\t\t\tif(a>0){\n\n\t\t\t\tcounter++;\n\n\t\t\t\ta--;\n\n\t\t\t}if(b>0){\n\n\t\t\t\tcounter++;\n\n\t\t\t\tb--;\n\n\t\t\t}if(c>0){\n\n\t\t\t\tcounter++;\n\n\t\t\t\tc--;\n\n\t\t\t}if(a>0 && b>0){\n\n\t\t\t\tcounter++;a--;b--;\n\n\t\t\t}if(a>0 && c>0){\n\n\t\t\t\tcounter++;a--;c--;\n\n\t\t\t}if(b>0 && c>0){\n\n\t\t\t\tcounter++; b--;c--;\n\n\t\t\t}if(a>0 && b>0 && c>0){\n\n\t\t\t\tcounter++;\n\n\t\t\t}\n\n\t\t\tSystem.out.println(counter);\n\n\t\t\ttestCases--;\n\n\t\t}\n\n\t}\n\n}","language":"java"} -{"contest_id":"1303","problem_id":"C","statement":"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 \u2014 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\u2264T\u226410001\u2264T\u22641000) \u2014 the number of test cases.Then TT lines follow, each containing one string ss (1\u2264|s|\u22642001\u2264|s|\u2264200) 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 \u2014 the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5\nababa\ncodedoca\nabcda\nzxzytyz\nabcdefghijklmnopqrstuvwxyza\nOutputCopyYES\nbacdefghijklmnopqrstuvwxyz\nYES\nedocabfghijklmnpqrstuvwxyz\nNO\nYES\nxzytabcdefghijklmnopqrsuvw\nNO\n","tags":["dfs and similar","greedy","implementation"],"code":"import java.lang.*;\nimport java.util.*;\nimport java.io.*;\n\npublic class practice{\n\n static int components;\n\n private static int find(int[] parent, int x){\n\n if (!(x>=0 && x= cost[r2]){\n parent[r1] += parent[r2];\n parent[r2] = r1;\n }else{\n parent[r2] += parent[r1];\n parent[r1] = r2;\n }\n\n }\n\n private static boolean check(int[] parent, int x1, int x2){\n int r1 = find(parent, x1), r2 = find(parent, x2);\n\n if (r1 == r2){\n return false;\n }\n\n return true;\n }\n\n private static int dfs(List> adj, int idx){\n\n if (adj.get(idx).size() == 0){\n return 1;\n }\n\n List nei = adj.get(idx);\n\n int count = 0;\n\n for (int ne : nei){\n count += dfs(adj, ne);\n }\n\n return count;\n\n }\n\n public static class Pair{\n private int idx;\n private int sum;\n\n Pair(int idx, int sum){\n this.idx = idx;\n this.sum = sum;\n }\n }\n\n private static int rec(int v, int[] dp){\n if (v == 0){\n return 0;\n }\n\n if (dp[v] != -1){\n return dp[v];\n }\n\n return (dp[v]=1+Math.min(rec((v+1)%32768, dp), rec((2*v)%32768, dp)));\n\n }\n\n static class Node {\n \n int idx, level;\n \n public Node(int v, int d) {\n this.idx = v;\n this.level = d;\n }\n \n }\n static boolean vis[] = new boolean[100005];\n\n public static void main(String args[]) throws IOException{\n\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n \/\/StringTokenizer st = new StringTokenizer(br.readLine());\n\n int t = Integer.parseInt(br.readLine().trim()); \n\n while (t-->0){\n String s = br.readLine().trim();\n\n if (s.length() == 1){\n System.out.println(\"YES\");\n StringBuilder sb = new StringBuilder();\n\n boolean[] visited = new boolean[26];\n\n visited[s.charAt(0)-'a'] = true;\n\n sb.append(s.charAt(0));\n\n for (int i=0 ; i<26 ; i++){\n if (!visited[i]){\n sb.append((char)(i+'a'));\n }\n }\n\n System.out.println(sb.toString());\n\n continue;\n }\n\n Set[] adj = new HashSet[26];\n\n for (int i=0 ; i<26 ; i++){\n adj[i] = new HashSet<>();\n }\n\n char[] arr = s.toCharArray();\n\n boolean check = true;\n\n for (int i=1 ; i=3 || adj[v].size()>=3){\n check = false;\n }\n }\n\n if (!check){\n System.out.println(\"NO\");\n continue;\n }\n\n int start_idx = -1;\n\n for (int i=0 ; i<26 ; i++){\n if (adj[i].size() == 1){\n start_idx = i;\n }\n }\n\n if (start_idx == -1){\n System.out.println(\"NO\");\n continue;\n }\n\n boolean[] visited = new boolean[26];\n\n StringBuilder sb = new StringBuilder();\n\n LinkedList q = new LinkedList<>();\n q.offer(start_idx);\n\n while(!q.isEmpty()){\n int size = q.size();\n\n while (size-->0){\n int tmp = q.poll();\n\n sb.append((char)(tmp+'a'));\n\n visited[tmp] = true;\n\n for (int next : adj[tmp]){\n if (!visited[next]){\n q.offer(next);\n }\n }\n }\n }\n\n for(int i=0 ; i<26 ; i++){\n if(!visited[i]){\n sb.append((char)(i+'a'));\n }\n }\n\n System.out.println(\"YES\");\n System.out.println(sb.toString());\n }\n }\n\n}","language":"java"} -{"contest_id":"1316","problem_id":"A","statement":"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\u2264ai\u2264m0\u2264ai\u2264m 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\u2264t\u22642001\u2264t\u2264200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1\u2264n\u22641031\u2264n\u2264103, 1\u2264m\u22641051\u2264m\u2264105) \u00a0\u2014 the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u2264m0\u2264ai\u2264m) \u00a0\u2014 scores of the students.OutputFor each testcase, output one integer \u00a0\u2014 the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2\n4 10\n1 2 3 4\n4 5\n1 2 3 4\nOutputCopy10\n5\nNoteIn 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\u2264ai\u226450\u2264ai\u22645. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0\u2264ai\u2264m0\u2264ai\u2264m.","tags":["implementation"],"code":"\n\nimport java.util.Scanner;\n\npublic class CF{\n\n\tpublic static void main(String[] args){\n\n\t\tScanner scan = new Scanner(System.in);\n\n\t\tint testCas = scan.nextInt();\n\n\t\twhile(testCas>0){\n\n\t\t\tint arrayLength = scan.nextInt();\n\n\t\t\tint maxPossibleScore = scan.nextInt();\n\n\t\t\tint totalSumOfScores = 0;\n\n\t\t\tfor(int i=0; i=0 && tsum>=0;i--) {\n\n if(((xor&(p<0?1:0)>0) {\n\n \t tsum-=(p<=0 && tsum>=0;i--) {\n\n\/\/ \t System.out.println(p<0?1:0)>0)?1:0;\n\n max=Math.max(max, (int)(count+shift));\n\n tsum-=(count*(p<=0;i--) {\n\n \t if(((xor&(p<0?1:0)>0) {\n\n ans[0]+=(p<=0;i--) {\n\n \t long count=tsum\/(p<0?1:0)>0)?1:0;\n\n \t for(int j=shift;j> ar,int a[],int src,int xor,int pr) {\n\n int xr=a[src];\n\n for(int k:ar.get(src)) {\n\n\t if(k==pr)continue;\n\n\t xr^=eval(ar,a,k,xor,src);\n\n }\n\n if(xr==(xor^xr))ans=true;\n\n return xr;\n\n}\n\nstatic int eval2(ArrayList> ar,int a[],int src,int xor,int pr) {\n\n\tint xr=a[src];\n\n\tfor(int k:ar.get(src)) {\n\n\t\t if(k==pr)continue;\n\n\t\t xr^=eval2(ar,a,k,xor,src);\n\n\t}\n\n\tif(xr==xor) {\n\n\t\tcnt++;\n\n\t\treturn 0;\n\n\t}\n\n\telse return xr;\n\n}\n\npublic static int m=(int)(998244353);\t\n\npublic static int mul(int a, int b) {\n\n\treturn ((a%m)*(b%m))%m;\n\n}\n\npublic static long mul(long a, long b) {\n\n\treturn ((a%m)*(b%m))%m;\n\n}\n\npublic static int add(int a, int b) {\n\n\treturn ((a%m)+(b%m))%m;\n\n}\n\npublic static long add(long a, long b) {\n\n\treturn ((a%m)+(b%m))%m;\n\n}\n\npublic static long sub(long a,long b) {\n\nreturn ((a%m)-(b%m)+m)%m;\t\n\n}\n\nstatic long gcd(long a,long b) {\n\n\tif(b==0)return a;\n\n\telse return gcd(b,a%b);\n\n}\n\nstatic int gcd(int a,int b) {\n\n\tif(b==0)return a;\n\n\telse return gcd(b,a%b);\n\n}\n\n\tstatic long ncr(int n, int r){\n\n\t if(r>n-r)r=n-r;\n\n\t long ans=1;\n\n\t long m=(int)(1e9+7);\n\n\t for(int i=0;i=end)return ;\n\n\t\tint mid=start+(end-start)\/2;\n\n\t\tmergesort(a,start,mid);\n\n\t\tmergesort(a,mid+1,end);\n\n\t\tmerge(a,start,mid,end);\n\n\t\t\n\n\t}\n\nstatic void merge(int[] a, int start,int mid,int end) {\n\n\t\tint ptr1=start;\n\n\t\tint ptr2=mid+1;\n\n\t\tint b[]=new int[end-start+1];\n\n\t\tint i=0;\n\n\t\twhile(ptr1<=mid && ptr2<=end) {\n\n\t\t\tif(a[ptr1]<=a[ptr2]) {\n\n\t\t\t\tb[i]=a[ptr1];\n\n\t\t\t\tptr1++;\n\n\t\t\t\ti++;\n\n\t\t\t}\n\n\t\t\telse {\n\n\t\t\t\tb[i]=a[ptr2];\n\n\t\t\t\tptr2++;\n\n\t\t\t\ti++;\n\n\t\t\t}\n\n\t\t}\n\n\t\twhile(ptr1<=mid) {\n\n\t\t\tb[i]=a[ptr1];\n\n\t\t\tptr1++;\n\n\t\t\ti++;\n\n\t\t}\n\n\t\twhile(ptr2<=end) {\n\n\t\t\tb[i]=a[ptr2];\n\n\t\t\tptr2++;\n\n\t\t\ti++;\n\n\t\t}\n\n\t\tfor(int j=start;j<=end;j++) {\n\n\t\t\ta[j]=b[j-start];\n\n\t\t}\n\n\t}\n\n\tpublic static class FastReader {\n\n\t\n\n\t\t\tBufferedReader b;\n\n\t\t\tStringTokenizer s;\n\n\t\t\tpublic FastReader() {\n\n\t\t\t\tb=new BufferedReader(new InputStreamReader(System.in));\n\n\t\t\t}\n\n\t\t\tString next() {\n\n\t\t\t\twhile(s==null ||!s.hasMoreElements()) {\n\n\t\t\t\t\ttry {\n\n\t\t\t\t\t\ts=new StringTokenizer(b.readLine());\n\n\t\t\t\t\t}\n\n\t\t\t\t\tcatch(IOException e) {\n\n\t\t\t\t\t\te.printStackTrace();\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\treturn s.nextToken();\n\n\t\t\t}\n\n\t\t\tpublic int nextInt() {\n\n\t\t\t\treturn Integer.parseInt(next());\n\n\t\t\t}\n\n\t\t\tpublic long nextLong() {\n\n\t\t\t\treturn Long.parseLong(next());\n\n\t\t\t}\n\n\t\t\tpublic double nextDouble() {\n\n\t\t\t\treturn Double.parseDouble(next());\n\n\t\t\t}\n\n\t\t\tString nextLine() {\n\n\t\t\t\tString str=\"\";\n\n\t\t\t\ttry {\n\n\t\t\t\t\tstr=b.readLine();\n\n\t\t\t\t}\n\n\t\t\t\tcatch(IOException e) {\n\n\t\t\t\t\te.printStackTrace();\n\n\t\t\t\t}\n\n\t\t\t\treturn str;\n\n\t\t\t}\n\n\t\t\tboolean hasNext() {\n\n\t\t\t if (s != null && s.hasMoreTokens()) {\n\n\t\t\t return true;\n\n\t\t\t }\n\n\t\t\t String tmp;\n\n\t\t\t try {\n\n\t\t\t b.mark(1000);\n\n\t\t\t tmp = b.readLine();\n\n\t\t\t if (tmp == null) {\n\n\t\t\t return false;\n\n\t\t\t }\n\n\t\t\t b.reset();\n\n\t\t\t } catch (IOException e) {\n\n\t\t\t return false;\n\n\t\t\t }\n\n\t\t\t return true;\n\n\t\t\t}\n\n\t}\n\n\tpublic static class pair{\n\n\t\tint a;\n\n int b;\n\n\t\tpublic pair(int a,int b) {\n\n\t\t\tthis.a=a;\n\n\t\t\tthis.b=b;\n\n\t\t}\n\n\t\t@Override\n\n\t\tpublic String toString() {\n\n\t\t\treturn \"{\"+this.a+\" \"+this.b+\"}\";\n\n\t\t\t}\n\n\t}\t\n\n\t\tstatic long pow(long a, long pw) {\n\n\t\t\tlong temp;\n\n\t\t\tif(pw==0)return 1;\n\n\t\t\ttemp=pow(a,pw\/2);\n\n\t\t\tif(pw%2==0)return mul(temp,temp);\n\n\t\t\treturn mul(a,mul(temp,temp));\n\n\t\t\t\n\n\t\t}\n\n\t\tpublic static int md=998244353;\t\t\n\n\t\tstatic int pow(int a, int pw) {\n\n\t\t\tint temp;\n\n\t\t\tif(pw==0)return 1;\n\n\t\t\ttemp=pow(a,pw\/2);\n\n\t\t\tif(pw%2==0)return temp*temp;\n\n\t\t\treturn a*temp*temp;\n\n\t\t\t\n\n\t\t}\n\n\t\n\n}","language":"java"} -{"contest_id":"1303","problem_id":"A","statement":"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\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1\u2264|s|\u22641001\u2264|s|\u2264100); 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\n010011\n0\n1111000\nOutputCopy2\n0\n0\nNoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).","tags":["implementation","strings"],"code":"import java.util.*;\n\npublic class waytoolong {\n\n\t\t\n\n\t\tpublic static void main(String args[]) {\n\n\t\t\tScanner s=new Scanner(System.in);\n\n\t\t\tint t=s.nextInt();\n\n\t\t\tfor(int i=0;i '9'); c = getChar()) {\n\n if (c == '-') neg = true;\n\n }\n\n long res = 0;\n\n for (; c >= '0' && c <= '9'; c = getChar()) {\n\n res = (res << 3) + (res << 1) + c - '0';\n\n cnt *= 10;\n\n }\n\n return neg ? -res : res;\n\n }\n\n\n\n public double nextDouble() {\n\n double cur = nextLong();\n\n return c != '.' ? cur : cur + nextLong() \/ cnt;\n\n }\n\n\n\n public double[] nextDoubles(int N) {\n\n double[] res = new double[N];\n\n for (int i = 0; i < N; i++) {\n\n res[i] = nextDouble();\n\n }\n\n return res;\n\n }\n\n\n\n public String next() {\n\n StringBuilder res = new StringBuilder();\n\n while (c <= 32) c = getChar();\n\n while (c > 32) {\n\n res.append(c);\n\n c = getChar();\n\n }\n\n return res.toString();\n\n }\n\n\n\n public String nextLine() {\n\n StringBuilder res = new StringBuilder();\n\n while (c <= 32) c = getChar();\n\n while (c != '\\n') {\n\n res.append(c);\n\n c = getChar();\n\n }\n\n return res.toString();\n\n }\n\n\n\n public boolean hasNext() {\n\n if (c > 32) return true;\n\n while (true) {\n\n c = getChar();\n\n if (c == NC) return false;\n\n else if (c > 32) return true;\n\n }\n\n }\n\n }\n\n\n\n public static void main(String[] args) {\n\n FastScanner in = new FastScanner();\n\n int n = in.nextInt(); \/\/ 1 <= a[i] <= n\n\n int m = in.nextInt(); \/\/ 1 <= i <= m\n\n PrintWriter out = new PrintWriter(System.out);\n\n out.println(getCountOfValidArrays(n, m));\n\n out.close();\n\n }\n\n\n\n private static long add(long a, long b) {\n\n return (a + b) % MOD;\n\n }\n\n\n\n private static final long MOD = (long) (1e9 + 7);\n\n\n\n private static long getCountOfValidArrays(int n, int m) {\n\n long[][] dp = new long[2 * m + 1][n + 1]; \/\/ dp[i][j] = # of valid arrays of size 'i' ending with 'j'\n\n dp[0][0] = 1;\n\n for (int i = 1; i <= 2 * m; i++) {\n\n for (int j = 1; j <= n; j++) {\n\n for (int k = 0; k <= j; k++) {\n\n dp[i][j] = add(dp[i][j], dp[i - 1][k]);\n\n }\n\n }\n\n }\n\n long ans = 0;\n\n for (int i = 0; i <= n; i++) {\n\n ans = add(ans, dp[2 * m][i]);\n\n }\n\n return ans;\n\n }\n\n}\n\n","language":"java"} -{"contest_id":"1304","problem_id":"E","statement":"E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3\u2264n\u22641053\u2264n\u2264105), the number of vertices of the tree.Next n\u22121n\u22121 lines contain two integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n, u\u2260vu\u2260v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1\u2264q\u22641051\u2264q\u2264105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1\u2264x,y,a,b\u2264n1\u2264x,y,a,b\u2264n, x\u2260yx\u2260y, 1\u2264k\u22641091\u2264k\u2264109) \u2013 the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print \"YES\" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print \"NO\".You can print each letter in any case (upper or lower).ExampleInputCopy5\n1 2\n2 3\n3 4\n4 5\n5\n1 3 1 2 2\n1 4 1 3 2\n1 4 1 3 3\n4 2 3 3 9\n5 2 3 3 9\nOutputCopyYES\nYES\nNO\nYES\nNO\nNoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with \"YES\" answers are: 11-st query: 11 \u2013 33 \u2013 22 22-nd query: 11 \u2013 22 \u2013 33 44-th query: 33 \u2013 44 \u2013 22 \u2013 33 \u2013 44 \u2013 22 \u2013 33 \u2013 44 \u2013 22 \u2013 33 ","tags":["data structures","dfs and similar","shortest paths","trees"],"code":"import java.io.*;\n\nimport java.util.*;\n\n\n\nimport static java.lang.Math.*;\n\nimport static java.util.Arrays.*;\n\n\n\npublic class cf1304e_2 {\n\n\n\n public static void main(String[] args) throws IOException {\n\n int n = ri();\n\n dep = new int[n];\n\n anc = new int[n][18];\n\n List> g = rg(n, n - 1);\n\n binary_lifting_dfs(g, 0, -1);\n\n int q = ri();\n\n while (q --> 0) {\n\n int x = rni() - 1, y = ni() - 1, a = ni() - 1, b = ni() - 1, k = ni(), d;\n\n d = dist(a, b);\n\n if (k >= d && (k - d) % 2 == 0) {\n\n prY();\n\n continue;\n\n }\n\n d = dist(a, x) + 1 + dist(y, b);\n\n if (k >= d && (k - d) % 2 == 0) {\n\n prY();\n\n continue;\n\n }\n\n d = dist(a, y) + 1 + dist(x, b);\n\n if (k >= d && (k - d) % 2 == 0) {\n\n prY();\n\n continue;\n\n }\n\n prN();\n\n }\n\n close();\n\n }\n\n\n\n \/\/ initialization: dep[n], anc[n][lg(n)], fill(anc, -1)\n\n static int dep[], anc[][];\n\n\n\n static int dist(int a, int b) {\n\n int lca = lca(a, b);\n\n return (dep[a] - dep[lca]) + (dep[b] - dep[lca]);\n\n }\n\n\n\n static int lca(int a, int b) {\n\n if (dep[a] < dep[b]) {\n\n int __swap = a;\n\n a = b;\n\n b = __swap;\n\n }\n\n for(int i = anc[a].length - 1; i >= 0; --i) {\n\n if(dep[a] - (1 << i) >= dep[b]) {\n\n a = anc[a][i];\n\n }\n\n }\n\n if(a == b) {\n\n return a;\n\n } else {\n\n for(int i = anc[a].length - 1; i >= 0; --i) {\n\n if(anc[a][i] != anc[b][i]) {\n\n a = anc[a][i];\n\n b = anc[b][i];\n\n }\n\n }\n\n return anc[a][0];\n\n }\n\n }\n\n\n\n \/\/ anc should be initialized to all -1s\n\n static void binary_lifting_dfs(List> g, int i, int p) {\n\n if (p == -1) {\n\n dep[i] = 0;\n\n } else {\n\n dep[i] = dep[p] + 1;\n\n }\n\n anc[i][0] = p;\n\n for (int j = 1; j < anc[i].length && anc[i][j - 1] >= 0; ++j) {\n\n anc[i][j] = anc[anc[i][j - 1]][j - 1];\n\n }\n\n for (int n : g.get(i)) {\n\n if (n != p) {\n\n binary_lifting_dfs(g, n, i);\n\n }\n\n }\n\n }\n\n\n\n static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));\n\n static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));\n\n static StringTokenizer input;\n\n static Random __rand = new Random();\n\n\n\n \/\/ references\n\n \/\/ IBIG = 1e9 + 7\n\n \/\/ IMAX ~= 2e9\n\n \/\/ LMAX ~= 9e18\n\n \n\n \/\/ constants\n\n static final int IBIG = 1000000007;\n\n static final int IMAX = 2147483647;\n\n static final int IMIN = -2147483648;\n\n static final long LMAX = 9223372036854775807L;\n\n static final long LMIN = -9223372036854775808L;\n\n \/\/ math util\n\n static int minof(int a, int b, int c) {return min(a, min(b, c));}\n\n 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;}\n\n static long minof(long a, long b, long c) {return min(a, min(b, c));}\n\n 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;}\n\n static int maxof(int a, int b, int c) {return max(a, max(b, c));}\n\n 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;}\n\n static long maxof(long a, long b, long c) {return max(a, max(b, c));}\n\n 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;}\n\n 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;}\n\n 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;}\n\n static int fli(double d) {return (int)d;}\n\n static int cei(double d) {return (int)ceil(d);}\n\n static long fll(double d) {return (long)d;}\n\n static long cel(double d) {return (long)ceil(d);}\n\n static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}\n\n static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}\n\n static int lcm(int a, int b) {return a * b \/ gcf(a, b);}\n\n static long lcm(long a, long b) {return a * b \/ gcf(a, b);}\n\n static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}\n\n static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}\n\n \/\/ array util\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n static void rsort(int[] a) {shuffle(a); sort(a);}\n\n static void rsort(long[] a) {shuffle(a); sort(a);}\n\n static void rsort(double[] a) {shuffle(a); sort(a);}\n\n 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;}\n\n 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;}\n\n 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;}\n\n 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;}\n\n \/\/ graph util\n\n static List> g(int n) {List> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}\n\n static List> sg(int n) {List> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}\n\n static void c(List> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}\n\n static void cto(List> g, int u, int v) {g.get(u).add(v);}\n\n static void dc(List> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}\n\n static void dcto(List> g, int u, int v) {g.get(u).remove(v);}\n\n \/\/ input\n\n static void r() throws IOException {input = new StringTokenizer(rline());}\n\n static int ri() throws IOException {return Integer.parseInt(rline());}\n\n static long rl() throws IOException {return Long.parseLong(rline());}\n\n 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;}\n\n 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;}\n\n 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;}\n\n static char[] rcha() throws IOException {return rline().toCharArray();}\n\n static String rline() throws IOException {return __in.readLine();}\n\n static String n() {return input.nextToken();}\n\n static int rni() throws IOException {r(); return ni();}\n\n static int ni() {return Integer.parseInt(n());}\n\n static long rnl() throws IOException {r(); return nl();}\n\n static long nl() {return Long.parseLong(n());}\n\n static double rnd() throws IOException {r(); return nd();}\n\n static double nd() {return Double.parseDouble(n());}\n\n static List> rg(int n, int m) throws IOException {List> g = g(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}\n\n static void rg(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}\n\n static List> rdg(int n, int m) throws IOException {List> g = g(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}\n\n static void rdg(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}\n\n static List> rsg(int n, int m) throws IOException {List> g = sg(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}\n\n static void rsg(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}\n\n static List> rdsg(int n, int m) throws IOException {List> g = sg(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}\n\n static void rdsg(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}\n\n \/\/ output\n\n static void pr(int i) {__out.print(i);}\n\n static void prln(int i) {__out.println(i);}\n\n static void pr(long l) {__out.print(l);}\n\n static void prln(long l) {__out.println(l);}\n\n static void pr(double d) {__out.print(d);}\n\n static void prln(double d) {__out.println(d);}\n\n static void pr(char c) {__out.print(c);}\n\n static void prln(char c) {__out.println(c);}\n\n static void pr(char[] s) {__out.print(new String(s));}\n\n static void prln(char[] s) {__out.println(new String(s));}\n\n static void pr(String s) {__out.print(s);}\n\n static void prln(String s) {__out.println(s);}\n\n static void pr(Object o) {__out.print(o);}\n\n static void prln(Object o) {__out.println(o);}\n\n static void prln() {__out.println();}\n\n static void pryes() {__out.println(\"yes\");}\n\n static void pry() {__out.println(\"Yes\");}\n\n static void prY() {__out.println(\"YES\");}\n\n static void prno() {__out.println(\"no\");}\n\n static void prn() {__out.println(\"No\");}\n\n static void prN() {__out.println(\"NO\");}\n\n static void pryesno(boolean b) {__out.println(b ? \"yes\" : \"no\");};\n\n static void pryn(boolean b) {__out.println(b ? \"Yes\" : \"No\");}\n\n static void prYN(boolean b) {__out.println(b ? \"YES\" : \"NO\");}\n\n 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]);}\n\n 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]);}\n\n static void prln(double... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}\n\n static void prln(Collection c) {int n = c.size() - 1; Iterator 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();}\n\n static void h() {__out.println(\"hlfd\"); flush();}\n\n static void flush() {__out.flush();}\n\n static void close() {__out.close();}\n\n}","language":"java"} -{"contest_id":"1315","problem_id":"A","statement":"A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a\u00d7ba\u00d7b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0\u2264x2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers\u00a0\u2014 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\n8 8 0 0\n1 10 0 3\n17 31 10 4\n2 1 0 0\n5 10 3 9\n10 10 4 8\nOutputCopy56\n6\n442\n1\n45\n80\nNoteIn the first test case; the screen resolution is 8\u00d788\u00d78, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. ","tags":["implementation"],"code":"import java.util.Scanner;\n\n\n\npublic class App {\n\n private static Scanner fs;\n\n\n\n public static void solve() {\n\n int a=fs.nextInt();\n\n int b=fs.nextInt();\n\n int x=fs.nextInt();\n\n int y=fs.nextInt();\n\n\n\n int ans=0;\n\n ans=Math.max(x*b,(a-x-1)*b);\n\n ans=Math.max(ans,Math.max(y*a,(b-y-1)*a));\n\n\n\n System.out.println(ans); \n\n }\n\n\n\n public static void main(String[] args) {\n\n fs = new Scanner(System.in);\n\n int t=fs.nextInt();\n\n\n\n while (t>0) {\n\n solve();\n\n t--;\n\n }\n\n\n\n fs.close();\n\n }\n\n}\n\n","language":"java"} -{"contest_id":"1304","problem_id":"F1","statement":"F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1\u2264n\u2264501\u2264n\u226450, 1\u2264m\u22642\u22c51041\u2264m\u22642\u22c5104, 1\u2264k\u2264min(m,20)1\u2264k\u2264min(m,20)) \u2013 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 \u2013 the maximum number of animals that can be observed.ExamplesInputCopy4 5 2\n0 2 1 1 0\n0 0 3 1 2\n1 0 4 3 1\n3 3 0 0 4\nOutputCopy25\nInputCopy3 3 1\n1 2 3\n4 5 6\n7 8 9\nOutputCopy31\nInputCopy3 3 2\n1 2 3\n4 5 6\n7 8 9\nOutputCopy44\nInputCopy3 3 3\n1 2 3\n4 5 6\n7 8 9\nOutputCopy45\nNoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: ","tags":["data structures","dp"],"code":"\/\/package round620;\n\nimport java.io.ByteArrayInputStream;\n\nimport java.io.IOException;\n\nimport java.io.InputStream;\n\nimport java.io.PrintWriter;\n\nimport java.util.ArrayDeque;\n\nimport java.util.Arrays;\n\nimport java.util.Deque;\n\nimport java.util.InputMismatchException;\n\n\n\npublic class F2 {\n\n\tInputStream is;\n\n\tPrintWriter out;\n\n\tString INPUT = \"\";\n\n\t\n\n\tvoid solve()\n\n\t{\n\n\t\tint n = ni(), m = ni(), K = ni();\n\n\t\tint[][] a = new int[n][];\n\n\t\tfor(int i = 0;i < n;i++){\n\n\t\t\ta[i] = na(m);\n\n\t\t}\n\n\t\t\n\n\t\tlong[][] cum = new long[n][m+1];\n\n\t\tfor(int i = 0;i < n;i++){\n\n\t\t\tfor(int j = 0;j < m;j++){\n\n\t\t\t\tcum[i][j+1] = cum[i][j] + a[i][j];\n\n\t\t\t}\n\n\t\t}\n\n\t\t\n\n\t\tlong[][] rcum = new long[n][m+1];\n\n\t\tfor(int i = 0;i < n;i++){\n\n\t\t\tfor(int j = 0;j < m;j++){\n\n\t\t\t\trcum[i][j+1] = rcum[i][j] + a[i][m-1-j];\n\n\t\t\t}\n\n\t\t}\n\n\t\t\n\n\t\tlong[] dp = new long[m-K+1];\n\n\t\tfor(int i = 0;i < m-K+1;i++){\n\n\t\t\tdp[i] = cum[0][i+K] - cum[0][i];\n\n\t\t}\n\n\t\tfor(int i = 1;i < n;i++){\n\n\t\t\tdp = trans(dp, cum[i], rcum[i] ,K);\n\n\t\t}\n\n\t\tlong ans = 0;\n\n\t\tfor(long v : dp){\n\n\t\t\tans = Math.max(ans, v);\n\n\t\t}\n\n\t\tout.println(ans);\n\n\t}\n\n\t\n\n\tlong[] trans(long[] dp, long[] cum, long[] rcum, int K)\n\n\t{\n\n\t\tint n = cum.length-1;\n\n\t\tfor(int i = 0;i < n-K+1;i++){\n\n\t\t\tdp[i] += cum[i+K] - cum[i];\n\n\t\t}\n\n\/\/\t\ttr(dp, cum, rcum);\n\n\t\t\n\n\t\tlong[] ndp = new long[n-K+1];\n\n\t\tArrays.fill(ndp, Long.MIN_VALUE \/ 2);\n\n\t\t\n\n\t\t\/\/ 2321\n\n\t\t\/\/ 000346\n\n\t\t\n\n\t\tgo(ndp, dp, cum, K);\n\n\t\t\n\n\t\trev_(ndp);\n\n\t\trev_(dp);\n\n\t\tgo(ndp, dp, rcum, K);\n\n\t\t\n\n\t\trev_(ndp);\n\n\/\/\t\ttr(ndp);\n\n\t\treturn ndp;\n\n\t}\n\n\t\n\n\tpublic static long[] rev_(long[] a)\n\n\t{\n\n\t\tfor(int i = 0, j = a.length-1;i < j;i++,j--){\n\n\t\t\tlong c = a[i]; a[i] = a[j]; a[j] = c;\n\n\t\t}\n\n\t\treturn a;\n\n\t}\n\n\t\n\n\n\n\t\n\n\tvoid go(long[] ndp, long[] dp, long[] cum, int K)\n\n\t{\n\n\t\tint n = cum.length-1;\n\n\t\tlong flatmax = Long.MIN_VALUE \/ 2;\n\n\t\tDeque nonflat = new ArrayDeque<>();\n\n\t\tfor(int i = 0;i < n-K+1;i++){\n\n\t\t\twhile(!nonflat.isEmpty() && nonflat.peekLast()[1] < dp[i]-cum[i+K]){\n\n\t\t\t\tnonflat.pollLast();\n\n\t\t\t}\n\n\t\t\tnonflat.add(new long[]{i, dp[i]-cum[i+K]});\n\n\t\t\twhile(!nonflat.isEmpty() && nonflat.peekFirst()[0] < i-K){\n\n\t\t\t\tnonflat.pollFirst();\n\n\t\t\t}\n\n\t\t\t\n\n\t\t\tif(i-K >= 0){\n\n\t\t\t\tflatmax = Math.max(flatmax, dp[i-K]);\n\n\t\t\t}\n\n\/\/\t\t\ttr(flatmax, nonflat.peekFirst());\n\n\t\t\t\n\n\t\t\tndp[i] = Math.max(ndp[i], flatmax + cum[i+K] - cum[i]);\n\n\t\t\tif(!nonflat.isEmpty()){\n\n\t\t\t\tndp[i] = Math.max(ndp[i], nonflat.peekFirst()[1] + cum[i] + cum[i+K] - cum[i]);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t\n\n\tvoid run() throws Exception\n\n\t{\n\n\t\tis = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());\n\n\t\tout = new PrintWriter(System.out);\n\n\t\t\n\n\t\tlong s = System.currentTimeMillis();\n\n\t\tsolve();\n\n\t\tout.flush();\n\n\t\ttr(System.currentTimeMillis()-s+\"ms\");\n\n\t}\n\n\t\n\n\tpublic static void main(String[] args) throws Exception { new F2().run(); }\n\n\t\n\n\tprivate byte[] inbuf = new byte[1024];\n\n\tpublic int lenbuf = 0, ptrbuf = 0;\n\n\t\n\n\tprivate int readByte()\n\n\t{\n\n\t\tif(lenbuf == -1)throw new InputMismatchException();\n\n\t\tif(ptrbuf >= lenbuf){\n\n\t\t\tptrbuf = 0;\n\n\t\t\ttry { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }\n\n\t\t\tif(lenbuf <= 0)return -1;\n\n\t\t}\n\n\t\treturn inbuf[ptrbuf++];\n\n\t}\n\n\t\n\n\tprivate boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }\n\n\tprivate int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }\n\n\t\n\n\tprivate double nd() { return Double.parseDouble(ns()); }\n\n\tprivate char nc() { return (char)skip(); }\n\n\t\n\n\tprivate String ns()\n\n\t{\n\n\t\tint b = skip();\n\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\twhile(!(isSpaceChar(b))){ \/\/ when nextLine, (isSpaceChar(b) && b != ' ')\n\n\t\t\tsb.appendCodePoint(b);\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t\treturn sb.toString();\n\n\t}\n\n\t\n\n\tprivate char[] ns(int n)\n\n\t{\n\n\t\tchar[] buf = new char[n];\n\n\t\tint b = skip(), p = 0;\n\n\t\twhile(p < n && !(isSpaceChar(b))){\n\n\t\t\tbuf[p++] = (char)b;\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t\treturn n == p ? buf : Arrays.copyOf(buf, p);\n\n\t}\n\n\t\n\n\tprivate char[][] nm(int n, int m)\n\n\t{\n\n\t\tchar[][] map = new char[n][];\n\n\t\tfor(int i = 0;i < n;i++)map[i] = ns(m);\n\n\t\treturn map;\n\n\t}\n\n\t\n\n\tprivate int[] na(int n)\n\n\t{\n\n\t\tint[] a = new int[n];\n\n\t\tfor(int i = 0;i < n;i++)a[i] = ni();\n\n\t\treturn a;\n\n\t}\n\n\t\n\n\tprivate int ni()\n\n\t{\n\n\t\tint num = 0, b;\n\n\t\tboolean minus = false;\n\n\t\twhile((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));\n\n\t\tif(b == '-'){\n\n\t\t\tminus = true;\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t\t\n\n\t\twhile(true){\n\n\t\t\tif(b >= '0' && b <= '9'){\n\n\t\t\t\tnum = num * 10 + (b - '0');\n\n\t\t\t}else{\n\n\t\t\t\treturn minus ? -num : num;\n\n\t\t\t}\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t}\n\n\t\n\n\tprivate long nl()\n\n\t{\n\n\t\tlong num = 0;\n\n\t\tint b;\n\n\t\tboolean minus = false;\n\n\t\twhile((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));\n\n\t\tif(b == '-'){\n\n\t\t\tminus = true;\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t\t\n\n\t\twhile(true){\n\n\t\t\tif(b >= '0' && b <= '9'){\n\n\t\t\t\tnum = num * 10 + (b - '0');\n\n\t\t\t}else{\n\n\t\t\t\treturn minus ? -num : num;\n\n\t\t\t}\n\n\t\t\tb = readByte();\n\n\t\t}\n\n\t}\n\n\t\n\n\tprivate boolean oj = System.getProperty(\"ONLINE_JUDGE\") != null;\n\n\tprivate void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }\n\n}\n\n","language":"java"} -{"contest_id":"1290","problem_id":"A","statement":"A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n\u22121n\u22121 friends have found an array of integers a1,a2,\u2026,ana1,a2,\u2026,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\u2264t\u226410001\u2264t\u22641000) \u00a0\u2014 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\u2264m\u2264n\u226435001\u2264m\u2264n\u22643500, 0\u2264k\u2264n\u221210\u2264k\u2264n\u22121) \u00a0\u2014 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,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109) \u00a0\u2014 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\n6 4 2\n2 9 2 3 8 5\n4 4 1\n2 13 60 4\n4 1 3\n1 2 2 1\n2 2 0\n1 2\nOutputCopy8\n4\n1\n1\nNoteIn 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.","tags":["brute force","data structures","implementation"],"code":"import java.util.*;\n\n\/\/ import java.lang.*;\n\nimport java.io.*;\n\n\n\n\/\/ THIS TEMPLATE MADE BY AKSH BANSAL.\n\n\n\npublic class Solution {\n\n static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public FastReader() {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n\n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n\n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n String nextLine() {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n private static boolean[] isPrime;\n\n private static void primes(){\n\n int num = (int)1e6; \/\/ PRIMES FROM 1 TO NUM\n\n isPrime = new boolean[num];\n\n \n\n for (int i = 2; i< isPrime.length; i++) {\n\n isPrime[i] = true;\n\n }\n\n for (int i = 2; i< Math.sqrt(num); i++) {\n\n if(isPrime[i] == true) {\n\n for(int j = (i*i); j arr=new ArrayList<>();\n\n for(int i=0;i arr=new ArrayList<>();\n\n for(int i=0;i[] adj;\n\n \/\/ static void getAdj(int n,int q, FastReader sc){\n\n \/\/ adj = new ArrayList[n+1];\n\n \/\/ for(int i=1;i<=n;i++){\n\n \/\/ adj[i] = new ArrayList<>();\n\n \/\/ }\n\n \/\/ for(int i=0;i 0) {\n\n int n= sc.nextInt();\n\n int m= sc.nextInt();\n\n int k= sc.nextInt();\n\n int[] arr =new int[n];\n\n for(int i=0;i=m-1){\n\n int max = 0;\n\n for(int i=0;i=n-m;i--){\n\n max = Math.max(max, arr[i]);\n\n }\n\n return max;\n\n }\n\n else{\n\n int best = -1;\n\n for(int kk=0;kk<=k;kk++){\n\n int min =Integer.MAX_VALUE; \n\n for(int i=0;iak+1>\u2026>anak>ak+1>\u2026>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1\u2264i\u2264n1\u2264i\u2264n) such that ai>0ai>0 and assign ai:=ai\u22121ai:=ai\u22121.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u226415\u00a00001\u2264t\u226415\u00a0000) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22643\u22c51051\u2264n\u22643\u22c5105).The second line of each test case contains a sequence of nn non-negative integers a1,\u2026,ana1,\u2026,an (0\u2264ai\u22641090\u2264ai\u2264109).It is guaranteed that the sum of nn over all test cases does not exceed 3\u22c51053\u22c5105.OutputFor each test case, output a single line containing \"Yes\" (without quotes) if it's possible to make the given array sharpened using the described operations, or \"No\" (without quotes) otherwise.ExampleInputCopy10\n1\n248618\n3\n12 10 8\n6\n100 11 15 9 7 8\n4\n0 1 1 0\n2\n0 0\n2\n0 1\n2\n1 0\n2\n1 1\n3\n0 1 0\n3\n1 0 1\nOutputCopyYes\nYes\nYes\nNo\nNo\nYes\nYes\nYes\nYes\nNo\nNoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.","tags":["greedy","implementation"],"code":"import java.io.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.io.PrintWriter;\n\n\n\npublic class ArraySharpening {\n\n\n\n public static void main(String[] args) throws IOException {\n\n BufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\n PrintWriter pr=new PrintWriter(System.out);\n\n int t=Integer.parseInt(br.readLine());\n\n while(t!=0){\n\n solve(br,pr);\n\n t--;\n\n }\n\n pr.flush();\n\n pr.close();\n\n }\n\n\n\n public static void solve(BufferedReader br,PrintWriter pr) throws IOException{\n\n int n=Integer.parseInt(br.readLine());\n\n int[] nums=new int[n];\n\n String[] temp=br.readLine().split(\" \");\n\n for(int i=0;i=i){\n\n canIncreaseLeft[i]=true;\n\n }\n\n else{\n\n canIncreaseLeft[i]=false;\n\n }\n\n }\n\n boolean[] canDecreaseRight=new boolean[n];\n\n canDecreaseRight[n-1]=true;\n\n for(int i=n-2;i>=0;i--){\n\n if(canDecreaseRight[i+1]==false){\n\n canDecreaseRight[i]=false;\n\n continue;\n\n }\n\n if(nums[i]>=n-1-i){\n\n canDecreaseRight[i]=true;\n\n }\n\n else{\n\n canDecreaseRight[i]=false;\n\n }\n\n }\n\n if(canDecreaseRight[0]||canIncreaseLeft[n-1]){\n\n pr.println(\"Yes\");\n\n return;\n\n }\n\n for(int i=1;i max) max = x[i]; return max;}\n\n static long maxof(long a, long b, long c) {return max(a, max(b, c));}\n\n 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;}\n\n 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;}\n\n 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;}\n\n static int fli(double d) {return (int) d;}\n\n static int cei(double d) {return (int) ceil(d);}\n\n static long fll(double d) {return (long) d;}\n\n static long cel(double d) {return (long) ceil(d);}\n\n static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}\n\n static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}\n\n static int lcm(int a, int b) {return a * b \/ gcf(a, b);}\n\n static long lcm(long a, long b) {return a * b \/ gcf(a, b);}\n\n static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}\n\n static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}\n\n \/\/ array util\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n static void rsort(int[] a) {shuffle(a); sort(a);}\n\n static void rsort(long[] a) {shuffle(a); sort(a);}\n\n static void rsort(double[] a) {shuffle(a); sort(a);}\n\n 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;}\n\n 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;}\n\n 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;}\n\n 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;}\n\n \/\/ graph util\n\n static List> g(int n) {List> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}\n\n static List> sg(int n) {List> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}\n\n static void c(List> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}\n\n static void cto(List> g, int u, int v) {g.get(u).add(v);}\n\n static void dc(List> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}\n\n static void dcto(List> g, int u, int v) {g.get(u).remove(v);}\n\n \/\/ input\n\n static void r() throws IOException {input = new StringTokenizer(rline());}\n\n static int ri() throws IOException {return Integer.parseInt(rline());}\n\n static long rl() throws IOException {return Long.parseLong(rline());}\n\n static double rd() throws IOException {return Double.parseDouble(rline());}\n\n 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;}\n\n 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;}\n\n 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;}\n\n 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;}\n\n static char[] rcha() throws IOException {return rline().toCharArray();}\n\n static String rline() throws IOException {return __in.readLine();}\n\n static String n() {return input.nextToken();}\n\n static int rni() throws IOException {r(); return ni();}\n\n static int ni() {return Integer.parseInt(n());}\n\n static long rnl() throws IOException {r(); return nl();}\n\n static long nl() {return Long.parseLong(n());}\n\n static double rnd() throws IOException {r(); return nd();}\n\n static double nd() {return Double.parseDouble(n());}\n\n static List> rg(int n, int m) throws IOException {List> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}\n\n static void rg(List> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}\n\n static List> rdg(int n, int m) throws IOException {List> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}\n\n static void rdg(List> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}\n\n static List> rsg(int n, int m) throws IOException {List> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}\n\n static void rsg(List> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}\n\n static List> rdsg(int n, int m) throws IOException {List> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}\n\n static void rdsg(List> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}\n\n \/\/ output\n\n static void pr(int i) {__out.print(i);}\n\n static void prln(int i) {__out.println(i);}\n\n static void pr(long l) {__out.print(l);}\n\n static void prln(long l) {__out.println(l);}\n\n static void pr(double d) {__out.print(d);}\n\n static void prln(double d) {__out.println(d);}\n\n static void pr(char c) {__out.print(c);}\n\n static void prln(char c) {__out.println(c);}\n\n static void pr(char[] s) {__out.print(new String(s));}\n\n static void prln(char[] s) {__out.println(new String(s));}\n\n static void pr(String s) {__out.print(s);}\n\n static void prln(String s) {__out.println(s);}\n\n static void pr(Object o) {__out.print(o);}\n\n static void prln(Object o) {__out.println(o);}\n\n static void prln() {__out.println();}\n\n static void pryes() {prln(\"yes\");}\n\n static void pry() {prln(\"Yes\");}\n\n static void prY() {prln(\"YES\");}\n\n static void prno() {prln(\"no\");}\n\n static void prn() {prln(\"No\");}\n\n static void prN() {prln(\"NO\");}\n\n static void pryesno(boolean b) {prln(b ? \"yes\" : \"no\");};\n\n static void pryn(boolean b) {prln(b ? \"Yes\" : \"No\");}\n\n static void prYN(boolean b) {prln(b ? \"YES\" : \"NO\");}\n\n 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();}\n\n 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();}\n\n 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();}\n\n static void prln(Collection c) {int n = c.size() - 1; Iterator iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}\n\n static void h() {prln(\"hlfd\"); flush();}\n\n static void flush() {__out.flush();}\n\n static void close() {__out.close();}\n\n}","language":"java"} -{"contest_id":"1324","problem_id":"E","statement":"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\u22121ai\u22121 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\u2264n\u22642000,3\u2264h\u22642000,0\u2264l\u2264r= 0; i--) {\n\n\t\t for (int j = h; j >= 0; j--) {\n\n\t\t\tint d1 = (j + a[i]) % h;\n\n\t\t\tint d2 = (j + (a[i] - 1)) % h;\n\n\t\t\tif (d1 >= l && d1 <= r) {\n\n\t\t\t dp[i][j] = max(dp[i][j], 1 + dp[i + 1][d1]);\n\n\t\t\t} else dp[i][j] = max(dp[i][j], dp[i + 1][d1]);\n\n\t\t\tif (d2 >= l && d2 <= r) {\n\n\t\t\t dp[i][j] = max(dp[i][j], 1 + dp[i + 1][d2]);\n\n\t\t\t} else dp[i][j] = max(dp[i][j], dp[i + 1][d2]);\n\n\t\t }\n\n\t }\n\n\n\n\t System.out.println(dp[0][0]);\n\n\n\n }\n\n\n\n void sort(int[] a) {\n\n\t ArrayList l = new ArrayList<>();\n\n\t for (int i : a) l.add(i);\n\n\t Collections.sort(l);\n\n\t for (int i = 0; i < a.length; i++) a[i] = l.get(i);\n\n }\n\n\n\n public static void main(String[] args) {\n\n\t Main obj = new Main();\n\n\t int c = 1;\n\n\t for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve();\n\n\t obj.solve();\n\n\t obj.flush();\n\n }\n\n\n\n static class FastScanner {\n\n\t BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n\t StringTokenizer st = new StringTokenizer(\"\");\n\n\n\n\t String next() {\n\n\t\t while (!st.hasMoreTokens()) try {\n\n\t\t\tst = new StringTokenizer(br.readLine());\n\n\t\t } catch (IOException e) {\n\n\t\t\te.printStackTrace();\n\n\t\t }\n\n\t\t return st.nextToken();\n\n\t }\n\n\n\n\t int nextInt() { return Integer.parseInt(next()); }\n\n\n\n\t int[] readIntArray(int n) {\n\n\t\t int[] a = new int[n];\n\n\t\t for (int i = 0; i < n; i++) a[i] = nextInt();\n\n\t\t return a;\n\n\t }\n\n\n\n\t char[] readCharArray(int n) {\n\n\t\t char a[] = new char[n];\n\n\t\t String s = sc.next();\n\n\t\t for (int i = 0; i < n; i++) { a[i] = s.charAt(i); }\n\n\t\t return a;\n\n\t }\n\n\n\n\t long[] readLongArray(int n) {\n\n\t\t long[] a = new long[n];\n\n\t\t for (int i = 0; i < n; i++) a[i] = nextLong();\n\n\t\t return a;\n\n\t }\n\n\n\n\t long nextLong() { return Long.parseLong(next()); }\n\n }\n\n\n\n final int ima = Integer.MAX_VALUE;\n\n final int imi = Integer.MIN_VALUE;\n\n final long lma = Long.MAX_VALUE;\n\n final long lmi = Long.MIN_VALUE;\n\n static final long mod = (long) 1e9 + 7;\n\n private static final FastScanner sc = new FastScanner();\n\n private PrintWriter out = new PrintWriter(System.out);\n\n}","language":"java"} -{"contest_id":"1301","problem_id":"C","statement":"C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols \"0\" and \"1\"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to \"1\".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1\u2264l\u2264r\u2264|s|1\u2264l\u2264r\u2264|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,\u2026,srsl,sl+1,\u2026,sr is equal to \"1\". For example, if s=s=\"01010\" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to \"1\", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u22641051\u2264t\u2264105) \u00a0\u2014 the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1\u2264n\u22641091\u2264n\u2264109, 0\u2264m\u2264n0\u2264m\u2264n)\u00a0\u2014 the length of the string and the number of symbols equal to \"1\" in it.OutputFor every test case print one integer number\u00a0\u2014 the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to \"1\".ExampleInputCopy5\n3 1\n3 2\n3 3\n4 0\n5 2\nOutputCopy4\n5\n6\n0\n12\nNoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to \"1\". These strings are: s1=s1=\"100\", s2=s2=\"010\", s3=s3=\"001\". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is \"101\".In the third test case, the string ss with the maximum value is \"111\".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to \"1\" is \"0000\" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is \"01010\" and it is described as an example in the problem statement.","tags":["binary search","combinatorics","greedy","math","strings"],"code":"\n\nimport java.awt.MultipleGradientPaint.ColorSpaceType;\n\nimport java.io.*;\n\nimport java.sql.PreparedStatement;\n\nimport java.util.*;\n\n\n\n\n\n\n\n\n\n\n\npublic class cp {\n\n\tstatic int mod=998244353;\/\/(int)1e9+7;\n\n\t\n\n\/\/\tstatic Reader sc=new Reader();\n\n\tstatic FastReader sc=new FastReader(System.in);\n\n\tstatic int[] sp;\n\n\tstatic int size=(int)1e6;\n\n\tstatic int[] arInt;\n\n\tstatic long[] arLong;\n\n\tstatic long ans;\n\n\tpublic static void main(String[] args) throws IOException { \n\n\t\tlong tc=sc.nextLong();\n\n\/\/\t\tScanner sc=new Scanner(System.in);\n\n\/\/\t\t\tint tc=1;\n\n\/\/\t\t\tprint_int(pre);\n\n\/\/\t\t\tprimeSet=new HashSet<>();\n\n\/\/\t\t\tprimeCnt=new int[(int)1e9];\n\n\/\/\t\t\tsieveOfEratosthenes((int)1e9);\n\n\/\/\t\t\tfactorial(mod);\n\n\/\/\t\t\tInverseofNumber(mod);\n\n\/\/\t\t\tInverseofFactorial(mod);\n\n\t\t\t\n\n\t\t\twhile(tc-->0)\n\n\t\t\t{\n\n\t\t\t\t\n\n\t\t\t\tlong n=sc.nextLong();\n\n\t\t\t\tlong m=sc.nextLong();\n\n\t\t\t\tlong ans=n*(n+1)\/2;\n\n\t\t\t\tlong zero=(n-m);\n\n\t\t\t\tlong grps=m+1;\n\n\t\t\t\tlong k=zero\/grps;\n\n\t\t\t\tans-=(k*(k+1)\/2)*grps;\n\n\t\t\t\tans-=(k+1)*(zero%grps);\n\n\t\t\t\tout.println(ans);\n\n\t\t\t\t\n\n\t\t\t}\n\n\/\/\t\t\tSystem.out.flush();\n\n\t\t\tout.flush();\n\n\t\t\tout.close();\n\n\t\t\tSystem.gc();\n\n\t\n\n\t}\n\n\t\n\n\t\n\n\t\n\n\n\n\n\n\t\/*\n\n\t ...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...\n\n *\/\n\n\t\n\n\t\n\n\t\n\n\t\n\n\t\n\n\tstatic class Node{\n\n\t\tint a;\n\n\t\tArrayList adj;\n\n\t\tpublic Node(int a) {\n\n\t\t\tthis.a=a;\n\n\t\t\tthis.adj=new ArrayList<>();\n\n\t\t}\n\n\t\t\n\n\t}\n\n\t\n\n\tstatic void dijkstra(Node[] g,int dist[],int parent[],int src)\n\n\t{\n\n\t\tArrays.fill(dist, int_max);\n\n\t\tArrays.fill(parent, -1);\n\n\t\tboolean vis[]=new boolean[dist.length];\n\n\/\/\t\tvis[1]=true;\n\n\t\tPriorityQueue q=new PriorityQueue<>();\n\n\t\tq.add(new Pair(1, 0));\n\n\t\tdist[1]=0;\n\n\t\t\n\n\t\twhile(!q.isEmpty())\n\n\t\t{\n\n\t\t\tPair curr=q.poll();\n\n\t\t\tvis[curr.x]=true;\n\n\t\t\tfor(Pair edge:g[curr.x].adj)\n\n\t\t\t{\n\n\t\t\t\tif (vis[edge.x]) {\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\t}\n\n\t\t\t\tif (dist[edge.x]>dist[curr.x]+edge.y) {\n\n\t\t\t\t\tdist[edge.x]=dist[curr.x]+edge.y;\n\n\t\t\t\t\tparent[edge.x]=curr.x;\n\n\t\t\t\t\tq.add(new Pair(edge.x, dist[edge.x]));\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\t\n\n\t\t\n\n\t\t\n\n\t}\n\n\t\n\n\tstatic void mapping(int a[])\n\n\t{\n\n\t\tPair[] temp=new Pair[a.length];\n\n\t\tfor (int i = 0; i < temp.length; i++) {\n\n\t\t\ttemp[i]=new Pair(a[i], i);\n\n\t\t}\n\n\t\tArrays.sort(temp);\n\n\t\tint k=0;\n\n\t\tfor (int i = 0; i < temp.length; i++) {\n\n\t\t\ta[temp[i].y]=k++;\n\n\t\t}\n\n\t\t\n\n\t}\n\n\t\n\n\tstatic boolean palin(String s)\n\n\t{\n\n\t\tfor(int i=0;i{\n\n\t\tint x;\n\n\t\tint y;\n\n\t\tint sec;\n\n\t\tpublic temp(int x,int y,int l) {\n\n\t\t\t\/\/ TODO Auto-generated constructor stub\n\n\t\t\tthis.x=x;\n\n\t\t\tthis.y=y;\n\n\t\t\tthis.sec=l;\n\n\t\t}\n\n\t\t@Override\n\n\t\tpublic int compareTo(cp.temp o) {\n\n\t\t\t\/\/ TODO Auto-generated method stub\n\n\t\t\treturn this.sec-o.sec;\n\n\t\t}\n\n\t}\n\n\t\n\n\t\n\n\/\/\tstatic class Node{\n\n\/\/\t\tint x;\n\n\/\/\t\tint y;\n\n\/\/\t\tArrayList edges;\n\n\/\/\t\tpublic Node(int x,int y) {\n\n\/\/\t\t\t\/\/ TODO Auto-generated constructor stub\n\n\/\/\t\t\tthis.x=x;\n\n\/\/\t\t\tthis.y=y;\n\n\/\/\t\t\tthis.edges=new ArrayList<>();\n\n\/\/\t\t}\n\n\/\/\t}\n\n\t\n\n\t\n\n\tstatic int lis(int arr[],int n)\n\n\t{\n\n\t\tint ans=0;\n\n\t\t\n\n\t\tint dp[]=new int[n+1];\n\n\t\tArrays.fill(dp, int_max);\n\n\t\tdp[0]=int_min;\n\n\t\tfor(int i=0;i caves,int k)\n\n\t{\n\n\t\tfor(Pair each:caves)\n\n\t\t{\n\n\t\t\tif(k<=each.x)\n\n\t\t\t\treturn false;\n\n\t\t\tk+=each.y;\n\n\t\t}\n\n\t\t\n\n\t\treturn true;\n\n\t}\n\n\t\n\n\tstatic String revString(String s)\n\n\t{\n\n\t\tchar arr[]=s.toCharArray();\n\n\t\tint n=s.length();\n\n\t\tfor(int i=0;i0)\n\n\t\t{\n\n\t\t\tif((n&1)==1)\n\n\t\t\t{\n\n\t\t\t\tcnt++;\n\n\t\t\t\t\n\n\t\t\t}\n\n\t\t\tn=n>>1;\n\n\t\t\t\n\n\t\t}\n\n\t\t\n\n\t\treturn cnt;\n\n\t}\n\n\t\n\n\t\n\n\t\n\n\t\n\n\tstatic boolean isPowerOfTwo(int n)\n\n {\n\n return (int)(Math.ceil((Math.log(n) \/ Math.log(2))))\n\n == (int)(Math.floor(((Math.log(n) \/ Math.log(2)))));\n\n }\n\n\t\n\n\t\n\n\t\n\n\t\n\n\tstatic void arrInt(int n) throws IOException\n\n\t{\n\n\t\tarInt=new int[n];\n\n\t\tfor (int i = 0; i < arInt.length; i++) {\n\n\t\t\tarInt[i]=sc.nextInt();\n\n\t\t}\n\n\t}\n\n\t\n\n\tstatic void arrLong(int n) throws IOException\n\n\t{\n\n\t\tarLong=new long[n];\n\n\t\tfor (int i = 0; i < arLong.length; i++) {\n\n\t\t\tarLong[i]=sc.nextLong();\n\n\t\t}\n\n\t}\n\n\t\n\n\t\n\n\t\n\n\tstatic ArrayList add(int id,int c)\n\n\t{\n\n\t\tArrayList newArr=new ArrayList<>();\n\n\t\tfor(int i=0;i= y\n\n static int upper(ArrayList arr, int n, int x)\n\n {\n\n \tint l = 0, h = n - 1;\n\n while (h-l>1)\n\n {\n\n int mid = (l + h) \/ 2;\n\n if (arr.get(mid) <= x)\n\n l=mid+1;\n\n else\n\n {\n\n \th=mid;\n\n }\n\n }\n\n if(arr.get(l)>x)\n\n {\n\n \treturn l;\n\n }\n\n if(arr.get(h)>x)\n\n \treturn h;\n\n return -1;\n\n }\n\n static int upper(ArrayList arr, int n, long x)\n\n {\n\n \tint l = 0, h = n - 1;\n\n \twhile (h-l>1)\n\n \t{\n\n \t\tint mid = (l + h) \/ 2;\n\n \t\tif (arr.get(mid) <= x)\n\n \t\t\tl=mid+1;\n\n \t\telse\n\n \t\t{\n\n \t\t\th=mid;\n\n \t\t}\n\n \t}\n\n \tif(arr.get(l)>x)\n\n \t{\n\n \t\treturn l;\n\n \t}\n\n \tif(arr.get(h)>x)\n\n \t\treturn h;\n\n \treturn -1;\n\n }\n\n \n\n\t\n\n\t\n\n\tstatic int lower(ArrayList arr, int n, int x)\n\n {\n\n int l = 0, h = n - 1;\n\n while (h-l>1)\n\n {\n\n int mid = (l + h) \/ 2;\n\n if (arr.get(mid) < x)\n\n l=mid+1;\n\n else\n\n {\n\n \th=mid;\n\n }\n\n }\n\n if(arr.get(l)>=x)\n\n {\n\n \treturn l;\n\n }\n\n if(arr.get(h)>=x)\n\n \treturn h;\n\n return -1;\n\n }\n\n \n\n\t\n\n\t\n\n\t\n\n\t\n\n\tstatic int N = (int)2e5+5; \n\n\t \n\n\t\/\/ Array to store inverse of 1 to N\n\n\tstatic long[] factorialNumInverse = new long[N + 1];\n\n\t \n\n\t\/\/ Array to precompute inverse of 1! to N!\n\n\tstatic long[] naturalNumInverse = new long[N + 1];\n\n\t \n\n\t\/\/ Array to store factorial of first N numbers\n\n\tstatic long[] fact = new long[N + 1];\n\n\t \n\n\t\/\/ Function to precompute inverse of numbers\n\n\tpublic static void InverseofNumber(int p)\n\n\t{\n\n\t naturalNumInverse[0] = naturalNumInverse[1] = 1;\n\n\t \n\n\t for(int i = 2; i <= N; i++)\n\n\t naturalNumInverse[i] = naturalNumInverse[p % i] *\n\n\t (long)(p - p \/ i) % p;\n\n\t}\n\n\t \n\n\t\/\/ Function to precompute inverse of factorials\n\n\tpublic static void InverseofFactorial(int p)\n\n\t{\n\n\t factorialNumInverse[0] = factorialNumInverse[1] = 1;\n\n\t \n\n\t \/\/ Precompute inverse of natural numbers\n\n\t for(int i = 2; i <= N; i++)\n\n\t factorialNumInverse[i] = (naturalNumInverse[i] *\n\n\t factorialNumInverse[i - 1]) % p;\n\n\t}\n\n\t \n\n\t\/\/ Function to calculate factorial of 1 to N\n\n\tpublic static void factorial(int p)\n\n\t{\n\n\t fact[0] = 1;\n\n\t \n\n\t \/\/ Precompute factorials\n\n\t for(int i = 1; i <= N; i++)\n\n\t {\n\n\t fact[i] = (fact[i - 1] * (long)i) % p;\n\n\t }\n\n\t}\n\n\t \n\n\t\/\/ Function to return nCr % p in O(1) time\n\n\tpublic static long Binomial(int N, int R, int p)\n\n\t{\n\n\t \n\n\t \/\/ n C r = n!*inverse(r!)*inverse((n-r)!)\n\n\t long ans = ((fact[N] * factorialNumInverse[R]) %\n\n\t p * factorialNumInverse[N - R]) % p;\n\n\t \n\n\t return ans;\n\n\t}\n\n\t\n\n\t\n\n\tstatic String tr(String s)\n\n\t{\n\n\t\tint now = 0;\n\n\t\twhile (now + 1 < s.length() && s.charAt(now)== '0')\n\n\t\t\t++now;\n\n\t\treturn s.substring(now);\n\n\t}\n\n\t\n\n\t\n\n\t\n\n\t\n\n\tstatic boolean isPrime(long n)\n\n {\n\n \/\/ Corner cases\n\n if (n <= 1)\n\n return false;\n\n if (n <= 3)\n\n return true;\n\n \n\n \/\/ This is checked so that we can skip\n\n \/\/ middle five numbers in below loop\n\n if (n % 2 == 0 || n % 3 == 0)\n\n return false;\n\n \n\n for (int i = 5; i * i <= n; i = i + 6)\n\n if (n % i == 0 || n % (i + 2) == 0)\n\n return false;\n\n \n\n return true;\n\n }\n\n\t\n\n\t\n\n\tstatic ArrayList commDiv(int a, int b)\n\n {\n\n \/\/ find gcd of a, b\n\n int n = gcd(a, b);\n\n \n\n \/\/ Count divisors of n.\n\n ArrayList Div=new ArrayList<>();\n\n for (int i = 1; i <= Math.sqrt(n); i++) {\n\n \/\/ if 'i' is factor of n\n\n if (n % i == 0) {\n\n \/\/ check if divisors are equal\n\n if (n \/ i == i)\n\n Div.add(i);\n\n else\n\n {\n\n \tDiv.add(i);\n\n \tDiv.add(n\/i);\n\n }\n\n }\n\n }\n\n return Div;\n\n }\n\n\t\n\n\tstatic HashSet factors(int x)\n\n\t{\n\n\t\tHashSet a=new HashSet();\n\n\t\tfor(int i=2;i*i<=x;i++)\n\n\t\t{\n\n\t\t\tif(x%i==0)\n\n\t\t\t{\n\n\t\t\t\ta.add(i);\n\n\t\t\t\ta.add(x\/i);\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn a;\n\n\t}\n\n\tstatic void primeFactors(int n,HashSet factors)\n\n {\n\n \/\/ Print the number of 2s that divide n\n\n while (n%2==0)\n\n {\n\n factors.add(2);\n\n n \/= 2;\n\n }\n\n\n\n \/\/ n must be odd at this point. So we can\n\n \/\/ skip one element (Note i = i +2)\n\n for (int i = 3; i <= Math.sqrt(n); i+= 2)\n\n {\n\n \/\/ While i divides n, print i and divide n\n\n while (n%i == 0)\n\n {\n\n factors.add(i);\n\n n \/= i;\n\n }\n\n }\n\n\n\n \/\/ This condition is to handle the case when\n\n \/\/ n is a prime number greater than 2\n\n if (n > 2)\n\n factors.add(n);\n\n }\n\n\t\t\n\n\t\n\n\n\n\tstatic class Tuple{\n\n\t\tint a;\n\n\t\tint b;\n\n\t\tint c;\n\n\t\tpublic Tuple(int a,int b,int c) {\n\n\t\t\tthis.a=a;\n\n\t\t\tthis.b=b;\n\n\t\t\tthis.c=c;\n\n\t\t}\n\n\t\t\n\n\t}\n\n\n\n\t\/\/function to find prime factors of n\n\n\tstatic HashMap findFactors(long n2)\n\n\t{\n\n\t\tHashMap ans=new HashMap<>();\n\n\t\tif(n2%2==0)\n\n\t\t{\n\n\t\t\tans.put(2L, 0L);\n\n\/\/\t\t\tcnt++;\n\n\t\t\twhile((n2&1)==0)\n\n\t\t\t{\n\n\t\t\t\tn2=n2>>1;\n\n\t\t\t\tans.put(2L, ans.get(2L)+1);\n\n\/\/\t\t\t\t\n\n\t\t\t}\n\n\t\t\t\t\n\n\t\t}\n\n\t\tfor(long i=3;i*i<=n2;i+=2)\n\n\t\t{\n\n\t\t\tif(n2%i==0)\n\n\t\t\t{\n\n\t\t\t\tans.put((long)i, 0L);\n\n\/\/\t\t\t\tcnt++;\n\n\t\t\t\twhile(n2%i==0)\n\n\t\t\t\t{\n\n\t\t\t\t\tn2=n2\/i;\n\n\t\t\t\t\tans.put((long)i, ans.get((long)i)+1);\n\n\t\t\t\t\t\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif(n2!=1)\n\n\t\t{\n\n\t\t\tans.put(n2, ans.getOrDefault(n2, (long) 0)+1);\n\n\t\t\t\n\n\t\t}\n\n\t\t\t\n\n\t\treturn ans;\n\n\t}\n\n\t\n\n\n\n\t\/\/fenwick tree implementaion\n\n\tstatic class fwt\n\n\t{\n\n\t\tint n;\n\n\t\tlong BITree[];\n\n\t\tfwt(int n)\n\n\t\t{\n\n\t\t\tthis.n=n;\n\n\t\t\tBITree=new long[n+1];\n\n\t\t}\n\n\t\t\n\n\t\tfwt(int arr[], int n)\n\n\t\t{\n\n\t\t\tthis.n=n;\n\n\t\t\tBITree=new long[n+1];\n\n\t\t\tfor(int i = 0; i < n; i++)\n\n\t\t\tupdateBIT(n, i, arr[i]);\n\n\t\t }\n\n\t\t\n\n\t\t long getSum(int index)\n\n\t\t {\n\n\t\t long sum = 0;\n\n\t\t index = index + 1;\n\n\t\t while(index>0)\n\n\t\t {\n\n\t\t sum += BITree[index];\n\n\t\t index -= index & (-index);\n\n\t\t }\n\n\t\t return sum;\n\n\t\t }\n\n\t\t void updateBIT(int n, int index,int val)\n\n\t\t {\n\n\t\t index = index + 1;\n\n\t\t while(index <= n)\n\n\t\t {\n\n\t\t\t BITree[index] += val;\n\n\t\t\t index += index & (-index);\n\n\t\t }\n\n\t\t }\n\n\t\t \n\n\t\t long sum(int l, int r) {\n\n\t\t return getSum(r) - getSum(l - 1);\n\n\t\t }\n\n\t\t \n\n\t\t \n\n\t\t void print()\n\n\t\t {\n\n\t\t\t for(int i=0;i primes;\n\n\tstatic HashSet primeSet;\n\n\tstatic boolean prime[];\n\n\tstatic int primeCnt[];\n\n\tstatic void sieveOfEratosthenes(int n)\n\n {\n\n \n\n prime= new boolean[n + 1];\n\n for (int i = 2; i <= n; i++)\n\n prime[i] = true;\n\n \n\n for (int p = 2; p * p <= n; p++)\n\n {\n\n \/\/ If prime[p] is not changed, then it is a\n\n \/\/ prime\n\n if (prime[p] == true)\n\n {\n\n \/\/ Update all multiples of p\n\n for (int i = p * p; i <= n; i += p)\n\n prime[i] = false;\n\n }\n\n }\n\n \n\n \/\/ Print all prime numbers\n\n for (int i = 2; i <= n; i++)\n\n {\n\n if (prime[i] == true)\n\n primeCnt[i]=primeCnt[i-1]+1;\n\n }\n\n }\n\n\t\n\n\t\n\n\t\n\n\tstatic long mod(long a, long b) {\n\n\t\t long c = a % b;\n\n\t\t return (c < 0) ? c + b : c;\n\n\t\t}\n\n\t\n\n\tstatic void swap(long arr[],int i,int j)\n\n\t{\n\n\t\tlong temp=arr[i];\n\n\t\tarr[i]=arr[j];\n\n\t\tarr[j]=temp;\n\n\t}\n\n\n\n\t\n\n\t\n\n\tstatic boolean util(int a,int b,int c)\n\n\t{\n\n\t\tif(b>a)util(b, a, c);\n\n\t\t\n\n\t\twhile(c>=a)\n\n\t\t{\n\n\t\t\tc-=a;\n\n\t\t\tif(c%b==0)\n\n\t\t\t\treturn true;\n\n\t\t}\n\n\t\t\n\n\t\t\n\n\t\treturn (c%b==0);\n\n\t}\n\n\t\n\n\t\n\n\t\n\n\tstatic void flag(boolean flag)\n\n\t {\n\n\t out.println(flag ? \"YES\" : \"NO\");\n\n\t out.flush();\n\n\t }\n\n\t \n\n\t\n\n\tstatic void print(int a[])\n\n\t {\n\n\t int n=a.length;\n\n\t for(int i=0;i al)\n\n\t {\n\n\t int si=al.size();\n\n\t for(int i=0;i al)\n\n\t {\n\n\t int si=al.size();\n\n\t for(int i=0;i>>1;\n\n\t if(a[m]>=x) r=m;\n\n\t else l=m;\n\n\t }\n\n\t return r;\n\n\t}\n\n\t\n\n\t\n\n\tstatic int lowerIndex(int arr[], int n, int x)\n\n {\n\n int l = 0, h = n - 1;\n\n while (l<=h)\n\n {\n\n int mid = (l + h) \/ 2;\n\n if (arr[mid] >= x)\n\n h = mid -1 ;\n\n else\n\n l = mid + 1;\n\n }\n\n return l;\n\n }\n\n\t\n\n\t\n\n\t \/\/ function to find last index <= y\n\n static int upperIndex(int arr[], int n, int y)\n\n {\n\n int l = 0, h = n - 1;\n\n while (l <= h)\n\n {\n\n int mid = (l + h) \/ 2;\n\n if (arr[mid] <= y)\n\n l = mid + 1;\n\n else\n\n h = mid - 1;\n\n }\n\n return h;\n\n }\n\n static int upperIndex(long arr[], int n, long y)\n\n {\n\n \tint l = 0, h = n - 1;\n\n \twhile (l <= h)\n\n \t{\n\n \t\tint mid = (l + h) \/ 2;\n\n \t\tif (arr[mid] <= y)\n\n \t\t\tl = mid + 1;\n\n \t\telse\n\n \t\t\th = mid - 1;\n\n \t}\n\n \treturn h;\n\n }\n\n \n\n\t\n\n\t static int UpperBound(int a[], int x)\n\n\t {\/\/ x is the key or target value\n\n\t int l=-1,r=a.length;\n\n\t while(l+1>>1;\n\n\t if(a[m]<=x) l=m;\n\n\t else r=m;\n\n\t }\n\n\t return l+1;\n\n\t }\n\n\t static int UpperBound(long a[], long x)\n\n\t {\/\/ x is the key or target value\n\n\t\t int l=-1,r=a.length;\n\n\t\t while(l+1>>1;\n\n\t if(a[m]<=x) l=m;\n\n\t else r=m;\n\n\t\t }\n\n\t\t return l+1;\n\n\t }\n\n\t\n\n\t \n\n\t static class DisjointUnionSets\n\n\t {\n\n\t int[] rank, parent;\n\n\t int n;\n\n\t \/\/ Constructor\n\n\t public DisjointUnionSets(int n)\n\n\t {\n\n\t rank = new int[n];\n\n\t parent = new int[n];\n\n\t this.n = n;\n\n\t makeSet();\n\n\t }\n\n\t \/\/ Creates n sets with single item in each\n\n\t void makeSet()\n\n\t {\n\n\t for (int i = 0; i < n; i++)\n\n\t parent[i] = i;\n\n\t }\n\n\t int find(int x)\n\n\t {\n\n\t if (parent[x] != x) {\n\n\t parent[x] = find(parent[x]);\n\n\t }\n\n\t return parent[x];\n\n\t }\n\n\t \/\/ Unites the set that includes x and the set\n\n\t \/\/ that includes x\n\n\t void union(int x, int y)\n\n\t {\n\n\t int xRoot = find(x), yRoot = find(y);\n\n\t if (xRoot == yRoot)\n\n\t return;\n\n\t if (rank[xRoot] < rank[yRoot])\n\n\t parent[xRoot] = yRoot;\n\n\t else if (rank[yRoot] < rank[xRoot])\n\n\t parent[yRoot] = xRoot;\n\n\t else \/\/ if ranks are the same\n\n\t {\n\n\t parent[yRoot] = xRoot;\n\n\t rank[xRoot] = rank[xRoot] + 1;\n\n\t }\n\n\t \n\n\/\/\t if(xRoot!=yRoot)\n\n\/\/\t \tparent[y]=x;\n\n\t }\n\n\t \n\n\t int connectedComponents()\n\n\t {\n\n\t \tint cnt=0;\n\n\t \tfor(int i=0;i list[];\n\n\/\/\t Graph(int v)\n\n\/\/\t {\n\n\/\/\t this.v=v;\n\n\/\/\t list=new ArrayList[v+1];\n\n\/\/\t for(int i=1;i<=v;i++)\n\n\/\/\t list[i]=new ArrayList();\n\n\/\/\t }\n\n\/\/\t void addEdge(int a, int b)\n\n\/\/\t {\n\n\/\/\t this.list[a].add(b);\n\n\/\/\t }\n\n\/\/\t \n\n\/\/\t \n\n\/\/\t \n\n\/\/\t }\n\n\t\n\n\t\n\n\t \n\n\t static class Pair implements Comparable\n\n\t {\n\n\t int x;\n\n\t int y;\n\n\t Pair(int x,int y)\n\n\t {\n\n\t this.x=x;\n\n\t this.y=y;\n\n\t \n\n\t }\n\n\t\t@Override\n\n\t\tpublic int compareTo(Pair o) {\n\n\t\t\t\/\/ TODO Auto-generated method stub\n\n\t\t\treturn this.y-o.y;\n\n\t\t}\n\n\t \n\n\t \n\n\t \n\n\t }\n\n\t static class PairL implements Comparable\n\n\t {\n\n\t\t long x;\n\n\t\t long y;\n\n\t\t PairL(long x,long y)\n\n\t\t {\n\n\t\t\t this.x=x;\n\n\t\t\t this.y=y;\n\n\t\t\t \n\n\t\t }\n\n\t\t @Override\n\n\t\t public int compareTo(PairL o) {\n\n\t\t\t \/\/ TODO Auto-generated method stub\n\n\t\t\t return (this.y>o.y)?1:-1;\n\n\t\t }\n\n\t\t \n\n\t\t \n\n\t\t \n\n\t }\n\n\t \n\n\t \n\n\tstatic long sum_array(int a[])\n\n\t {\n\n\t int n=a.length;\n\n\t long sum=0;\n\n\t for(int i=0;i l=new ArrayList<>();\n\n\t\t\tfor (int i:a) l.add(i);\n\n\t\t\tCollections.sort(l);\n\n\t\t\tfor (int i=0; i l=new ArrayList<>();\n\n\t\t\tfor (long i:a) l.add(i);\n\n\t\t\tCollections.sort(l);\n\n\t\t\tfor (int i=0; i 0)\n\n\t {\n\n\t if ((y & 1) != 0)\n\n\t res = (res * x) % mod;\n\n\t \n\n\t y = y >> 1; \/\/ y = y\/2\n\n\t x = (x * x) % mod;\n\n\t }\n\n\t return res;\n\n\t }\n\n\tstatic int power(int x, int y)\n\n\t{\n\n\t\tint res = 1;\n\n\t\tx = x % mod;\n\n\t\tif (x == 0)\n\n\t\t\treturn 0;\n\n\t\twhile (y > 0)\n\n\t\t{\n\n\t\t\tif ((y & 1) != 0)\n\n\t\t\t\tres = (res * x) % mod;\n\n\t\t\t\n\n\t\t\ty = y >> 1; \/\/ y = y\/2\n\n\t x = (x * x) % mod;\n\n\t\t}\n\n\t\treturn res;\n\n\t}\n\n\tstatic long gcd(long a, long b) \n\n\t { \n\n\t\t\t\n\n\t if (a == 0) \n\n\t return b; \n\n\t \/\/cnt+=a\/b;\n\n\t return gcd(b%a,a); \n\n\t } \n\n\tstatic int gcd(int a, int b) \n\n\t { \n\n\t if (a == 0) \n\n\t return b; \n\n\t \n\n\t return gcd(b%a, a); \n\n\t } \n\n\n\n\t static class FastReader{\n\n\t \n\n\t byte[] buf = new byte[2048];\n\n\t int index, total;\n\n\t InputStream in;\n\n\t \n\n\t FastReader(InputStream is) {\n\n\t in = is;\n\n\t }\n\n\t \n\n\t int scan() throws IOException {\n\n\t if (index >= total) {\n\n\t index = 0;\n\n\t total = in.read(buf);\n\n\t if (total <= 0) {\n\n\t return -1;\n\n\t }\n\n\t }\n\n\t return buf[index++];\n\n\t }\n\n\t \n\n\t String next() throws IOException {\n\n\t int c;\n\n\t for (c = scan(); c <= 32; c = scan());\n\n\t StringBuilder sb = new StringBuilder();\n\n\t for (; c > 32; c = scan()) {\n\n\t sb.append((char) c);\n\n\t }\n\n\t return sb.toString();\n\n\t }\n\n\t \n\n\t int nextInt() throws IOException {\n\n\t int c, val = 0;\n\n\t for (c = scan(); c <= 32; c = scan());\n\n\t boolean neg = c == '-';\n\n\t if (c == '-' || c == '+') {\n\n\t c = scan();\n\n\t }\n\n\t for (; c >= '0' && c <= '9'; c = scan()) {\n\n\t val = (val << 3) + (val << 1) + (c & 15);\n\n\t }\n\n\t return neg ? -val : val;\n\n\t }\n\n\t \n\n\t long nextLong() throws IOException {\n\n\t int c;\n\n\t long val = 0;\n\n\t for (c = scan(); c <= 32; c = scan());\n\n\t boolean neg = c == '-';\n\n\t if (c == '-' || c == '+') {\n\n\t c = scan();\n\n\t }\n\n\t for (; c >= '0' && c <= '9'; c = scan()) {\n\n\t val = (val << 3) + (val << 1) + (c & 15);\n\n\t }\n\n\t return neg ? -val : val;\n\n\t }\n\n\t }\n\n\t \n\n\t static class Reader \n\n\t { \n\n\t final private int BUFFER_SIZE = 1 << 16; \n\n\t private DataInputStream din; \n\n\t private byte[] buffer; \n\n\t private int bufferPointer, bytesRead; \n\n\t \n\n\t public Reader() \n\n\t { \n\n\t din = new DataInputStream(System.in); \n\n\t buffer = new byte[BUFFER_SIZE]; \n\n\t bufferPointer = bytesRead = 0; \n\n\t } \n\n\t \n\n\t public Reader(String file_name) throws IOException \n\n\t { \n\n\t din = new DataInputStream(new FileInputStream(file_name)); \n\n\t buffer = new byte[BUFFER_SIZE]; \n\n\t bufferPointer = bytesRead = 0; \n\n\t } \n\n\t \n\n\t public String readLine() throws IOException \n\n\t { \n\n\t byte[] buf = new byte[64]; \/\/ line length \n\n\t int cnt = 0, c; \n\n\t while ((c = read()) != -1) \n\n\t { \n\n\t if (c == '\\n') \n\n\t break; \n\n\t buf[cnt++] = (byte) c; \n\n\t } \n\n\t return new String(buf, 0, cnt); \n\n\t } \n\n\t \n\n\t public int nextInt() throws IOException \n\n\t { \n\n\t int ret = 0; \n\n\t byte c = read(); \n\n\t while (c <= ' ') \n\n\t c = read(); \n\n\t boolean neg = (c == '-'); \n\n\t if (neg) \n\n\t c = read(); \n\n\t do\n\n\t { \n\n\t ret = ret * 10 + c - '0'; \n\n\t } while ((c = read()) >= '0' && c <= '9'); \n\n\t \n\n\t if (neg) \n\n\t return -ret; \n\n\t return ret; \n\n\t } \n\n\t \n\n\t public long nextLong() throws IOException \n\n\t { \n\n\t long ret = 0; \n\n\t byte c = read(); \n\n\t while (c <= ' ') \n\n\t c = read(); \n\n\t boolean neg = (c == '-'); \n\n\t if (neg) \n\n\t c = read(); \n\n\t do { \n\n\t ret = ret * 10 + c - '0'; \n\n\t } \n\n\t while ((c = read()) >= '0' && c <= '9'); \n\n\t if (neg) \n\n\t return -ret; \n\n\t return ret; \n\n\t } \n\n\t \n\n\t public double nextDouble() throws IOException \n\n\t { \n\n\t double ret = 0, div = 1; \n\n\t byte c = read(); \n\n\t while (c <= ' ') \n\n\t c = read(); \n\n\t boolean neg = (c == '-'); \n\n\t if (neg) \n\n\t c = read(); \n\n\t \n\n\t do { \n\n\t ret = ret * 10 + c - '0'; \n\n\t } \n\n\t while ((c = read()) >= '0' && c <= '9'); \n\n\t \n\n\t if (c == '.') \n\n\t { \n\n\t while ((c = read()) >= '0' && c <= '9') \n\n\t { \n\n\t ret += (c - '0') \/ (div *= 10); \n\n\t } \n\n\t } \n\n\t \n\n\t if (neg) \n\n\t return -ret; \n\n\t return ret; \n\n\t } \n\n\t \n\n\t private void fillBuffer() throws IOException \n\n\t { \n\n\t bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); \n\n\t if (bytesRead == -1) \n\n\t buffer[0] = -1; \n\n\t } \n\n\t \n\n\t private byte read() throws IOException \n\n\t { \n\n\t if (bufferPointer == bytesRead) \n\n\t fillBuffer(); \n\n\t return buffer[bufferPointer++]; \n\n\t } \n\n\t \n\n\t public void close() throws IOException \n\n\t { \n\n\t if (din == null) \n\n\t return; \n\n\t din.close(); \n\n\t } \n\n\t }\n\n\t static PrintWriter out=new PrintWriter(System.out);\n\n\t static int int_max=Integer.MAX_VALUE;\n\n\t static int int_min=Integer.MIN_VALUE;\n\n\t static long long_max=Long.MAX_VALUE;\n\n\t static long long_min=Long.MIN_VALUE;\n\n\n\n}\n\n\n\n\n\n\n\n\n\n","language":"java"} -{"contest_id":"1301","problem_id":"C","statement":"C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols \"0\" and \"1\"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to \"1\".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1\u2264l\u2264r\u2264|s|1\u2264l\u2264r\u2264|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,\u2026,srsl,sl+1,\u2026,sr is equal to \"1\". For example, if s=s=\"01010\" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to \"1\", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u22641051\u2264t\u2264105) \u00a0\u2014 the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1\u2264n\u22641091\u2264n\u2264109, 0\u2264m\u2264n0\u2264m\u2264n)\u00a0\u2014 the length of the string and the number of symbols equal to \"1\" in it.OutputFor every test case print one integer number\u00a0\u2014 the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to \"1\".ExampleInputCopy5\n3 1\n3 2\n3 3\n4 0\n5 2\nOutputCopy4\n5\n6\n0\n12\nNoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to \"1\". These strings are: s1=s1=\"100\", s2=s2=\"010\", s3=s3=\"001\". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is \"101\".In the third test case, the string ss with the maximum value is \"111\".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to \"1\" is \"0000\" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is \"01010\" and it is described as an example in the problem statement.","tags":["binary search","combinatorics","greedy","math","strings"],"code":"\n\nimport java.io.*;\n\nimport java.util.*;\n\n \n\npublic class CF1562C extends PrintWriter {\n\n\tCF1562C() { super(System.out); }\n\n\tpublic static Scanner sc = new Scanner(System.in);\n\n\tpublic static void main(String[] $) {\n\n\t\tCF1562C o = new CF1562C(); o.main(); o.flush();\n\n\t}\n\n\n\n \n\n\tstatic long calculate(long p, long q)\n\n{\n\n long mod = 1000000007, expo;\n\n expo = mod - 2;\n\n \n\n \/\/ Loop to find the value\n\n \/\/ until the expo is not zero\n\n while (expo != 0)\n\n {\n\n \n\n \/\/ Multiply p with q\n\n \/\/ if expo is odd\n\n if ((expo & 1) == 1)\n\n {\n\n p = (p * q) % mod;\n\n }\n\n q = (q * q) % mod;\n\n \n\n \/\/ Reduce the value of\n\n \/\/ expo by 2\n\n expo >>= 1;\n\n }\n\n return p;\n\n}\n\n static String longestPalSubstr(String str)\n\n {\n\n \/\/ The result (length of LPS)\n\n int maxLength = 1;\n\n \n\n int start = 0;\n\n int len = str.length();\n\n \n\n int low, high;\n\n \n\n \/\/ One by one consider every\n\n \/\/ character as center\n\n \/\/ point of even and length\n\n \/\/ palindromes\n\n for (int i = 1; i < len; ++i) {\n\n \/\/ Find the longest even\n\n \/\/ length palindrome with\n\n \/\/ center points as i-1 and i.\n\n low = i - 1;\n\n high = i;\n\n while (low >= 0 && high < len\n\n && str.charAt(low)\n\n == str.charAt(high)) {\n\n --low;\n\n ++high;\n\n }\n\n \n\n \/\/ Move back to the last possible valid palindrom substring\n\n \/\/ as that will anyway be the longest from above loop\n\n ++low; --high;\n\n if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {\n\n start = low;\n\n maxLength = high - low + 1;\n\n }\n\n \n\n \/\/ Find the longest odd length\n\n \/\/ palindrome with center point as i\n\n low = i - 1;\n\n high = i + 1;\n\n while (low >= 0 && high < len\n\n && str.charAt(low)\n\n == str.charAt(high)) {\n\n --low;\n\n ++high;\n\n }\n\n \n\n \/\/ Move back to the last possible valid palindrom substring\n\n \/\/ as that will anyway be the longest from above loop\n\n ++low; --high;\n\n if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {\n\n start = low;\n\n maxLength = high - low + 1;\n\n }\n\n }\n\n \n\n \n\n return str.substring(start, start + maxLength - 1);\n\n \n\n }\n\n \n\nlong check(long a){\n\n long ret=0;\n\n for(long k=2;(k*k*k)<=a;k++){\n\n ret=ret+(a\/(k*k*k)); \n\n }\n\n return ret;\n\n}\n\n\/*public static int getFirstSetBitPos(int n)\n\n\t{\n\n\t\treturn (int)((Math.log10(n & -n)) \/ Math.log10(2)) + 1;\n\n\t}\n\n\tpublic static int bfsq(int n, int m, HashMap>h,boolean v ){\n\n\t v[n]=true;\n\n\t if(n==m)\n\n\t return 1;\n\n\t else \n\n\t {\n\n\t int a=h.get(n).get(0);\n\n\t int b=h.get(n).get(1);\n\n\t if(b>m)\n\n\t return(m-n);\n\n\t else \n\n\t {\n\n\t int a1=bfsq(a,m,h,v);\n\n\t int b1=bfsq(b,m,h,v);\n\n\t return 1+Math.min(a1,b1);\n\n\t }\n\n\t \n\n\t }\n\n\t}*\/\n\n\tstatic long nCr(int n, int r)\n\n{ return fact(n) \/ (fact(r) *\n\n fact(n - r));\n\n}\n\n \n\n\/\/ Returns factorial of n\n\nstatic long fact(long n)\n\n{\n\n long res = 1;\n\n for (long i = 2; i <= n; i++)\n\n res = res * i;\n\n return res;\n\n}\n\n\/*void bfs(int src, HashMap>h,int deg, boolean v[] ){\n\n a[src]=deg;\n\n Queue= new LinkedList();\n\n q.add(src);\n\n while(!q.isEmpty()){\n\n (int a:h.get(src)){\n\n if()\n\n }\n\n }\n\n \n\n}*\/\n\n \n\n\t \/* void dfs(int root, int par, HashMap>h,int dp[], int child[]) {\n\n \n\n dp[root]=0;\n\n child[root]=1;\n\n for(int x: h.get(root)){\n\n if(x == par) continue;\n\n dfs(x,root,h,in,dp);\n\n child[root]+=child[x];\n\n }\n\n ArrayList mine= new ArrayList();\n\n for(int x: h.get(root)) {\n\n if(x == par) continue;\n\n mine.add(x);\n\n }\n\n if(mine.size() >=2){\n\nint y= Math.max(child[mine.get(0)] - 1 + dp[mine.get(1)] , child[mine.get(1)] -1 + dp[mine.get(0)]);\n\n dp[root]=y;}\n\nelse if(mine.size() == 1)\n\n dp[root]=child[mine.get(0)] - 1;\n\n }\n\n\t *\/ \n\nclass Pair implements Comparable{\n\n\t\tint i;\n\n\t\tint j;\n\n\tPair (int a, int b){\n\n\t\ti = a;\n\n\tj = b;\n\n\t}\n\n\tpublic int compareTo(Pair A){\n\n\t\treturn (int)(this.i-A.i);\n\n\t}}\n\n\/*static class Pair {\n\n int i;\n\n int j;\n\n \n\n Pair() {\n\n \n\n }\n\n Pair(int i, int j) {\n\n this.i = i;\n\n this.j = j;\n\n }\n\n }*\/\n\n \n\n public int[] check(String s) {\n\n int ans[]= new int[2];\n\n int maxans = 0;\n\n int dp[] = new int[s.length()];\n\n for (int i = 1; i < s.length(); i++) {\n\n if (s.charAt(i) == ')') {\n\n if (s.charAt(i - 1) == '(') {\n\n dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;\n\n } else if (i - dp[i - 1] > 0 && s.charAt(i - dp[i - 1] - 1) == '(') {\n\n dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;\n\n }\n\n if(dp[i]==maxans)\n\n ans[1]=ans[1]+1;\n\n if(dp[i]>maxans){\n\n ans[0]=dp[i];\n\n ans[1]=1;\n\n maxans = Math.max(maxans, dp[i]);}\n\n \n\n }\n\n }\n\n if(ans[0]==0)\n\n ans[1]=1;\n\n return ans;\n\n } \n\n void main() {\n\nint g=sc.nextInt();\n\nfor(int w=0;w 0){\n\n solve(f, out);\n\n }\n\n\n\n\n\n\n\n out.close();\n\n }\n\n\n\n\n\n public static void solve(FastReader f, PrintWriter out) {\n\n int n = f.nextInt();\n\n String s = f.nextLine();\n\n\n\n HashMap hm = new HashMap<>();\n\n int ansL = -1;\n\n int ansR = -1;\n\n\n\n int x = 0;\n\n int y = 0;\n\n hm.put(x+\":\"+y, 0);\n\n for(int i = 0; i < n; i++) {\n\n if(s.charAt(i) == 'U') {\n\n y++;\n\n } else if(s.charAt(i) == 'D') {\n\n y--;\n\n } else if(s.charAt(i) == 'L') {\n\n x--;\n\n } else {\n\n x++;\n\n }\n\n String pos = x + \":\" + y;\n\n if(hm.containsKey(pos)) {\n\n int sInd = hm.get(pos)+1;\n\n int eInd = i+1;\n\n\n\n if((ansL == -1 && ansR == -1) || (eInd-sInd+1 < ansR-ansL+1)) {\n\n ansL = sInd;\n\n ansR = eInd;\n\n }\n\n\n\n }\n\n \n\n hm.put(pos, i+1);\n\n }\n\n\n\n if(ansL == -1 && ansR == -1) {\n\n out.println(-1);\n\n } else {\n\n out.println(ansL + \" \" + ansR);\n\n }\n\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n \/\/ Sort an array\n\n public static void sort(int arr[]) {\n\n ArrayList al = new ArrayList<>();\n\n for(int i: arr) {\n\n al.add(i);\n\n }\n\n Collections.sort(al);\n\n for(int i = 0; i < arr.length; i++) {\n\n arr[i] = al.get(i);\n\n }\n\n }\n\n\n\n \/\/ Find all divisors of n\n\n public static void allDivisors(int n) {\n\n for(int i = 1; i*i <= n; i++) {\n\n if(n%i == 0) {\n\n System.out.println(i + \" \");\n\n if(i != n\/i) {\n\n System.out.println(n\/i + \" \");\n\n }\n\n }\n\n }\n\n }\n\n\n\n \/\/ Check if n is prime or not\n\n public static boolean isPrime(int n) {\n\n if(n < 1) return false;\n\n if(n == 2 || n == 3) return true;\n\n if(n % 2 == 0 || n % 3 == 0) return false;\n\n for(int i = 5; i*i <= n; i += 6) {\n\n if(n % i == 0 || n % (i+2) == 0) {\n\n return false;\n\n }\n\n }\n\n return true;\n\n }\n\n\n\n \/\/ Find gcd of a and b\n\n public static long gcd(long a, long b) {\n\n long dividend = a > b ? a : b;\n\n long divisor = a < b ? a : b;\n\n \n\n while(divisor > 0) {\n\n long reminder = dividend % divisor;\n\n dividend = divisor;\n\n divisor = reminder;\n\n }\n\n return dividend;\n\n }\n\n\n\n \/\/ Find lcm of a and b\n\n public static long lcm(long a, long b) {\n\n long lcm = gcd(a, b);\n\n long hcf = (a * b) \/ lcm;\n\n return hcf;\n\n }\n\n\n\n \/\/ Find factorial in O(n) time\n\n public static long fact(int n) {\n\n long res = 1;\n\n for(int i = 2; i <= n; i++) {\n\n res = res * i;\n\n }\n\n return res;\n\n }\n\n\n\n \/\/ Find power in O(logb) time\n\n public static long power(long a, long b) {\n\n long res = 1;\n\n while(b > 0) {\n\n if((b&1) == 1) {\n\n res = (res * a)%mod;\n\n }\n\n a = (a * a)%mod;\n\n b >>= 1;\n\n }\n\n return res;\n\n }\n\n\n\n \/\/ Find nCr\n\n public static long nCr(int n, int r) {\n\n if(r < 0 || r > n) {\n\n return 0;\n\n }\n\n long ans = fact(n) \/ (fact(r) * fact(n-r));\n\n return ans;\n\n }\n\n\n\n \/\/ Find nPr\n\n public static long nPr(int n, int r) {\n\n if(r < 0 || r > n) {\n\n return 0;\n\n }\n\n long ans = fact(n) \/ fact(r);\n\n return ans;\n\n }\n\n\n\n\n\n \/\/ sort all characters of a string\n\n public static String sortString(String inputString) {\n\n char tempArray[] = inputString.toCharArray();\n\n Arrays.sort(tempArray);\n\n return new String(tempArray);\n\n }\n\n\n\n \/\/ User defined class for fast I\/O\n\n static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n \n\n public FastReader() {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n \n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n }\n\n catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n boolean hasNext() {\n\n if (st != null && st.hasMoreTokens()) {\n\n return true;\n\n }\n\n String tmp;\n\n try {\n\n br.mark(1000);\n\n tmp = br.readLine();\n\n if (tmp == null) {\n\n return false;\n\n }\n\n br.reset();\n\n } catch (IOException e) {\n\n return false;\n\n }\n\n return true;\n\n }\n\n \n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n \n\n long nextLong() {\n\n return Long.parseLong(next()); \n\n }\n\n \n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n \n\n float nextFloat() {\n\n return Float.parseFloat(next());\n\n }\n\n \n\n boolean nextBoolean() {\n\n return Boolean.parseBoolean(next());\n\n }\n\n \n\n String nextLine() {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n }\n\n catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n\n\n int[] nextArray(int n) {\n\n int[] a = new int[n];\n\n for(int i=0; i 94 ^ 126 ~\n\n 31 US (unit separator) 63 ? 95 _ 127 DEL\n\n *\/\n\n\n\n\n\n \n\n\/\/ (a\/b)%mod == (a * moduloInverse(b)) % mod;\n\n\/\/ moduloInverse(b) = power(b, mod-2);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","language":"java"} -{"contest_id":"1307","problem_id":"D","statement":"D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105, n\u22121\u2264m\u22642\u22c5105n\u22121\u2264m\u22642\u22c5105, 2\u2264k\u2264n2\u2264k\u2264n) \u00a0\u2014 the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,\u2026,aka1,a2,\u2026,ak (1\u2264ai\u2264n1\u2264ai\u2264n) \u00a0\u2014 the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n, xi\u2260yixi\u2260yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3\n1 3 5\n1 2\n2 3\n3 4\n3 5\n2 4\nOutputCopy3\nInputCopy5 4 2\n2 4\n1 2\n2 3\n3 4\n4 5\nOutputCopy3\nNoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33. ","tags":["binary search","data structures","dfs and similar","graphs","greedy","shortest paths","sortings"],"code":"\/*\n\n \"Everything in the universe is balanced. Every disappointment\n\n you face in life will be balanced by something good for you!\n\n Keep going, never give up.\"\n\n\n\n Just have Patience + 1...\n\n\n\n*\/\n\n\n\n\n\n\n\nimport java.util.*;\n\nimport java.lang.*;\n\nimport java.io.*;\n\n\n\n\n\npublic class Solution {\n\n\n\n static int MAX = 200005, INF = 1000000007;\n\n static Map> graph = new HashMap<>();\n\n static int[][] shortestDistance = new int[2][MAX];\n\n\n\n public static void main(String[] args) throws java.lang.Exception {\n\n out = new PrintWriter(new BufferedOutputStream(System.out));\n\n sc = new FastReader();\n\n\n\n int test = 1;\n\n for (int t = 0; t < test; t++) {\n\n solve();\n\n }\n\n out.close();\n\n }\n\n\n\n\n\n private static void solve() {\n\n int n = sc.nextInt();\n\n int m = sc.nextInt();\n\n int k = sc.nextInt();\n\n\n\n for (int i = 0; i < 2; i++) {\n\n Arrays.fill(shortestDistance[i], INF);\n\n }\n\n\n\n List specialNodes = new ArrayList<>();\n\n for (int i = 0; i < k; i++) {\n\n int node = sc.nextInt();\n\n specialNodes.add(node);\n\n }\n\n\n\n for (int i = 1; i <= n; i++) {\n\n graph.put(i, new ArrayList<>());\n\n }\n\n\n\n for (int i = 0; i < m; i++) {\n\n int u = sc.nextInt();\n\n int v = sc.nextInt();\n\n graph.get(u).add(v);\n\n graph.get(v).add(u);\n\n }\n\n\n\n bfs(1, 0);\n\n bfs(n, 1);\n\n\n\n specialNodes.sort(Comparator.comparingInt(a -> (shortestDistance[0][a] - shortestDistance[1][a])));\n\n\n\n int maxShortestPath = 0, maxSpecialDistanceFromStart = -INF;\n\n for (int node : specialNodes) {\n\n maxShortestPath = Math.max(maxShortestPath, maxSpecialDistanceFromStart + shortestDistance[1][node]);\n\n maxSpecialDistanceFromStart = Math.max(maxSpecialDistanceFromStart, shortestDistance[0][node]);\n\n }\n\n\n\n maxShortestPath++; \/\/ special edge length\n\n\n\n out.println(Math.min(maxShortestPath, shortestDistance[0][n]));\n\n }\n\n\n\n private static void bfs(int startNode, int index) {\n\n Queue q = new LinkedList<>();\n\n shortestDistance[index][startNode] = 0;\n\n q.add(startNode);\n\n\n\n while (!q.isEmpty()) {\n\n int currNode = q.poll();\n\n for (int adjacentNode : graph.get(currNode)) {\n\n if (shortestDistance[index][adjacentNode] > shortestDistance[index][currNode] + 1) {\n\n shortestDistance[index][adjacentNode] = shortestDistance[index][currNode] + 1;\n\n q.add(adjacentNode);\n\n }\n\n }\n\n }\n\n }\n\n\n\n\n\n public static FastReader sc;\n\n public static PrintWriter out;\n\n static class FastReader\n\n {\n\n BufferedReader br;\n\n StringTokenizer str;\n\n\n\n public FastReader()\n\n {\n\n br = new BufferedReader(new\n\n InputStreamReader(System.in));\n\n }\n\n\n\n String next()\n\n {\n\n while (str == null || !str.hasMoreElements())\n\n {\n\n try\n\n {\n\n str = new StringTokenizer(br.readLine());\n\n }\n\n catch (IOException lastMonthOfVacation)\n\n {\n\n lastMonthOfVacation.printStackTrace();\n\n }\n\n }\n\n return str.nextToken();\n\n }\n\n\n\n int nextInt()\n\n {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n long nextLong()\n\n {\n\n return Long.parseLong(next());\n\n }\n\n\n\n double nextDouble()\n\n {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n String nextLine()\n\n {\n\n String str = \"\";\n\n try\n\n {\n\n str = br.readLine();\n\n }\n\n catch (IOException lastMonthOfVacation)\n\n {\n\n lastMonthOfVacation.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n}\n\n","language":"java"} -{"contest_id":"1294","problem_id":"E","statement":"E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n\u00d7mn\u00d7m consisting of integers from 11 to 2\u22c51052\u22c5105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n\u22c5mn\u22c5m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1\u2264j\u2264m1\u2264j\u2264m) and set a1,j:=a2,j,a2,j:=a3,j,\u2026,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,\u2026,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,\u2026,a1,m=m,a2,1=m+1,a2,2=m+2,\u2026,an,m=n\u22c5ma1,1=1,a1,2=2,\u2026,a1,m=m,a2,1=m+1,a2,2=m+2,\u2026,an,m=n\u22c5m (i.e. ai,j=(i\u22121)\u22c5m+jai,j=(i\u22121)\u22c5m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1\u2264n,m\u22642\u22c5105,n\u22c5m\u22642\u22c51051\u2264n,m\u22642\u22c5105,n\u22c5m\u22642\u22c5105) \u2014 the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1\u2264ai,j\u22642\u22c51051\u2264ai,j\u22642\u22c5105).OutputPrint one integer \u2014 the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,\u2026,a1,m=m,a2,1=m+1,a2,2=m+2,\u2026,an,m=n\u22c5ma1,1=1,a1,2=2,\u2026,a1,m=m,a2,1=m+1,a2,2=m+2,\u2026,an,m=n\u22c5m (ai,j=(i\u22121)m+jai,j=(i\u22121)m+j).ExamplesInputCopy3 3\n3 2 1\n1 2 3\n4 5 6\nOutputCopy6\nInputCopy4 3\n1 2 3\n4 5 6\n7 8 9\n10 11 12\nOutputCopy0\nInputCopy3 4\n1 6 3 4\n5 10 7 8\n9 2 11 12\nOutputCopy2\nNoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.","tags":["greedy","implementation","math"],"code":"import java.io.*;\n\nimport java.util.*;\n\n\n\npublic class E{\n\n\tstatic int n,m;\n\n\tstatic int[][] g;\n\n\tstatic int[][] t;\n\n\t\n\n\tstatic void dbg(int[][] cur) {\n\n\t\tfor (int[] x: cur) {\n\n\t\t\tfor (int y: x) out.print(y + \" \");\n\n\t\t\tout.println();\n\n\t\t}\n\n\t}\n\n\t\n\n\tpublic static void main(String[] args) throws IOException {\n\n\t\t\/\/ br = new BufferedReader(new FileReader(\".in\"));\n\n\t\t\/\/ out = new PrintWriter(new FileWriter(\".out\"));\n\n\t\t\/\/new Thread(null, new (), \"peepee\", 1<<28).start();\n\n\t\tn = readInt();\n\n\t\tm = readInt();\n\n\t\tg = new int[n][m];\n\n\t\tt = new int[n][m];\n\n\t\tint b = 1;\n\n\t\tfor (int i =0 ; i < n; i++) {\n\n\t\t\tfor (int j = 0; j < m; j++) {\n\n\t\t\t\tt[i][j] = b++;\n\n\t\t\t\tg[i][j] = readInt();\n\n\t\t\t}\n\n\t\t}\n\n\t\tlong cost = 0;\n\n\t\tfor (int i = 0; i < m; i++) {\n\n\t\t\tlong v = solve(i);\n\n\t\t\t\/\/System.out.println(v);\n\n\t\t\tcost += v;\n\n\t\t}\n\n\t\tout.println(cost);\n\n\t\tout.close();\n\n\t}\n\n\t\n\n\tstatic void dbg(long[] a) {\n\n\t\tfor (long x: a) out.print(x + \" \");\n\n\t\tout.println();\n\n\t}\n\n\t\n\n\tstatic long solve(int col) {\n\n\t\tlong[] r = new long[n];\n\n\t\tlong[] r2 = new long[n];\n\n\t\tHashMap>hm = new HashMap>();\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tr[i] = g[i][col];\n\n\t\t\tr2[i] = t[i][col];\n\n\t\t\tif (!hm.containsKey(r2[i])) {\n\n\t\t\t\thm.put(r2[i], new ArrayList());\n\n\t\t\t}\n\n\t\t\thm.get(r2[i]).add(i);\n\n\t\t}\n\n\t\t\n\n\t\tlong ans = 2*n;\n\n\t\tlong[] cycles = new long[n]; \/\/ I cycled i times.\n\n\t\t\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tif (!hm.containsKey(r[i])) continue;\n\n\t\t\tfor (int x: hm.get(r[i])) {\n\n\t\t\t\t\/\/ X IS FROM R2 (the correct)\n\n\t\t\t\t\/\/ I IS FROM R1. (ours)\n\n\t\t\t\tif (i >= x) cycles[i-x]++;\n\n\t\t\t\telse {\n\n\t\t\t\t\tint newR2Pos = x-n;\n\n\t\t\t\t\t\/\/System.out.println(\"We saw it at r2 pos \" + x + \" but our r pos is \" + i );\n\n\t\t\t\t\tcycles[i-newR2Pos]++;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tfor (int i= 0 ; i < n; i++) {\n\n\t\t\tlong tans = i+n-cycles[i];\n\n\t\t\tans = Long.min(ans, tans);\n\n\n\n\t\t}\n\n\t\t\/\/System.out.println(ans);\n\n\t\treturn ans;\n\n\t}\n\n\n\n\t\n\n\tstatic BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n\tstatic PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));\n\n\tstatic StringTokenizer st = new StringTokenizer(\"\");\n\n\tstatic String read() throws IOException{return st.hasMoreTokens() ? st.nextToken():(st = new StringTokenizer(br.readLine())).nextToken();}\n\n\tstatic int readInt() throws IOException{return Integer.parseInt(read());}\n\n\tstatic long readLong() throws IOException{return Long.parseLong(read());}\n\n\tstatic double readDouble() throws IOException{return Double.parseDouble(read());}\n\n\t\n\n}","language":"java"} -{"contest_id":"1141","problem_id":"A","statement":"A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays \"Game 23\". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1\u2264n\u2264m\u22645\u22c51081\u2264n\u2264m\u22645\u22c5108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840\nOutputCopy7\nInputCopy42 42\nOutputCopy0\nInputCopy48 72\nOutputCopy-1\nNoteIn the first example; the possible sequence of moves is: 120\u2192240\u2192720\u21921440\u21924320\u219212960\u219225920\u219251840.120\u2192240\u2192720\u21921440\u21924320\u219212960\u219225920\u219251840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.","tags":["implementation","math"],"code":"\/\/Code By KB.\n\n\n\nimport java.beans.Visibility;\n\nimport java.io.*;\n\nimport java.lang.annotation.Target;\n\nimport java.lang.reflect.Array;\n\nimport java.nio.channels.AsynchronousCloseException;\n\nimport java.security.KeyStore.Entry;\n\nimport java.util.*;\n\nimport java.util.logging.*;\n\nimport java.io.*;\n\nimport java.util.logging.*;\n\nimport java.util.regex.*;\n\n\n\nimport javax.management.ValueExp;\n\nimport javax.print.DocFlavor.INPUT_STREAM;\n\nimport javax.print.event.PrintJobListener;\n\nimport javax.swing.plaf.basic.BasicBorders.SplitPaneBorder;\n\nimport javax.swing.text.AbstractDocument.LeafElement;\n\nimport javax.xml.validation.Validator;\n\n\n\n\n\npublic class Codeforces {\n\n\t\n\n\tpublic static void main(String[] args) {\n\n\t\tFlashFastReader in = new FlashFastReader(System.in);\n\n\t\t\n\n\t\ttry(PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));)\n\n\t\t{\n\n\t\t\tnew Codeforces().solution(in, out);\n\n\t\t} catch (Exception e) {\n\n\t\t\tSystem.out.println(e.getStackTrace());\n\n\t\t}\n\n\t}\n\n\t\n\n\tpublic void solution(FlashFastReader in, PrintWriter out)\n\n\t{\n\n\t\ttry {\n\n\t\t\t\/\/ int t =in.nextInt();\n\n\t\t\t\n\n\t\t\t\/\/ while (t-->0) {\n\n\t\t\t\t\n\n\t\t\t\/\/ }\n\n\t\t\tint n = in.nextInt();\n\n\t\t\tint m = in.nextInt();\n\n\t\t\tif (m%n==0) {\n\n\t\t\t\tint d = m\/n;\n\n\t\t\t\tint res = 0 ;\n\n\t\t\t\twhile (d%2==0) {\n\n\t\t\t\t\td\/=2;\n\n\t\t\t\t\tres++;\n\n\n\n\t\t\t\t}\n\n\t\t\t\twhile (d%3==0) {\n\n\t\t\t\t\td\/=3;\n\n\t\t\t\t\tres++;\n\n\t\t\t\t}\n\n\t\t\t\tif (d==1) {\n\n\t\t\t\t\tout.println(res);\n\n\t\t\t\t} else {\n\n\t\t\t\t\tout.println(-1);\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tout.println(\"-1\");\n\n\t\t\t}\n\n\t\t\t\n\n\t\t} catch (Exception exception) {\n\n\t\t\tout.println(exception);\n\n\t\t}\t\n\n\t\t\t\n\n\t}\n\n\t\n\n\t\n\n\tboolean visited [] = new boolean[1001];\n\n\n\n public int[] topKFrequent(int[] nums, int k) {\n\n\t\tHashMap map = new HashMap<>();\n\n \n\n\t\tint f[] = new int[k];\n\n\n\n\n\n\t\tfor (int i = 0; i < nums.length; i++) {\n\n\t\t\tmap.put(nums[i], map.getOrDefault(nums[i], 0)+1);\n\n\t\t}\n\n\t\t\/\/descending oder of values of map ,here map is the frequency map with key -value pairs\n\n PriorityQueue heap = new PriorityQueue<>(map.size(), (a, b) -> ((int[])b)[1] - ((int[])a)[1]);\n\n\t\t\n\n\t\tfor (Map.Entry e : map.entrySet()) {\n\n\t\t\theap.add(new int[]{e.getKey() , e.getValue()});\n\n\t\t}\n\n\t\tint j = 0;\n\n\t\twhile (k-->0) {\n\n\t\t\tint c[] = heap.remove();\n\n\t\t\tf[j++] = c[0];\n\n\t\t}\n\n\t\treturn f;\n\n\n\n }\n\n\n\n\n\n\n\n\tpublic int countSquares(int[][] matrix) {\n\n int dp [][] = new int [matrix.length+1][matrix[0].length+1];\n\n\t\tfor (int i = 1; i <=matrix.length; i++) {\n\n\t\t\tfor (int j = 1; j <=matrix[0].length; j++) {\n\n\t\t\t\tif (matrix[i][j]==1) {\n\n\t\t\t\t\tif (i>=1&&j>=1) {\n\n\t\t\t\t\t\tdp[i][j] =1+ Math.min(dp[i-1][j], Math.min(dp[i-1][j-1], dp[i][j-1]) );\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tx+=dp[i][j];\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\treturn x;\n\n }\n\n\n\n\n\n\tHashMap map = new HashMap<>();\n\n\tpublic int totalNQueens(int n) {\n\n if (n==1) {\n\n\t\t\treturn 1;\n\n\t\t}\n\n\t\tif (n==2||n==3) {\n\n\t\t\treturn 0;\n\n\t\t}\n\n\t\tdfsNqueens( map , 0 , n );\n\n\n\n\t\treturn x;\n\n }\n\n\n\n\n\n\n\n\tpublic void dfsNqueens( HashMapmap , int col , int n ) {\n\n\t\tif (col == n) {\n\n\t\t\tx++;\n\n\t\t\treturn;\n\n\t\t}\n\n\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tmap.put(col, i);\n\n\t\t\tboolean f = true;\n\n\t\t\tfor (int j = 0; j < n; j++) {\n\n\t\t\t\tif (map.containsKey(j)) {\n\n\t\t\t\t\tif (map.get(j)==i||Math.abs(col - j)==Math.abs(map.get(j)-i) ) {\n\n\t\t\t\t\t\tf = false;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif (f) {\n\n\t\t\t\tdfsNqueens(map, col+1, n);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\tpublic int[] minOperations(String boxes) {\n\n\n\n int a [] = new int[boxes.length()];\n\n\n\n\t\tfor (int i = 0; i < boxes.length(); i++) {\n\n\t\t\tStringBuilder sb = new StringBuilder(boxes);\n\n\t\t\tint x = 0;\n\n\n\n\t\t\tfor (int j = 0; j < sb.length(); j++) {\n\n\t\t\t\tif (sb.indexOf(\"1\")<0) {\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t\tx+=Math.abs(i - sb.indexOf(\"1\"));\n\n\t\t\t\tsb.setCharAt(sb.indexOf(\"1\"), '0');\n\n\t\t\t}\n\n\t\t\t\n\n\t\t\ta[i] = x;\n\n\t\t}\n\n\t\t\n\n\t\treturn a;\n\n\n\n }\n\n\n\n\t\n\n\tpublic List> subsets(int[] nums) {\n\n List curr = new ArrayList<>();\n\n\t\tsubsetsGen(0, nums , curr);\n\n\t\treturn list;\n\n }\n\n\tpublic void subsetsGen(int j ,int[] n , Listcurr) {\n\n\t\tlist.add(curr);\n\n\t\t\n\n\t\tfor (int i = j; i < n.length; i++) {\n\n\t\t\tcurr.add(n[i]);\n\n\t\t\tsubsetsGen(j+1, n, curr);\n\n\t\t\tcurr.remove(curr.size()-1);\n\n\t\t}\n\n\t}\n\n\t\n\n\n\n\tpublic int findCircleNum(int[][] isConnected) {\n\n \n\n\t\tfor (int i = 0; i < isConnected.length; i++) {\n\n\t\t\tif (visited[i]!=true) {\n\n\t\t\t\tx++;\n\n\n\n\t\t\t\tdfsFindProvinces( i , isConnected );\n\n\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn x;\n\n }\n\n\tpublic void dfsFindProvinces( int i ,int [][]isConnected ) {\n\n\t\tvisited[i]=true;\n\n\t\tfor (int j = 0; j < isConnected.length; j++) {\n\n\t\t\tif (isConnected[i][j]==1&&visited[j]!=true) {\n\n\t\t\t\tdfsFindProvinces(j, isConnected);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\n\n\tpublic int[] canSeePersonsCount(int[] heights) {\n\n\t\tint ans [] = new int[heights.length];\n\n\t\tStack stck = new Stack<>();\n\n\t\tfor (int i = 0; i < heights.length; i++) {\n\n\n\n\t\t\twhile(!stck.isEmpty()&&heights[stck.peek()] path = new ArrayList<>();\n\n\n\n dsfPathSum(root, targetSum , 0 ,path);\n\n\t\tpathSum(root.left, targetSum);\n\n\t\tpathSum(root.right, targetSum);\n\n\t\tfor (List p : list) {\n\n\t\t\tfor (int i = 0; i < p.size() ; i++) {\n\n\t\t\t\tSystem.out.print(p.get(i)+\" \");\n\n\t\t\t}\n\n\t\t\tSystem.out.println();\n\n\t\t}\n\n return list.size();\n\n }\n\n public void dsfPathSum(TreeNode root , int t , long sum , Listpath ) {\n\n\t\tif (root==null) {\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tsum+=root.val ;\n\n\t\tpath.add(root.val);\n\n\t\tif (sum==t) {\n\n\t\t\tlist.add(path);\n\n\t\t}\n\n\t\tdsfPathSum(root.left, t, sum , path);\n\n\t\tdsfPathSum(root.right, t, sum , path);\n\n\t}\n\n\t\n\n\tpublic ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n\n ListNode l = new ListNode();\n\n\t\tint a = 0;\n\n\t\tint b =0;\n\n\t\tl1 = reverseList(l1);\n\n\t\tl2 = reverseList(l2);\n\n\t\twhile (l1!=null) {\n\n\t\t\ta=a*10+l1.val;\n\n\t\t\tl1=l1.next;\n\n\t\t}\n\n\t\twhile (l2!=null) {\n\n\t\t\tb=b*10+l2.val;\n\n\t\t\tl2=l2.next;\n\n\t\t}\n\n\t\ta=a+b;\n\n\t\tListNode head = null;\n\n\t\twhile (a!=0) {\n\n\t\t\tint r = a%10;\n\n\t\t\tif(l==null) {\n\n\t\t\t\thead= new ListNode(r);\n\n\t\t\t\tl=head;\n\n\t\t\t}else {\n\n\t\t\t\tl.next = new ListNode(r);\n\n\t\t\t\tl= l.next;\n\n\t\t\t\t}\n\n\t\t\ta\/=10;\n\n\t\t}\n\n\t\treturn head;\n\n }\n\n\tpublic ListNode reverseList(ListNode head) {\n\n if(head==null || head.next==null)\n\n return head;\n\n ListNode nextNode=head.next;\n\n ListNode newHead=reverseList(nextNode);\n\n nextNode.next=head;\n\n head.next=null;\n\n return newHead;\n\n }\n\n\n\n\tint x=0;\n\n\tpublic int uniquePathsIII(int[][] grid) {\n\n \n\n\t\tint zeros = 0;\n\n\t\tint sx=0;\n\n\t\tint sy =0;\n\n\t\tfor (int i = 0; i < grid.length; i++) {\n\n\t\t\tfor (int j = 0; j < grid[0].length; j++) {\n\n\t\t\t\tif (grid[i][j]==0) {\n\n\t\t\t\t\tzeros++;\n\n\t\t\t\t} else if (grid[i][j]==1) {\n\n\t\t\t\t\tsx=i;\n\n\t\t\t\t\tsy=j;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tdfsUniquePaths(zeros , sx , sy , grid);\n\n\t\treturn x;\n\n }\n\n\n\n\tpublic void dfsUniquePaths(int zeros ,int i ,int j , int g[][]) {\n\n\n\n\t\tif (i<0||i>=g.length||j>=g[0].length||j<0||g[i][j]<0) {\n\n\t\t\tSystem.out.println(i+\" \"+j);\n\n\t\t\treturn;\n\n\t\t}\n\n\n\n\t\t\n\n\t\tif (g[i][j]==2) {\n\n\t\t\tif(zeros==0)\n\n\t\t\t\tx++;\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tg[i][j]=-2;\n\n\t\tzeros--;\n\n\t\tdfsUniquePaths(zeros, i+1, j, g);\n\n\t\tdfsUniquePaths(zeros, i-1, j, g);\n\n\t\tdfsUniquePaths(zeros, i, j+1, g);\n\n\t\tdfsUniquePaths(zeros, i, j-1, g);\n\n\t\tg[i][j]=0;\n\n\t\tzeros++;\n\n\n\n\n\n\t}\n\n\tpublic TreeNode addOneRow(TreeNode root, int val, int depth) {\n\n if (depth==1) {\n\n\t\t\tTreeNode t = new TreeNode(val);\n\n\t\t\tt.left=root;\n\n\t\t\treturn t;\n\n\t\t}\n\n\t\tdfsAddOneRow(root , 1 , val , depth);\n\n\t\treturn root;\n\n }\n\n\tpublic void dfsAddOneRow(TreeNode root , int currD , int val , int depth) {\n\n\t\tif (root==null) {\n\n\t\t\treturn ;\n\n\t\t}\n\n\t\tif (currD==depth) {\n\n\n\n\t\t\tTreeNode l = root.left;\n\n\t\t\troot.left = new TreeNode(val);\n\n\t\t\troot.left.left = l;\n\n\t\t\tTreeNode r = root.right;\n\n\t\t\troot.right = new TreeNode(val);\n\n\t\t\troot.right.right = r;\n\n\n\n\t\t}\n\n\t\tcurrD++;\n\n\t\tdfsAddOneRow(root.left, currD, val, depth);\n\n\t\tdfsAddOneRow(root.right, currD, val, depth);\n\n\n\n\t}\n\n\n\n public List> threeSum(int[] nums) {\n\n \n\n\t\tint n = nums.length;\n\n\t\tint sum =0;\n\n\t\tHashSet> h = new HashSet>();\n\n\n\n\t\tfor (int i = 0; i < nums.length; i++) {\n\n\t\t\tsum=nums[i];\n\n\t\t\tfor (int j = i+1; j < nums.length; j++) {\n\n\t\t\t\t\n\n\t\t\t\t\n\n\t\t\t}\n\n\t\t}\n\n\t\t\n\n\t\treturn list;\n\n }\n\n\n\n\n\n\n\n\tpublic int uniquePaths(int m, int n) {\n\n\t\tint dp[][]= new int [m][n];\n\n\t\t\n\n for (int i = 0; i < m; i++) {\n\n\t\t\tfor (int j = 0; j < n; j++) {\n\n\t\t\t\tif(i==0&&j==0) {\n\n\t\t\t\t\tdp[i][j]=1;\n\n\t\t\t\t} else if (i==0) {\n\n\t\t\t\t\tdp[i][j]=dp[i][j]+dp[i][j-1];\n\n\t\t\t\t} else if (j==0) {\n\n\t\t\t\t\tdp[i][j]=dp[i][j]+dp[i-1][j];\n\n\t\t\t\t} else {\n\n\t\t\t\t\tdp[i][j]+=dp[i][j-1]+dp[i-1][j];\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn dp[m-1][n-1];\n\n }\n\n\n\n\n\n\n\n\tpublic int maxProfit(int[] prices) {\n\n int p = -1;\n\n\t\t\n\n\t\treturn p ;\n\n }\n\n\n\n\tpublic int trap(int[] height) {\n\n\t\tint n = height.length;\n\n\t\tint left[] = new int [n];\n\n\t\tint right[] = new int [n];\n\n\t\tleft[0] = height[0];\n\n\t\tfor (int i = 1; i =0 ; i--) {\n\n\t\t\tright[i] = Math.max(height[i], right[i+1]);\n\n\t\t}\n\n\t\tfor (int i = 1; i < right.length-1; i++) {\n\n\t\t\tint s =Math.min(left[i] , right[i])-height[i];\n\n\t\t\tif (s>0) {\n\n\t\t\t\tx+=s;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn x;\n\n }\n\n\n\n public int maxProduct(int[] nums) {\n\n int maxSoFar = Integer.MIN_VALUE;\n\n\t\tint maxTillEnd = 0;\n\n\n\n\t\tfor (int i = 0; i < nums.length; i++) {\n\n\t\t\tmaxTillEnd*=nums[i];\n\n\t\t\tif (maxSoFar=grid.length||j<0||j>grid[0].length) {\n\n\t\t\tx++;\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tif(grid[i][j]==0) {\n\n\t\t\tx++;\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tif(grid[i][j]==1) {\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tdfsIslandPerimeter(i+1, j, grid);\n\n\t\tdfsIslandPerimeter(i-1, j, grid);\n\n\t\tdfsIslandPerimeter(i, j+1, grid);\n\n\t\tdfsIslandPerimeter(i, j-1, grid);\n\n\n\n\t}\n\n\t\n\n\n\n\tpublic int[] findOriginalArray(int[] changed) {\n\n\t\tint n =changed.length;\n\n\t\tint m = n\/2;\n\n int a[] = new int[m];\n\n\t\tif (n<2) {\n\n\t\t\treturn new int[]{};\n\n\t\t}\n\n\t\tif (n%2!=0) {\n\n\t\t\treturn new int[]{};\n\n\t\t}\n\n\n\n\t\tTreeMap map = new TreeMap<>();\n\n\n\n\t\tfor (int i = 0; i < changed.length; i++) {\n\n\t\t\tmap.put(changed[i], map.getOrDefault(changed[i] ,0)+1);\n\n\t\t}\n\n\t\tint j =0;\n\n\t\tfor (Map.Entry e : map.entrySet()) {\n\n\t\t\tif (map.containsKey(e.getKey()*2)&&map.get(e.getKey()*2)>=1&&map.get(e.getKey())>=1) {\n\n\t\t\t\tmap.put(e.getKey(), map.get(e.getKey()) -1);\n\n\t\t\t\tif(j==n-1)\n\n\t\t\t\t\tbreak;\n\n\t\t\t\ta[j++] = e.getKey();\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\treturn a;\n\n }\n\n\tpublic int jump(int[] nums) {\n\n int n =nums.length;\n\n\t\tint jumps =1;\n\n\t\tint i =0;\n\n\t\tint j =0;\n\n\t\twhile (i= n\/2) {\n\n\t\t\treturn stocks(prices, n);\n\n\t\t}\n\n\t\t\n\n\t\tint[][] dp = new int[k+1][n];\n\n\n\n\t\tfor (int i = 1; i <=k; i++) {\n\n\t\t\tint c= dp[i-1][0] - prices[0];\n\n\t\t\tfor (int j = 1; j < n; j++) {\n\n\t\t\t\tdp[i][j] = Math.max(dp[i][j-1], prices[j] + c);\n\n\t\t\t\tc = Math.max(c, dp[i-1][j] - prices[j]);\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn dp[k][n-1];\n\n\t}\n\n\n\n\tpublic int stocks(int [] prices , int n ) {\n\n\t\tint maxPro = 0;\n\n\t\t\tfor (int i = 1; i < n; i++) {\n\n\t\t\t\tif (prices[i] > prices[i-1])\n\n\t\t\t\t\tmaxPro += prices[i] - prices[i-1];\n\n\t\t\t}\n\n\t\treturn maxPro;\n\n\t}\n\n\n\n public List> combine(int n, int k) {\n\n\t\tList x = new ArrayList<>();\n\n\n\n combinations( n , k , 1 ,x);\n\n\t\treturn list;\n\n }\n\n\n\n\tpublic void combinations(int n , int k ,int startPos , List x) {\n\n\t\tif (k==x.size()) {\n\n\t\t\tlist.add(new ArrayList<>(x));\n\n\t\t\t\/\/x=new ArrayList<>();\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tfor (int i = startPos; i <=n; i++) {\n\n\t\t\tx.add(i);\n\n\t\t\t\n\n\t\t\tcombinations(n, k, i+1, x);\n\n\t\t\tx.remove(x.size()-1);\n\n\t\t}\n\n\n\n\n\n\t}\n\n\tList> list = new ArrayList<>();\n\n\n\n\tpublic List> permute(int[] a) {\n\n\t\tList x = new ArrayList<>();\n\n\n\n permutations(a , 0 ,a.length ,x );\n\n\t\treturn list ;\n\n }\n\n\n\n\tpublic void permutations(int a[] , int startPos , int l , Listx) {\n\n\t\tif (l==x.size()) {\n\n\t\t\tlist.add(new ArrayList<>(x));\n\n\t\t\t\/\/x=new ArrayList<>();\n\n\t\t}\n\n\t\tfor (int i = 0; i <=l; i++) {\n\n\t\t\tif (!x.contains(a[i])) {\n\n\t\t\t\tx.add(a[i]);\n\n\t\t\t\n\n\t\t\t\tpermutations(a, i, l, x);\n\n\t\t\t\tx.remove(x.size()-1);\n\n\t\t\t}\n\n\n\n\t\t}\n\n\t}\n\n\n\n\tList str = new ArrayList<>();\n\n\n\n\tpublic List letterCasePermutation(String s) {\n\n\n\n\t\tcasePermutations(s , 0 , s.length() , \"\" );\n\n return str;\n\n }\n\n\n\n\tpublic void casePermutations(String s ,int i , int l , String curr) {\n\n\n\n\t\tif (curr.length()==l) {\n\n\t\t\tstr.add(curr);\n\n\t\t\treturn;\n\n\t\t}\n\n\t\t\n\n\t\tchar b = s.charAt(i);\n\n\t\tcurr+=b;\n\n\t\tcasePermutations(s, i+1, l, curr);\n\n\t\tcurr = new StringBuilder(curr).deleteCharAt(curr.length()-1).toString();\n\n\t\tif (Character.isAlphabetic(b)&&Character.isLowerCase(b)) {\n\n\t\t\tcurr+=Character.toUpperCase(b);\n\n\t\t\tcasePermutations(s, i+1, l, curr);\n\n\t\t\tcurr = new StringBuilder(curr).deleteCharAt(curr.length()-1).toString();\n\n\n\n\t\t} else if (Character.isAlphabetic(b)) {\n\n\t\t\tcurr+=Character.toLowerCase(b);\n\n\t\t\tcasePermutations(s, i+1, l, curr);\n\n\t\t\tcurr = new StringBuilder(curr).deleteCharAt(curr.length()-1).toString();\n\n\n\n\n\n\t\t}\n\n\t}\n\n\n\n\tTreeNode ans= null;\n\n\tpublic TreeNode lcaDeepestLeaves(TreeNode root) {\n\n\t\tdfslcaDeepestLeaves(root , 0 );\n\n return ans;\n\n }\n\n\tpublic void dfslcaDeepestLeaves(TreeNode root , int level) {\n\n\t\tif (root==null) {\n\n\t\t\treturn;\n\n\t\t}\n\n\n\n\t\tif (depth(root.left)==depth(root.right)) {\n\n\t\t\tans= root;\n\n\t\t\treturn;\n\n\t\t} else if (depth(root.left)>depth(root.right)){\n\n\t\t\tdfslcaDeepestLeaves(root.left, level+1);\n\n\t\t} else {\n\n\t\t\tdfslcaDeepestLeaves(root.right, level+1);\n\n\t\t}\n\n\t}\n\n\n\n\n\n\tpublic int depth(TreeNode root) {\n\n\n\n\t\tif (root==null) {\n\n\t\t\treturn 0;\n\n\t\t}\n\n\n\n\t\treturn 1+Math.max(depth(root.left), depth(root.right));\n\n\t}\n\n\n\n\tTreeMap m = new TreeMap<>();\n\n\tpublic int maxLevelSum(TreeNode root) {\n\n int maxlevel =0;\n\n\t\tint mx = Integer.MIN_VALUE;\n\n\t\tdfsMaxLevelSum(root , 0);\n\n\n\n\t\tfor (Map.Entry e : m.entrySet()) {\n\n\t\t\tif (e.getValue()>mx) {\n\n\t\t\t\tmx=e.getValue();\n\n\t\t\t\tmaxlevel=e.getKey()+1;\n\n\t\t\t}\n\n\t\t}\n\n\t\t\n\n\t\treturn maxlevel;\n\n }\n\n\tpublic void dfsMaxLevelSum(TreeNode root , int currLevel) {\n\n\t\tif (root==null) {\n\n\t\t\treturn;\n\n\t\t}\n\n\n\n\t\tif (!m.containsKey(currLevel)) {\n\n\t\t\tm.put(currLevel, root.val);\n\n\t\t} else {\n\n\t\t\tm.put(currLevel, m.get(currLevel)+root.val);\n\n\t\t}\n\n\t\tdfsMaxLevelSum(root.left, currLevel+1);\n\n\t\tdfsMaxLevelSum(root.right, currLevel+1);\n\n\t\t\n\n\t}\n\n\n\n\tint teampPerf = 0;\n\n\tint teampSpeed = 0;\n\n\n\n public int maxPerformance(int n, int[] speed, int[] efficiency, int k) {\n\n\n\n\t\tint [][] map = new int[efficiency.length][2];\n\n\t\t\n\n\t\tfor (int i = 0; i < efficiency.length; i++) {\n\n\t\t\tmap[i][0] = efficiency[i];\n\n\t\t\tmap[i][1] = speed[i];\n\n\t\t}\n\n\t\tArrays.sort(map , (e1 , e2 )-> (e2[0] - e1[0]));\n\n\t\tPriorityQueue pq = new PriorityQueue<>();\n\n\n\n\t\tcalmax(map , speed , efficiency , pq , k);\n\n\t\treturn teampPerf ;\n\n }\n\n\n\n\tpublic void calmax(int [][]map , int s[] , int e[] , PriorityQueuepq , int k) {\n\n\t\t\n\n\t\tfor (int i = 0 ; i (b[0] == a[0]) ? (a[1] - b[1]) : b[0] - a[0]);\n\n\t\tPriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder());\n\n\t\tpq.offer(0);\n\n\n\n\t\tfor (int i = 0; i < properties.length; i++) {\n\n\t\t\tif (properties[i][1] map = new TreeMap<>();\n\n\t\tfor (int i = 0; i < prerequisites.length; i++) {\n\n\t\t\tif (map.get(prerequisites[i][1])!=null) {\n\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t\t\tmap.put(prerequisites[i][0], prerequisites[i][1]);\n\n\t\t}\n\n\n\n\t\treturn f;\n\n }\n\n\tint n =0;\n\n\t\n\n\tpublic int dfsB(int i , int j , char [][]b , char [][]res) {\n\n\t\tif (i<0||i>=b.length|j<0||j>=b[0].length||res[i][j]=='.') {\n\n\t\t\treturn 0;\n\n\t\t}\n\n\n\n\t\tif (res[i][j]=='X') {\n\n\t\t\treturn 1+dfsB(i+1, j, b, res)+dfsB(i, j+1, b, res);\n\n\t\t}\n\n\n\n\t\treturn 0;\n\n\n\n\t\t\n\n\t}\n\n\t\n\n\t\n\n\t\n\n\t public class ListNode {\n\n\t int val;\n\n\t ListNode next;\n\n\t ListNode() {}\n\n\t ListNode(int val) { this.val = val; }\n\n\t ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n\n\t }\n\n\t public ListNode middleNode(ListNode head) {\n\n ListNode mid = head;\n\n\t\tListNode last = head;\n\n\t\tint k =0;\n\n\t\twhile (last.next!=null&&last.next.next!=null) {\n\n\t\t\tk++;\n\n\t\t\tmid= mid.next;\n\n\t\t\tlast = last.next.next;\n\n\t\t}\n\n\n\n\t\tif (getLen(head)%2==0) {\n\n\t\t\treturn mid.next;\n\n\t\t}\n\n\t\treturn mid;\n\n }\n\n\tpublic int getLen(ListNode mid) {\n\n\t\tint l = 0;\n\n\t\tListNode p = mid;\n\n\t\twhile (p!=null) {\n\n\t\t\tl++;\n\n\t\t\tp=p.next;\n\n\t\t}\n\n\t\treturn l;\n\n\t}\n\n\tpublic class TreeNode {\n\n\t\tint val;\n\n\t\t TreeNode left;\n\n\t\t TreeNode right;\n\n\t\t TreeNode() {}\n\n\t\t TreeNode(int val) { this.val = val; }\n\n\t\t TreeNode(int val, TreeNode left, TreeNode right) {\n\n\t\t this.val = val;\n\n\t\t this.left = left;\n\n\t\t this.right = right;\n\n\t\t }\n\n\t\t }\n\n public List> verticalTraversal(TreeNode root) {\n\n TreeMap>> map = new TreeMap<>();\n\n dfs(root, 0, 0, map);\n\n List> list = new ArrayList<>();\n\n for (TreeMap> ys : map.values()) {\n\n list.add(new ArrayList<>());\n\n for (PriorityQueue nodes : ys.values()) {\n\n while (!nodes.isEmpty()) {\n\n \/\/ list.get(list.size() - 1).add(nodes.poll());\n\n }\n\n }\n\n }\n\n return list;\n\n }\n\n private void dfs(TreeNode root, int x, int y, TreeMap>> map) {\n\n if (root == null) {\n\n return;\n\n }\n\n if (!map.containsKey(x)) {\n\n map.put(x, new TreeMap<>());\n\n }\n\n if (!map.get(x).containsKey(y)) {\n\n map.get(x).put(y, new PriorityQueue<>());\n\n }\n\n map.get(x).get(y).offer(root.val);\n\n dfs(root.left, x - 1, y + 1, map);\n\n dfs(root.right, x + 1, y + 1, map);\n\n }\n\n\n\n\t\n\n\tpublic long pow (int x ,int n ) {\n\n\t\tlong y = 1;\n\n\t\tif (n==0) {\n\n\t\t\treturn y;\n\n\t\t}\n\n\n\n\t\twhile (n>0) {\n\n\t\t\tif (n%2!=0) {\n\n\t\t\t\ty=y*x;\n\n\n\n\t\t\t} \n\n\n\n\t\t\tx*=x;\n\n\t\t\tn\/=2;\n\n\t\t}\n\n\n\n\t\treturn y;\n\n\t}\n\n\tpublic long powrec (int x ,int n ) {\n\n\t\tlong y = 1;\n\n\t\tif (n==0) {\n\n\t\t\treturn y;\n\n\t\t}\n\n\n\n\t\ty = powrec(x, n\/2);\n\n\t\tif (n%2==0) {\n\n\t\t\treturn y*y;\n\n\t\t} \n\n\t\treturn y*y*x;\n\n\t}\n\n\n\n\n\n\tpublic int fib(int n) {\n\n\n\n\t\tif (n==0||n==11) {\n\n\t\t\treturn n;\n\n\t\t}\n\n\n\n\t\treturn fib(n-1)+fib(n-2);\n\n\t}\n\n\n\n\tpublic long gcd(long a , long b)\n\n\t{\n\n\t\tif (b%a==0) {\n\n\t\t\treturn a;\n\n\t\t}\n\n\t\treturn gcd(b%a,a);\n\n\t}\n\n\t\n\n\tpublic int maximumElement(int a[])\n\n\t{\n\n\t\tint x = Integer.MIN_VALUE;\n\n\t\tfor (int i = 0; i < a.length; i++) {\n\n\t\t\t if (a[i]>x) {\n\n\t\t\t\tx=a[i];\n\n\t\t\t }\n\n\n\n\t\t}\n\n\n\n\t\treturn x;\n\n\t}\n\n\n\n\tpublic int minimumElement(int a[])\n\n\t{\n\n\t\tint x = Integer.MAX_VALUE;\n\n\t\tfor (int i = 0; i < a.length; i++) {\n\n\t\t\t if (a[i] > x\n\n = new ArrayList >();\n\n \n\n \/\/ One space allocated for R0\n\n\n\n \/\/ Adding 3 to R0 created above x(R0, C0)\n\n \/\/x.get(0).add(0, 3);\n\n\t\tint xr = 0;\n\n\n\n\t\tfor (int i = 1; i <= n; i+=2) {\n\n\t\t\tif ((i+k)*(i+1)%4==0) {\n\n\t\t\t\tx.add(new ArrayList());\n\n\t\t\t\tx.get(xr).addAll(Arrays.asList(i , i+1));\n\n\n\n\t\t\t} \n\n\t\t\telse {\n\n\t\t\t\tx.add(new ArrayList());\n\n\t\t\t\tx.get(xr).addAll(Arrays.asList(i+1 , i));\n\n\t\t\t}\n\n\t\t\txr++;\n\n\t\t}\n\n \n\n \/\/ Creating R1 and adding values\n\n \/\/ Note: Another way for adding values in 2D\n\n \/\/ collections\n\n \/\/ x.add(\n\n \/\/ new ArrayList(Arrays.asList(3, 4, 6)));\n\n \n\n \/\/ \/\/ Adding 366 to x(R1, C0)\n\n \/\/ x.get(1).add(0, 366);\n\n \n\n \/\/ \/\/ Adding 576 to x(R1, C4)\n\n \/\/ x.get(1).add(4, 576);\n\n \n\n \/\/ \/\/ Now, adding values to R2\n\n \/\/ x.add(2, new ArrayList<>(Arrays.asList(3, 84)));\n\n \n\n \/\/ \/\/ Adding values to R3\n\n \/\/ x.add(new ArrayList(\n\n \/\/ Arrays.asList(83, 6684, 776)));\n\n \n\n \/\/ \/\/ Adding values to R4\n\n \/\/ x.add(new ArrayList<>(Arrays.asList(8)));\n\n \n\n \/\/ \/\/ Appending values to R4\n\n \/\/ x.get(4).addAll(Arrays.asList(9, 10, 11));\n\n \n\n \/\/ \/\/ Appending values to R1, but start appending from\n\n \/\/ \/\/ C3\n\n \/\/ x.get(1).addAll(3, Arrays.asList(22, 1000));\n\n \n\n \/\/ This method will return 2D array\n\n return x;\n\n }\n\n \n\n\t\n\n}\n\n\n\nclass FlashFastReader\n\n{\n\n\tBufferedReader in;\n\n\tStringTokenizer token;\n\n\t\n\n\tpublic FlashFastReader(InputStream ins)\n\n\t{\n\n\t\tin=new BufferedReader(new InputStreamReader(ins));\n\n\t\ttoken=new StringTokenizer(\"\");\n\n\t}\n\n \n\n\tpublic boolean hasNext()\n\n\t{\n\n\t\twhile (!token.hasMoreTokens())\n\n\t\t{\n\n\t\t\ttry\n\n\t\t\t{\n\n\t\t\t\tString s = in.readLine();\n\n\t\t\t\tif (s == null) return false;\n\n\t\t\t\ttoken = new StringTokenizer(s);\n\n\t\t\t} catch (IOException e)\n\n\t\t\t{\n\n\t\t\t\tthrow new InputMismatchException();\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n \n\n\tpublic String next()\n\n\t{\n\n\t\thasNext();\n\n\t\treturn token.nextToken();\n\n\t}\n\n \n\n\tpublic int nextInt()\n\n\t{\n\n\t\treturn Integer.parseInt(next());\n\n\t}\n\n \n\n\tpublic int[] nextIntsInputAsArray(int n)\n\n\t{\n\n\t\tint[] res = new int[n];\n\n\t\tfor (int i = 0; i < n; i++)\n\n\t\t\tres[i] = nextInt();\n\n\t\treturn res;\n\n\t}\n\n \n\n\tpublic long nextLong() {\n\n\t\treturn Long.parseLong(next());\n\n\t}\t\n\n\n\n\tpublic long[] nextLongsInputAsArray(int n)\n\n\t{\n\n\t\tlong [] a = new long[n];\n\n\t\tfor (int i = 0; i < n; i++)\n\n\t\t\ta[i] = nextLong();\n\n\t\treturn a;\n\n\t}\n\n\n\n\tpublic String nextString() {\n\n\n\n\t\treturn String.valueOf(next());\n\n\t}\t\n\n\n\n\tpublic String[] nextStringsInputAsArray(int n)\n\n\t{\n\n\t\tString [] a = new String[n];\n\n\t\tfor (int i = 0; i < n; i++)\n\n\t\t\ta[i] = nextString();\n\n\t\treturn a;\n\n\t}\n\n\t\n\n}\n\n\n\n\n\n \n\n\n\n \n\n\n\n","language":"java"} -{"contest_id":"1141","problem_id":"E","statement":"E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,\u2026,dnd1,d2,\u2026,dn (\u2212106\u2264di\u2264106\u2212106\u2264di\u2264106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1\u2264H\u226410121\u2264H\u22641012, 1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105). The second line contains the sequence of integers d1,d2,\u2026,dnd1,d2,\u2026,dn (\u2212106\u2264di\u2264106\u2212106\u2264di\u2264106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6\n-100 -200 -300 125 77 -4\nOutputCopy9\nInputCopy1000000000000 5\n-1 0 0 0 0\nOutputCopy4999999999996\nInputCopy10 4\n-3 -6 5 4\nOutputCopy-1\n","tags":["math"],"code":"\/\/package superherobattle;\n\n\n\nimport java.util.*;\n\nimport java.io.*;\n\n\n\npublic class superherobattle {\n\n\tpublic static void main(String[] args) throws IOException {\n\n\t\tBufferedReader fin = new BufferedReader(new InputStreamReader(System.in));\n\n\t\tStringTokenizer st = new StringTokenizer(fin.readLine());\n\n\t\tlong h = Long.parseLong(st.nextToken());\n\n\t\tint n = Integer.parseInt(st.nextToken());\n\n\t\tst = new StringTokenizer(fin.readLine());\n\n\t\tlong[] nums = new long[n];\n\n\t\tfor(int i = 0; i < n; i++) {\n\n\t\t\tnums[i] = Long.parseLong(st.nextToken());\n\n\t\t}\n\n\t\tlong[] pfxMin = new long[n];\n\n\t\tlong min = Integer.MAX_VALUE;\n\n\t\tfor(int i = 0; i < n; i++) {\n\n\t\t\tif(i == 0) {\n\n\t\t\t\tpfxMin[0] = nums[0];\n\n\t\t\t}\n\n\t\t\telse {\n\n\t\t\t\tpfxMin[i] = pfxMin[i - 1] + nums[i];\n\n\t\t\t}\n\n\t\t\tmin = Math.min(min, pfxMin[i]);\n\n\t\t}\n\n\t\tlong diff = pfxMin[n - 1];\n\n\t\tif(diff >= 0) {\n\n\t\t\tif(h + min <= 0) {\n\n\t\t\t\tlong ans = 0;\n\n\t\t\t\tfor(int i = 0; i < n; i++) {\n\n\t\t\t\t\tans ++;\n\n\t\t\t\t\tif(h + pfxMin[i] <= 0) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tSystem.out.println(ans);\n\n\t\t\t}\n\n\t\t\telse {\n\n\t\t\t\tSystem.out.println(\"-1\");\n\n\t\t\t}\n\n\t\t}\n\n\t\telse {\n\n\t\t\tlong ans = 0;\n\n\t\t\tif(h + min > 0) {\n\n\t\t\t\tlong toMin = h + min;\n\n\t\t\t\tlong cycles = Math.abs(Math.abs(toMin \/ diff) + (toMin % diff != 0? 1 : 0));\n\n\t\t\t\tans += cycles * n;\n\n\t\t\t\t\/\/System.out.println(cycles);\n\n\t\t\t\th += cycles * diff;\n\n\t\t\t}\n\n\t\t\t\n\n\t\t\t\/\/System.out.println(h);\n\n\t\t\tif(h > 0) {\n\n\t\t\t\tfor(int i = 0; i < n; i++) {\n\n\t\t\t\t\tans ++;\n\n\t\t\t\t\tif(h + pfxMin[i] <= 0) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tSystem.out.println(ans);\n\n\t\t}\n\n\t}\n\n}\n\n","language":"java"} -{"contest_id":"1296","problem_id":"C","statement":"C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x\u22121,y)(x\u22121,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y\u22121)(x,y\u22121). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of \"LURLLR\" are \"LU\", \"LR\", \"LURLLR\", \"URL\", but not \"RR\" and \"UL\".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' \u2014 the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2\u22c51052\u22c5105 (\u2211n\u22642\u22c5105\u2211n\u22642\u22c5105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n \u2014 endpoints of the substring you remove. The value r\u2212l+1r\u2212l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4\n4\nLRUD\n4\nLURD\n5\nRRUDU\n5\nLLDDR\nOutputCopy1 2\n1 4\n3 4\n-1\n","tags":["data structures","implementation"],"code":"import java.io.BufferedReader;\n\nimport java.io.InputStreamReader;\n\nimport java.util.HashMap;\n\nimport java.util.Objects;\n\n\n\npublic class YetAnotherWalkingRobot {\n\n static BufferedReader br;\n\n\n\n public static void main(String[] args) throws Exception {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n int t = Integer.parseInt(br.readLine());\n\n for (int i = 0; i < t; i++) test();\n\n }\n\n\n\n static void test() throws Exception {\n\n int n = Integer.parseInt(br.readLine());\n\n String s = br.readLine();\n\n Point p = new Point(0, 0);\n\n HashMap map = new HashMap<>();\n\n map.put(p, 1);\n\n\n\n int[] min = new int[2];\n\n min[0] = -1000000000;\n\n min[1] = 1000000000;\n\n boolean got = false;\n\n for (int i = 0; i < n; i++) {\n\n p = new Point(p.x, p.y);\n\n if (s.charAt(i) == 'L') p.x--;\n\n else if (s.charAt(i) == 'R') p.x++;\n\n else if (s.charAt(i) == 'U') p.y++;\n\n else p.y--;\n\n\n\n if (map.containsKey(p)) {\n\n int start = map.get(p);\n\n int minDist = min[1] - min[0];\n\n int dist = (i + 1) - start;\n\n\n\n if (dist < minDist) {\n\n min[1] = (i + 1);\n\n min[0] = start;\n\n got = true;\n\n }\n\n map.put(p, i + 2);\n\n } else map.put(p, i + 2);\n\n }\n\n if (got) System.out.println(min[0] + \" \" + min[1]);\n\n else System.out.println(-1);\n\n }\n\n\n\n static class Point {\n\n public long x, y;\n\n public Point(long x, long y) {\n\n this.x = x;\n\n this.y = y;\n\n }\n\n\n\n @Override\n\n public boolean equals(Object o) {\n\n if (this == o) return true;\n\n if (o == null || getClass() != o.getClass()) return false;\n\n Point point = (Point) o;\n\n return x == point.x && y == point.y;\n\n }\n\n\n\n @Override\n\n public int hashCode() {\n\n return Objects.hash(x, y);\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1296","problem_id":"C","statement":"C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x\u22121,y)(x\u22121,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y\u22121)(x,y\u22121). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of \"LURLLR\" are \"LU\", \"LR\", \"LURLLR\", \"URL\", but not \"RR\" and \"UL\".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' \u2014 the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2\u22c51052\u22c5105 (\u2211n\u22642\u22c5105\u2211n\u22642\u22c5105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n \u2014 endpoints of the substring you remove. The value r\u2212l+1r\u2212l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4\n4\nLRUD\n4\nLURD\n5\nRRUDU\n5\nLLDDR\nOutputCopy1 2\n1 4\n3 4\n-1\n","tags":["data structures","implementation"],"code":"import java.io.*;\n\nimport java.util.*;\n\n \n\npublic class ProblemB {\n\n \n\n\tpublic static void main(String[] args) throws Exception {\n\n\t\tScanner s = new Scanner();\n\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tint test = s.readInt();\n\n\t\twhile(test-->0){\n\n\t\t\tint n = s.readInt();\n\n\t\t\tString ss = s.readLine();\n\n\t\t\t\n\n\t\t\tint x =0,y = 0;\n\n\t\t\tString pos = x+\" \"+y;\n\n\t\t\tHashMapmap = new HashMap<>();\n\n\t\t\tString ans = \"\";\n\n\t\t\tint min = Integer.MAX_VALUE;\n\n\t\t\tmap.put(pos, -1);\n\n\t\t\tfor(int i = 0;i0){\n\n \n\n int n,m;\n\n n = in.nextInt();\n\n m = in.nextInt();\n\n \n\n if(n==m){\n\n System.out.println(0);\n\n t--;\n\n continue;\n\n }\n\n \n\n HashMap mp1 = new HashMap<>();\n\n HashMap mp2 = new HashMap<>();\n\n \n\n double x2 = Math.sqrt(n);\n\n int val1 = (int)x2;\n\n \n\n for(int i=2;i<=val1;i++){\n\n \n\n while(n%i==0){\n\n n \/= i;\n\n if(mp1.containsKey(i)){\n\n \n\n int x = mp1.get(i);\n\n mp1.put(i,++x);\n\n }\n\n else{\n\n mp1.put(i,1);\n\n }\n\n }\n\n }\n\n \n\n if(n!=1){\n\n if(mp1.containsKey(n)){\n\n \n\n int x = mp1.get(n);\n\n mp1.put(n,++x);\n\n }\n\n else{\n\n mp1.put(n,1);\n\n }\n\n }\n\n \n\n x2 = Math.sqrt(m);\n\n int val2 = (int)x2;\n\n for(int i=2;i<=val2;i++){\n\n \n\n while(m%i==0){\n\n m \/= i;\n\n if(mp2.containsKey(i)){\n\n \n\n int x = mp2.get(i);\n\n mp2.put(i,++x);\n\n }\n\n else{\n\n mp2.put(i,1);\n\n }\n\n }\n\n }\n\n \n\n if(m!=1){\n\n if(mp2.containsKey(m)){\n\n \n\n int x = mp2.get(m);\n\n mp2.put(m,++x);\n\n }\n\n else{\n\n mp2.put(m,1);\n\n }\n\n }\n\n \n\n Boolean flag = false;\n\n for (Integer key: mp1.keySet()) {\n\n \n\n int value = mp1.get(key);\n\n \n\n if(mp2.containsKey(key)==false){\n\n System.out.println(-1);\n\n flag = true;\n\n break;\n\n }\n\n }\n\n \n\n if(flag==false){\n\n for (Integer key: mp2.keySet()) {\n\n \n\n int value = mp2.get(key);\n\n \n\n if(mp1.containsKey(key)==false && key!=2 && key!=3){\n\n System.out.println(-1);\n\n flag = true;\n\n break;\n\n }\n\n }\n\n }\n\n \n\n if(flag==false){\n\n \n\n val1 = 0;\n\n val2 = 0;\n\n if(mp1.containsKey(2)){\n\n val1 = mp1.get(2);\n\n }\n\n if(mp2.containsKey(2)){\n\n int x = mp2.get(2);\n\n val1 = x - val1;\n\n }\n\n if(mp1.containsKey(3)){\n\n val2 = mp1.get(3);\n\n }\n\n if(mp2.containsKey(3)){\n\n int x = mp2.get(3);\n\n val2 = x - val2;\n\n }\n\n \n\n if(mp1.containsKey(2)==true && mp2.containsKey(2)==false){\n\n System.out.println(-1);\n\n }\n\n else if(mp1.containsKey(3)==true && mp2.containsKey(3)==false){\n\n System.out.println(-1);\n\n }\n\n else if(val1<0 || val2<0){\n\n System.out.println(-1);\n\n }\n\n else{\n\n val1 += val2;\n\n System.out.println(val1);\n\n }\n\n }\n\n t--;\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1288","problem_id":"E","statement":"E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,\u2026,n1,2,\u2026,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1\u2264n,m\u22643\u22c51051\u2264n,m\u22643\u22c5105) \u2014 the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,\u2026,ama1,a2,\u2026,am (1\u2264ai\u2264n1\u2264ai\u2264n) \u2014 the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4\n3 5 1 4\nOutputCopy1 3\n2 5\n1 4\n1 5\n1 5\nInputCopy4 3\n1 2 4\nOutputCopy1 3\n1 2\n3 4\n1 4\nNoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3] ","tags":["data structures"],"code":"import java.io.OutputStream;\n\nimport java.io.IOException;\n\nimport java.io.InputStream;\n\nimport java.io.PrintWriter;\n\nimport java.util.Arrays;\n\nimport java.io.IOException;\n\nimport java.util.TreeSet;\n\nimport java.util.ArrayList;\n\nimport java.util.Comparator;\n\nimport java.util.Collections;\n\nimport java.io.InputStream;\n\n\n\n\/**\n\n * Built using CHelper plug-in\n\n * Actual solution is at the top\n\n *\n\n * @author Indrajit Sinha\n\n *\/\n\npublic class Main {\n\n\tpublic static void main(String[] args) {\n\n\t\tInputStream inputStream = System.in;\n\n\t\tOutputStream outputStream = System.out;\n\n\t\tInputReader in = new InputReader(inputStream);\n\n\t\tPrintWriter out = new PrintWriter(outputStream);\n\n\t\tEMessengerSimulator solver = new EMessengerSimulator();\n\n\t\tsolver.solve(1, in, out);\n\n\t\tout.close();\n\n\t}\n\n\n\n\tstatic class EMessengerSimulator {\n\n\t\tint n;\n\n\t\tPrintWriter out;\n\n\t\tInputReader in;\n\n\t\tfinal Comparator com = new Comparator() {\n\n\t\t\tpublic int compare(Query x, Query y) {\n\n\t\t\t\tint xx = Integer.compare(x.r, y.r);\n\n\t\t\t\tif (xx == 0)\n\n\t\t\t\t\treturn Integer.compare(x.l, y.l);\n\n\t\t\t\treturn xx;\n\n\t\t\t}\n\n\t\t};\n\n\n\n\t\tpublic void solve(int testNumber, InputReader in, PrintWriter out) {\n\n\t\t\tint t, i, j, tt, k;\n\n\t\t\tthis.out = out;\n\n\t\t\tthis.in = in;\n\n\t\t\tn = in.nextInt();\n\n\t\t\tint m = in.nextInt();\n\n\t\t\tint a[] = new int[m];\n\n\t\t\tint[] mn, mx;\n\n\t\t\tmn = new int[n];\n\n\t\t\tmx = new int[n];\n\n\t\t\tfor (i = 0; i < n; i++) {\n\n\t\t\t\tmn[i] = i;\n\n\t\t\t\tmx[i] = i;\n\n\t\t\t}\n\n\t\t\tfor (i = 0; i < m; i++) {\n\n\t\t\t\ta[i] = in.nextInt() - 1;\n\n\t\t\t\tmn[a[i]] = 0;\n\n\t\t\t}\n\n\t\t\tArrayList ar[] = new ArrayList[n];\n\n\t\t\tfor (i = 0; i < n; i++) {\n\n\t\t\t\tar[i] = new ArrayList<>();\n\n\t\t\t}\n\n\t\t\tfor (i = 0; i < m; i++) {\n\n\t\t\t\tar[a[i]].add(i);\n\n\t\t\t}\n\n\t\t\tTreeSet ts = new TreeSet<>();\n\n\t\t\tSegmenTree sg = new SegmenTree();\n\n\t\t\tsg.build(n);\n\n\t\t\tfor (i = 0; i < m; i++) {\n\n\t\t\t\tif (ts.contains(a[i]))\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\tmx[a[i]] = Math.max(mx[a[i]], a[i] + sg.query(a[i] + 1, n));\n\n\t\t\t\tts.add(a[i]);\n\n\t\t\t\tsg.updateTreeNode(a[i], 1);\n\n\t\t\t}\n\n\t\t\tfor (i = 0; i < n; i++) {\n\n\t\t\t\tif (ar[i].size() == 0) {\n\n\t\t\t\t\tmx[i] = Math.max(mx[i], i + sg.query(i + 1, n));\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tArrayList queries = new ArrayList<>();\n\n\t\t\tfor (i = 0; i < n; i++) {\n\n\t\t\t\tif (i == 98) {\n\n\t\t\t\t\tint ou = 0;\n\n\t\t\t\t}\n\n\t\t\t\tfor (j = 1; j < ar[i].size(); j++) {\n\n\t\t\t\t\tint l = ar[i].get(j - 1) + 1;\n\n\t\t\t\t\tint r = ar[i].get(j) - 1;\n\n\t\t\t\t\tif (l <= r) {\n\n\t\t\t\t\t\tqueries.add(new Query(l, r, i));\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif (j == ar[i].size() - 1) {\n\n\t\t\t\t\t\tl = ar[i].get(j) + 1;\n\n\t\t\t\t\t\tr = m - 1;\n\n\t\t\t\t\t\tif (l <= r)\n\n\t\t\t\t\t\t\tqueries.add(new Query(l, r, i));\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif (ar[i].size() == 1) {\n\n\t\t\t\t\tint l = ar[i].get(0) + 1;\n\n\t\t\t\t\tint r = m - 1;\n\n\t\t\t\t\tif (l <= r)\n\n\t\t\t\t\t\tqueries.add(new Query(l, r, i));\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tCollections.sort(queries, com);\n\n\t\t\tint bit[] = new int[m + 1];\n\n\t\t\tint last_visit[] = new int[n + 5];\n\n\t\t\tArrays.fill(last_visit, -1);\n\n\t\t\tint query_counter = 0, q = queries.size();\n\n\t\t\tfor (i = 0; i < m; i++) {\n\n\t\t\t\tif (last_visit[a[i]] != -1)\n\n\t\t\t\t\tupdate(last_visit[a[i]] + 1, -1, bit, m);\n\n\t\t\t\tlast_visit[a[i]] = i;\n\n\t\t\t\tupdate(i + 1, 1, bit, m);\n\n\t\t\t\twhile (query_counter < q && queries.get(query_counter).r == i) {\n\n\t\t\t\t\tint an = query(queries.get(query_counter).r + 1, bit, m) - query(queries.get(query_counter).l, bit, m);\n\n\t\t\t\t\tint idx = queries.get(query_counter).idx;\n\n\t\t\t\t\tmx[idx] = Math.max(mx[idx], an);\n\n\t\t\t\t\tquery_counter++;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tfor (i = 0; i < n; i++) {\n\n\t\t\t\tpn((mn[i] + 1) + \" \" + (mx[i] + 1));\n\n\t\t\t}\n\n\n\n\t\t}\n\n\n\n\t\tvoid update(int idx, int val, int bit[], int n) {\n\n\t\t\tfor (; idx <= n; idx += idx & -idx)\n\n\t\t\t\tbit[idx] += val;\n\n\t\t}\n\n\n\n\t\tint query(int idx, int bit[], int n) {\n\n\t\t\tint sum = 0;\n\n\t\t\tfor (; idx > 0; idx -= idx & -idx)\n\n\t\t\t\tsum += bit[idx];\n\n\t\t\treturn sum;\n\n\t\t}\n\n\n\n\t\tvoid pn(String zx) {\n\n\t\t\tout.println(zx);\n\n\t\t}\n\n\n\n\t\tclass Query {\n\n\t\t\tint l;\n\n\t\t\tint r;\n\n\t\t\tint idx;\n\n\n\n\t\t\tQuery(int a, int b, int c) {\n\n\t\t\t\tl = a;\n\n\t\t\t\tr = b;\n\n\t\t\t\tidx = c;\n\n\t\t\t}\n\n\n\n\t\t}\n\n\n\n\t\tclass SegmenTree {\n\n\t\t\tint n;\n\n\t\t\tint[] tree;\n\n\n\n\t\t\tvoid build(int x) {\n\n\t\t\t\tn = x;\n\n\t\t\t\ttree = new int[2 * n + 1];\n\n\t\t\t}\n\n\n\n\t\t\tvoid updateTreeNode(int p, int value) {\n\n\t\t\t\ttree[p + n] = value;\n\n\t\t\t\tp = p + n;\n\n\t\t\t\tfor (int i = p; i > 1; i >>= 1)\n\n\t\t\t\t\ttree[i >> 1] = tree[i] + tree[i ^ 1];\n\n\t\t\t}\n\n\n\n\t\t\tint query(int l, int r) {\n\n\t\t\t\tint res = 0;\n\n\t\t\t\tfor (l += n, r += n; l < r;\n\n\t\t\t\t l >>= 1, r >>= 1) {\n\n\t\t\t\t\tif ((l & 1) > 0)\n\n\t\t\t\t\t\tres += tree[l++];\n\n\n\n\t\t\t\t\tif ((r & 1) > 0)\n\n\t\t\t\t\t\tres += tree[--r];\n\n\t\t\t\t}\n\n\n\n\t\t\t\treturn res;\n\n\t\t\t}\n\n\n\n\t\t}\n\n\n\n\t}\n\n\n\n\tstatic class InputReader {\n\n\t\tprivate InputStream stream;\n\n\t\tprivate byte[] buf = new byte[1024];\n\n\t\tprivate int curChar;\n\n\t\tprivate int numChars;\n\n\n\n\t\tpublic InputReader(InputStream stream) {\n\n\t\t\tthis.stream = stream;\n\n\t\t}\n\n\n\n\t\tpublic int read() {\n\n\t\t\tif (numChars == -1) {\n\n\t\t\t\tthrow new UnknownError();\n\n\t\t\t}\n\n\t\t\tif (curChar >= numChars) {\n\n\t\t\t\tcurChar = 0;\n\n\t\t\t\ttry {\n\n\t\t\t\t\tnumChars = stream.read(buf);\n\n\t\t\t\t} catch (IOException e) {\n\n\t\t\t\t\tthrow new UnknownError();\n\n\t\t\t\t}\n\n\t\t\t\tif (numChars <= 0) {\n\n\t\t\t\t\treturn -1;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn buf[curChar++];\n\n\t\t}\n\n\n\n\t\tpublic int nextInt() {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\n\n\t\tpublic String next() {\n\n\t\t\tint c = read();\n\n\t\t\twhile (isSpaceChar(c)) {\n\n\t\t\t\tc = read();\n\n\t\t\t}\n\n\t\t\tStringBuffer res = new StringBuffer();\n\n\t\t\tdo {\n\n\t\t\t\tres.appendCodePoint(c);\n\n\t\t\t\tc = read();\n\n\t\t\t} while (!isSpaceChar(c));\n\n\n\n\t\t\treturn res.toString();\n\n\t\t}\n\n\n\n\t\tprivate boolean isSpaceChar(int c) {\n\n\t\t\treturn c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n\n\t\t}\n\n\n\n\t}\n\n}\n\n\n\n","language":"java"} -{"contest_id":"1295","problem_id":"D","statement":"D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0\u2264x 1) ans -= ans\/m;\n\n\t\treturn ans;\n\n\t}\n\n\t\n\n\tstatic List p;\n\n\tpublic static void main(String[] args) throws IOException {\n\n\t\t\/\/ br = new BufferedReader(new FileReader(\".in\"));\n\n\t\t\/\/ out = new PrintWriter(new FileWriter(\".out\"));\n\n\t\t\/\/new Thread(null, new (), \"peepee\", 1<<28).start();\n\n\t\t\n\n\t\tboolean[] sieve = new boolean[(int)1e6+20];\n\n\t\tp = new ArrayList();\n\n\t\tfor (int i = 2; i *i <= sieve.length; i++) {\n\n\t\t\tif (!sieve[i]) {\n\n\t\t\t\tfor (int j = i*i; j < sieve.length; j+=i) sieve[j] = false;\n\n\t\t\t}\n\n\t\t}\n\n\t\tfor (int i = 2; i < sieve.length; i++) if (!sieve[i]) p.add((long)i);\n\n\t\t\n\n\/\/\t\tlong a = (long)(Math.random()*1e3+1);\n\n\/\/\t\tlong b = a + (long)(Math.random()*1e2+12);\n\n\/\/\t\tfor (int i = 1; i < 10; i++) {\n\n\/\/\t\t\tlong ta = a*i;\n\n\/\/\t\t\tlong tb = b*i;\n\n\/\/\t\t\tout.println(bf(ta,tb) + \" \" + pp(ta,tb));\n\n\/\/\t\t}\n\n\t\t\n\n\t\treadInput();\n\n\t\tout.close();\n\n\t}\n\n\t\n\n\tstatic void readInput() throws IOException{\n\n\t\tread();\n\n\t\tint t= RI();\n\n\t\twhile(t-->0) {\n\n\t\t\tread();\n\n\t\t\tlong a = RL();\n\n\t\t\tlong m = RL();\n\n\t\t\tout.println(pp(a,m));\n\n\t\t}\n\n\t}\n\n\t\n\n\tstatic BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n\tstatic PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));\n\n\tstatic StringTokenizer st;\n\n\tstatic void read() throws IOException{st = new StringTokenizer(br.readLine());}\t\n\n\tstatic int RI() throws IOException{return Integer.parseInt(st.nextToken());}\n\n\tstatic long RL() throws IOException{return Long.parseLong(st.nextToken());}\n\n\tstatic double RD() throws IOException{return Double.parseDouble(st.nextToken());}\n\n\t\n\n}\n\n","language":"java"} -{"contest_id":"1141","problem_id":"E","statement":"E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,\u2026,dnd1,d2,\u2026,dn (\u2212106\u2264di\u2264106\u2212106\u2264di\u2264106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1\u2264H\u226410121\u2264H\u22641012, 1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105). The second line contains the sequence of integers d1,d2,\u2026,dnd1,d2,\u2026,dn (\u2212106\u2264di\u2264106\u2212106\u2264di\u2264106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6\n-100 -200 -300 125 77 -4\nOutputCopy9\nInputCopy1000000000000 5\n-1 0 0 0 0\nOutputCopy4999999999996\nInputCopy10 4\n-3 -6 5 4\nOutputCopy-1\n","tags":["math"],"code":"import java.util.*;\n\n\n\npublic class Solution\n\n\n\n{\n\n public static void main(String[] args){\n\n Scanner sc=new Scanner(System.in);\n\n long h=sc.nextLong();\n\n int n=sc.nextInt();\n\n long[] ar=new long[n];\n\n long base=h;\n\n int an=0;\n\n int pr=0;\n\n boolean ok=false;\n\n for(int i=0;i=h){\n\n if(ok)System.out.println(pr);\n\n else System.out.println(\"-1\");\n\n }\n\n else{\n\n long b=h;\n\n long max=0;\n\n long ans=0;long extra=0; \n\n long min=0;\n\n ok=true;\n\n long overall=0;\n\n for(int i=0;imax && min<0){\n\n max=Math.abs(min);\n\n extra=i+1;\n\n }\n\n if(b<=0 && ok){ok=false;break;}\n\n \n\n }\n\n if(!ok)System.out.println(ans);\n\n else{\n\n long rem=b-max;\n\n overall=Math.abs(overall);\n\n if(rem<=0){\n\n while(true){\n\n for(int i=0;i h = new HashMap<>();\n\n for (int i = 2; i * i <= n; i++) {\n\n if (temp % i == 0) {\n\n int c = 0;\n\n while (temp % i == 0) {\n\n c++;\n\n temp \/= i;\n\n }\n\n h.put(i, c);\n\n }\n\n }\n\n if (temp != 1)\n\n h.put(temp, 1);\n\n\n\n }\n\n\n\n static void reverseArray(int a[]) {\n\n int n = a.length;\n\n for (int i = 0; i < n \/ 2; i++) {\n\n a[i] = a[i] ^ a[n - i - 1];\n\n a[n - i - 1] = a[i] ^ a[n - i - 1];\n\n a[i] = a[i] ^ a[n - i - 1];\n\n\n\n }\n\n }\n\n\n\n static void sort(int[] a) {\n\n ArrayList l = new ArrayList<>();\n\n for (int i : a) l.add(i);\n\n Collections.sort(l);\n\n for (int i = 0; i < a.length; i++) a[i] = l.get(i);\n\n }\n\n\n\n static void sort(long[] a) {\n\n ArrayList l = new ArrayList<>();\n\n for (long i : a) l.add(i);\n\n Collections.sort(l);\n\n for (int i = 0; i < a.length; i++) a[i] = l.get(i);\n\n }\n\n\n\n static int min(int a, int b) {\n\n return a < b ? a : b;\n\n }\n\n\n\n static int max(int a, int b) {\n\n return a < b ? a : b;\n\n }\n\n\n\n static long maxSum(int arr[], int n, int k) {\n\n long res = 0;\n\n for (int i = 0; i < k; i++)\n\n res += arr[i];\n\n\n\n\n\n long curr_sum = res;\n\n for (int i = k; i < n; i++) {\n\n curr_sum += arr[i] - arr[i - k];\n\n res = Math.max(res, curr_sum);\n\n }\n\n\n\n return res;\n\n }\n\n\n\n static boolean check(int n,int k,char s[],StringBuffer max[])\n\n {\n\n StringBuffer sa=new StringBuffer();\n\n for(int i=k-1;i=0;i--)\n\n sa.append(s[i]);\n\n }\n\n else \/\/ans==3\n\n {\n\n for(int i=0;i 0) {\n\n int n = sc.nextInt();\n\n String s1 = sc.next();\n\n char s[] = s1.toCharArray();\n\n StringBuffer max[]=new StringBuffer[1];\n\n max[0]=new StringBuffer(s1);\n\n int ans1=1;\n\n for (int k = 2; k <= n; k++)\n\n {\n\n if(check(n,k,s,max))\n\n {\n\n ans1=k;\n\n }\n\n }\n\n out.println(max[0]);\n\n out.println(ans1);\n\n }\n\n out.close();\n\n }\n\n}\n\n \/* public static void main(String args[]) throws IOException {\n\n Fast sc = new Fast();\n\n PrintWriter out = new PrintWriter(System.out);\n\n int t1 = sc.nextInt();\n\n while (t1-- > 0) {\n\n int n=sc.nextInt();\n\n String s1=sc.next();\n\n char s[]=s1.toCharArray();\n\n TreeMap> tm=new TreeMap<>();\n\n for(int i=0;i ts1=new TreeSet<>();\n\n ts1.add(i);\n\n tm.put(ch-97,ts1);\n\n }\n\n else\n\n {\n\n TreeSet ts1=tm.get(ch-97);\n\n ts1.add(i); tm.put(ch-97,ts1);\n\n }\n\n }\n\n\n\n TreeSet ts1=null;\n\n for(Map.Entry> en:tm.entrySet())\n\n {\n\n ts1=en.getValue();\n\n break;\n\n }\n\n\n\n\n\n if(ts1.size()==1)\n\n {\n\n int ans=ts1.first()+1;\n\n String sa=\"\";\n\n for(int i=ans-1;i=0;i--)\n\n sa+=s[i];\n\n }\n\n else \/\/ans==3\n\n {\n\n for(int i=0;is[ne-1])\n\n {\n\n comp=s[ne-1];\n\n ans=ne+1;\n\n }\n\n }\n\n }\n\n String sa=\"\";\n\n for(int i=ans-1;i=0;i--)\n\n sa+=s[i];\n\n }\n\n else \/\/ans==3\n\n {\n\n for(int i=0;i map = new HashMap<>();\n int p = 0, pre = 0, finished = 0;\n for (int[] kk : ns){\n if (!map.containsKey(kk[0])){\n map.put(kk[0], new Node(kk[0]));\n }\n map.get(kk[0]).st.add(p);\n if (!map.containsKey(kk[1]+1)){\n map.put(kk[1]+1, new Node(kk[1]+1));\n }\n map.get(kk[1]+1).en.add(p++);\n }\n Node[] nds = new Node[map.size()];\n p = 0;\n for (Node nd : map.values()){\n nds[p++] = nd;\n }\n Arrays.sort(nds);\n final int ks = 1<>1];\n }\n for (int i=0;i 0) {\n t += dp[i - 1][j - (j & added)];\n }\n dp[i][j - (j & finished)] = Math.max(dp[i][j - (j & finished)], t);\n }\n }\n }\n return dp[dp.length-2][0];\n }\n\n static class Node implements Comparable{\n int start;\n ArrayList st;\n ArrayList en;\n public Node(int a){\n start = a;\n st = new ArrayList<>(4);\n en = new ArrayList<>(4);\n }\n @Override\n public int compareTo(Node nd){\n return this.start - nd.start;\n }\n }\n}\n","language":"java"} -{"contest_id":"1311","problem_id":"A","statement":"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\u2212ya\u2212y. 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\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1\u2264a,b\u22641091\u2264a,b\u2264109).OutputFor each test case, print the answer \u2014 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\n2 3\n10 10\n2 4\n7 4\n9 3\nOutputCopy1\n0\n2\n2\n1\nNoteIn 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.","tags":["greedy","implementation","math"],"code":"import java.util.*;\n\npublic class Main\n\n{\n\n\tpublic static void main(String[] args) {\n\n\t\t\n\n\t\tScanner sc=new Scanner(System.in);\n\n\t\tint t=sc.nextInt();\n\n\t\twhile(t--!=0){\n\n\t\t int a=sc.nextInt();\n\n\t\t int b=sc.nextInt();\n\n\t\t int ans=0;\n\n\t\t boolean p=true;\n\n\t\t if(a==b){\n\n\t\t p=false;\n\n\t\t System.out.println(0);\n\n\t\t }\n\n\t\t else if(a>b){\n\n\t\t int d=a-b;\n\n\t\t ans++;\n\n\t\t if(d%2!=0){\n\n\t\t ans+=1;\n\n\t\t }\n\n\t\t }\n\n\t\t else{\n\n\t\t int d=b-a;\n\n\t\t ans++;\n\n\t\t if(d%2!=1){\n\n\t\t ans++;\n\n\t\t }\n\n\t\t }\n\n\t\t if(p==true){\n\n\t\t System.out.println(ans);\n\n\t\t }\n\n\t\t \n\n\t\t}\n\n\t}\n\n}","language":"java"} -{"contest_id":"1316","problem_id":"E","statement":"E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him\u00a0\u2014 the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j \u00a0\u2014 the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2\u2264n\u2264105,1\u2264p\u22647,1\u2264k,p+k\u2264n2\u2264n\u2264105,1\u2264p\u22647,1\u2264k,p+k\u2264n).The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an. (1\u2264ai\u22641091\u2264ai\u2264109).The ii-th of the next nn lines contains pp integers si,1,si,2,\u2026,si,psi,1,si,2,\u2026,si,p. (1\u2264si,j\u22641091\u2264si,j\u2264109)OutputPrint a single integer resres \u00a0\u2014 the maximum possible strength of the club.ExamplesInputCopy4 1 2\n1 16 10 3\n18\n19\n13\n15\nOutputCopy44\nInputCopy6 2 3\n78 93 9 17 13 78\n80 97\n30 52\n26 17\n56 68\n60 36\n84 55\nOutputCopy377\nInputCopy3 2 1\n500 498 564\n100002 3\n422332 2\n232323 1\nOutputCopy422899\nNoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.","tags":["bitmasks","dp","greedy","sortings"],"code":"import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.Arrays;\nimport java.util.StringTokenizer;\n\npublic class teambuilding {\n\n static class Node implements Comparable{\n int ind;\n int v;\n Node(int ind, int v){\n this.ind = ind;\n this.v = v;\n }\n public int compareTo(Node s){\n if(v != s.v) return s.v - v;\n return ind - s.ind;\n }\n }\n\n public static void main(String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n StringTokenizer st = new StringTokenizer(br.readLine());\n int n = Integer.parseInt(st.nextToken()), p = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken());\n Node[] ar = new Node[n];\n st = new StringTokenizer(br.readLine());\n for (int i = 0; i < n; i++) ar[i] = new Node(i, Integer.parseInt(st.nextToken()));\n long[][] vs = new long[n][p];\n for (int i = 0; i < n; i++) {\n st = new StringTokenizer(br.readLine());\n for (int j = 0; j < p; j++) {\n vs[i][j] = Long.parseLong(st.nextToken());\n }\n }\n Arrays.sort(ar);\n long[][] dp = new long[(1 << p)][n];\n for (int i = 0; i < (1 << p); i++) for (int j = 0; j < n; j++) dp[i][j] = -1;\n dp[0][0] = ar[0].v;\n for (int i = 0; i < p; i++) dp[(1 << i)][0] = vs[ar[0].ind][i];\n for (int i = 1; i < n; i++) {\n for (int j = 0; j < (1 << p); j++) {\n if(dp[j][i - 1] == -1) continue;\n int onecount = Integer.bitCount(j);\n\/\/ System.out.println(j + \" \" + onecount);\n if(k - (i - onecount + 1) >= 0){\n dp[j][i] = Math.max(dp[j][i - 1] + ar[i].v, dp[j][i]);\n } else {\n dp[j][i] = Math.max(dp[j][i], dp[j][i - 1]);\n }\n for (int l = 0; l < p; l++) {\n \/\/i is the current one to choose, j is the bitmask, l is the position\n if((j >> l) % 2 == 1) continue;\n dp[(j | (1 << l))][i] = Math.max(dp[j][i - 1] + vs[ar[i].ind][l], dp[(j | (1 << l))][i]);\n }\n }\n }\n System.out.println(dp[(1 << p) - 1][n - 1]);\n }\n}\n","language":"java"} -{"contest_id":"1324","problem_id":"D","statement":"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 (ibi+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\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the number of topics.The second line of the input contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u22641091\u2264bi\u2264109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer \u2014 the number of good pairs of topic.ExamplesInputCopy5\n4 8 2 6 2\n4 5 4 1 3\nOutputCopy7\nInputCopy4\n1 3 2 4\n1 3 2 4\nOutputCopy0\n","tags":["binary search","data structures","sortings","two pointers"],"code":"import java.util.*;\n\nimport java.io.*;\n\nimport java.math.BigInteger;\n\n\n\npublic class CODE {\n\n public static class pair implements Comparable {\n\n int x;\n\n int y;\n\n\n\n public pair(int par1, int par2) {\n\n x = par1;\n\n y = par2;\n\n }\n\n\n\n @Override\n\n public int compareTo(pair p) {\n\n return x - p.x;\n\n }\n\n\n\n @Override\n\n public String toString() {\n\n return +x + \" \" + y;\n\n }\n\n\n\n }\n\n\n\n static long mod = (long) (1e9 + 7);\n\n\n\n public static long facn(long n, long x) {\n\n long ans = 1;\n\n for (int i = 1; i <= x; i++) {\n\n ans *= n;\n\n ans %= mod;\n\n n--;\n\n }\n\n long k = 1;\n\n long t = x;\n\n for (int i = 1; i <= t; i++) {\n\n k *= x;\n\n k %= mod;\n\n x--;\n\n }\n\n\/\/ BigInteger b = BigInteger.valueOf((k)).modInverse(BigInteger.valueOf((mod)));\n\n long b = modPow(k, mod - 2, mod);\n\n return ((b % mod) * ans) % mod;\n\n\n\n }\n\n\n\n public static long modInverse(long a, long m) {\n\n a = a % m;\n\n for (int x = 1; x < m; x++)\n\n if ((a * x) % m == 1)\n\n return x;\n\n return 1;\n\n }\n\n\n\n static long modPow(long a, long e, long mod) { \/\/ O(log e)\n\n a %= mod;\n\n long res = 1;\n\n while (e > 0) {\n\n if ((e & 1) == 1)\n\n res = (res * a) % mod;\n\n a = (a * a) % mod;\n\n e >>= 1;\n\n }\n\n return res % mod;\n\n }\n\n\n\n public static void bb(Serializable s) {\n\n System.out.println(55);\n\n }\n\n\n\n public static int dfs(int u) {\n\n vis[u] = true;\n\n rank[u] = rnk;\n\n int ans = 1;\n\n for (int v : adj[u])\n\n if (!vis[v])\n\n ans += dfs(v);\n\n\n\n return ans;\n\n }\n\n\n\n public static void dfsD(int u) {\n\n dist[u] = dst;\n\n for (int v : adj[u])\n\n if (dist[v] == -1)\n\n dfsD(v);\n\n }\n\n\n\n static ArrayList[] adj, adj2;\n\n static int n, m, k, rnk, dst;\n\n static boolean[] vis;\n\n static int[] dist, rank;\n\n\n\n public static String rev(String str) {\n\n StringBuilder sb = new StringBuilder();\n\n for (int i = str.length() - 1; i >= 0; i--)\n\n sb.append(str.charAt(i));\n\n \/\/ System.out.println(sb);\n\n return sb.toString();\n\n }\n\n\n\n static PriorityQueue pq;\n\n static int p;\n\n static int[][] Matrix;\n\n static long[][] memo;\n\n static pair[] Arr;\n\n\n\n\/\/ public static long dp(int idx, int mask) {\n\n\/\/ int k=idx-Integer.bitCount(mask);\n\n\/\/ if (k==0&&Integer.bitCount(mask)==p)\n\n\/\/ return 0;\n\n\/\/ long ans = 0;\n\n\/\/ if (memo[mask][idx] != -1)\n\n\/\/ return memo[mask][idx];\n\n\/\/ if (kk > 0)\n\n\/\/ ans = Math.max(ans, Arr[k+p-kk - pp].y + dp(kk - 1, pp, mask));\n\n\/\/ if (pp > 0)\n\n\/\/ for (int i = 0; i < p; i++)\n\n\/\/ if ((mask & (1 << i)) == 0)\n\n\/\/ ans = Math.max(Matrix[Arr[k+p-kk - pp].x][i] + dp(kk, pp - 1, mask | 1 << i), ans);\n\n\/\/\n\n\/\/ return memo[mask][pp][kk] = ans;\n\n\/\/ }\n\n\n\n public static void main(String[] args) throws IOException {\n\n try {\n\n System.setIn(new FileInputStream(\"input.txt\"));\n\n System.setOut(new PrintStream(new FileOutputStream(\"output.txt\")));\n\n } catch (Exception e) {\n\n System.err.println(\"Error\");\n\n }\n\n\n\n\n\n Scanner sc = new Scanner(System.in);\n\n PrintWriter pw = new PrintWriter(System.out);\n\n\n\n int n = sc.nextInt();\n\n Long[]Arr = new Long[n];\n\n for (int i = 0; i < n; i++)Arr[i] = sc.nextLong();\n\n for (int i = 0; i < n; i++)Arr[i] -= sc.nextLong();\n\n Arrays.sort(Arr);\n\n long sum = 0;\n\n for (int i = 0; i < n; i++) {\n\n int lo = 0;\n\n int hi = n - 1;\n\n int mid = n;\n\n int ans = n;\n\n while (hi >= lo) {\n\n mid = (lo + hi) \/ 2;\n\n if (Arr[i] + Arr[mid] > 0) {\n\n ans = mid;\n\n hi = mid - 1;\n\n } else {\n\n lo = mid + 1;\n\n }\n\n }\n\n sum += n - ans;\n\n }\n\n for (int i = 0; i < n; i++) {\n\n if (Arr[i] > 0)sum--;\n\n }\n\n pw.println(sum \/ 2);\n\n\n\n\n\n\n\n\n\n pw.close();\n\n }\n\n \/*Scanner sc = new Scanner(System.in);\n\n PrintWriter pw = new PrintWriter(System.out);\n\n int t=sc.nextInt();\n\n while(t-->0) {\n\n int n=sc.nextInt();\n\n int[]Arr=new int [n];\n\n for(int i=0;i=lo) {\n\n mid=(lo+hi)\/2;\n\n\n\n }\n\n }\n\n\n\n }\n\n\n\n\n\n\n\n pw.close();*\/\n\n public static class trie {\n\n trie[] arr;\n\n int isLeaf;\n\n int freq;\n\n\n\n public trie() {\n\n super();\n\n this.arr = new trie[26];\n\n this.isLeaf = 0;\n\n this.freq = 0;\n\n }\n\n\n\n public void add(String str) {\n\n add(str, 0);\n\n }\n\n\n\n private void add(String str, int idx) {\n\n if (idx == str.length()) {\n\n isLeaf++;\n\n return;\n\n }\n\n int x = str.charAt(idx) - 'a';\n\n\n\n if (arr[x] == null)\n\n arr[x] = new trie();\n\n arr[x].freq++;\n\n arr[x].add(str, idx + 1);\n\n }\n\n\n\n public int numOfPref(String str) {\n\n return numOfPref(str, 0);\n\n }\n\n\n\n private int numOfPref(String str, int idx) {\n\n if (idx == str.length())\n\n return freq;\n\n\n\n int x = str.charAt(idx) - 'a';\n\n\n\n if (arr[x] == null)\n\n return 0;\n\n return arr[x].numOfPref(str, idx + 1);\n\n }\n\n\n\n public int numofStr(String str) {\n\n return numOfStr(str, 0);\n\n }\n\n\n\n private int numOfStr(String str, int idx) {\n\n if (idx == str.length())\n\n return isLeaf;\n\n\n\n int x = str.charAt(idx) - 'a';\n\n\n\n if (arr[x] == null)\n\n return 0;\n\n return arr[x].numOfStr(str, idx + 1);\n\n }\n\n\n\n public boolean contains(String str) {\n\n return numofStr(str) != 0;\n\n }\n\n\n\n public boolean containsPref(String str) {\n\n return numOfPref(str) != 0;\n\n }\n\n }\n\n\n\n public static class Scanner {\n\n StringTokenizer st;\n\n BufferedReader br;\n\n\n\n public Scanner(InputStream s) {\n\n br = new BufferedReader(new InputStreamReader(s));\n\n }\n\n\n\n public String next() throws IOException {\n\n while (st == null || !st.hasMoreTokens())\n\n st = new StringTokenizer(br.readLine());\n\n return st.nextToken();\n\n }\n\n\n\n public int nextInt() throws IOException {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n public long nextLong() throws IOException {\n\n return Long.parseLong(next());\n\n }\n\n\n\n public String nextLine() throws IOException {\n\n return br.readLine();\n\n }\n\n\n\n public double nextDouble() throws IOException {\n\n String x = next();\n\n StringBuilder sb = new StringBuilder(\"0\");\n\n double res = 0, f = 1;\n\n boolean dec = false, neg = false;\n\n int start = 0;\n\n if (x.charAt(0) == '-') {\n\n neg = true;\n\n start++;\n\n }\n\n for (int i = start; i < x.length(); i++)\n\n if (x.charAt(i) == '.') {\n\n res = Long.parseLong(sb.toString());\n\n sb = new StringBuilder(\"0\");\n\n dec = true;\n\n } else {\n\n sb.append(x.charAt(i));\n\n if (dec)\n\n f *= 10;\n\n }\n\n res += Long.parseLong(sb.toString()) \/ f;\n\n return res * (neg ? -1 : 1);\n\n }\n\n\n\n public boolean ready() throws IOException, IOException {\n\n return br.ready();\n\n }\n\n\n\n }\n\n}","language":"java"} -{"contest_id":"1141","problem_id":"A","statement":"A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays \"Game 23\". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1\u2264n\u2264m\u22645\u22c51081\u2264n\u2264m\u22645\u22c5108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840\nOutputCopy7\nInputCopy42 42\nOutputCopy0\nInputCopy48 72\nOutputCopy-1\nNoteIn the first example; the possible sequence of moves is: 120\u2192240\u2192720\u21921440\u21924320\u219212960\u219225920\u219251840.120\u2192240\u2192720\u21921440\u21924320\u219212960\u219225920\u219251840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.","tags":["implementation","math"],"code":"import java.util.*;\nimport static java.lang.System.out;\n\npublic class Main {\n static Scanner sc;\n\n public static void main(String[] args) {\n sc = new Scanner(System.in);\n\n\n\/\/ int t = sc.nextInt();\n\/\/ for(int __ = 0; __ < t; __++){\n var n = sc.nextLong();\n var m = sc.nextLong();\n if(m % n != 0) out.println(-1);\n else{\n m \/= n;\n int c = 0;\n while((m & 1) == 0) {\n m >>= 1;\n c++;\n }\n while( m % 3 == 0) {\n m \/= 3;\n c++;\n }\n if(m != 1) out.println(-1);\n else out.println(c);\n }\n\n \/\/}\n\n\n\n sc.close();\n }\n\n public static int[] intar(int n){\n var f = new int[n];\n for(int i = 0; i < n; i++) f [i] = sc.nextInt();\n return f;\n }\n\n public static void outintar(int[] a, String d){\n out.print(a[0]);\n for(int i = 1; i < a.length; i++)\n {\n out.print(\" \");\n out.print(a[i]);\n }\n out.println();\n }\n}\n\n","language":"java"} -{"contest_id":"1310","problem_id":"C","statement":"C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string ss written on its side. This part of the office is supposed to be split into mm meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of ss written on its side.For each possible arrangement of mm meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kkth label of the delivery?InputIn the first line, you are given three integer numbers n,m,kn,m,k\u00a0\u2014 length of string ss, number of planned meeting rooms to split ss into and number of the interesting label (2\u2264n\u22641000;1\u2264m\u22641000;1\u2264k\u226410182\u2264n\u22641000;1\u2264m\u22641000;1\u2264k\u22641018).Second input line has string ss, consisting of nn lowercase english letters.For given n,m,kn,m,k there are at least kk ways to split ss into mm substrings.OutputOutput single string \u2013 name of meeting room printed on kk-th label of the delivery.ExamplesInputCopy4 2 1\nabac\nOutputCopyaba\nInputCopy19 5 1821\naupontrougevkoffice\nOutputCopyau\nNoteIn the first example; delivery consists of the labels \"aba\"; \"ab\"; \"a\".In the second example; delivery consists of 30603060 labels. The first label is \"aupontrougevkof\" and the last one is \"a\".","tags":["binary search","dp","strings"],"code":"import java.io.BufferedOutputStream;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.io.Reader;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.StringTokenizer;\nimport java.util.stream.Collectors;\n\n\npublic class C1310C_2 {\n public static void main(String[] args) {\n var scanner = new BufferedScanner();\n var writer = new PrintWriter(new BufferedOutputStream(System.out));\n\n var n = scanner.nextInt();\n var m = scanner.nextInt();\n var k = scanner.nextLong();\n var s = scanner.next().toCharArray();\n\/\/ var n = 1000;\n\/\/ var m = 800;\n\/\/ var k = (long) 1e18;\n\/\/ var sb = new StringBuilder();\n\/\/ for (int i = 0; i < n; i++) {\n\/\/ sb.append((char) (Math.random() * 3 + 'a'));\n\/\/ }\n\/\/ var s = sb.toString().toCharArray();\n var t = System.nanoTime();\n writer.println(solve(n, m, k, s));\n\/\/ System.out.println((System.nanoTime() - t) \/ 1e9);\n\n scanner.close();\n writer.flush();\n writer.close();\n }\n\n static final long K_MAX = (long) 1e18;\n\n private static String solve(int n, int m, long k, char[] s) {\n var lcp = lcp(n, s);\n var subs = subs(n, s, lcp);\n var low = 0;\n var high = subs.size() - 1;\n var found = -1;\n while (low <= high && found < 0) {\n var mid = (low + high) >>> 1;\n var gte = countGte(n, s, m, subs.get(mid), lcp);\n var countFrom = gte[1] + 1;\n var countTo = gte[1] + gte[0];\n\/\/ System.out.println(subs.get(mid) + \" \" + Arrays.toString(gte));\n if (countFrom <= k && k <= countTo) {\n found = mid;\n } else if (countTo < k) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n\n }\n return new String(s, subs.get(found).from, subs.get(found).len);\n }\n\n static int compare(int from1, int len1, int from2, int len2, int[][] lcp, char[] s) {\n var common = lcp[from1][from2];\n if (common >= len1 || common >= len2) {\n return Integer.compare(len1, len2); \/\/ \u8c01\u957f\u8c01\u5927\n } else {\n return Character.compare(s[from1 + common], s[from2 + common]);\n }\n }\n\n private static long[] countGte(int n, char[] s, int m, Sub minS, int[][] lcp) {\n int minSLen = minS.len;\n var dp0 = new long[m + 1][n + 1];\n var dp1 = new long[m + 1][n + 1];\n dp0[0][0] = 0; \/\/ \u957f\u5ea6\u4e3a0\u5212\u5206\u4e3a0\u4e2a\u90e8\u5206\uff0c\u5176\u4e2d\u81f3\u5c11\u4e00\u4e2a\u7b49\u4e8eminS\u7684\u5212\u5206\u6570\u4e3a0\u3002\n dp1[0][0] = 1; \/\/ \u957f\u5ea6\u4e3a0\u5212\u5206\u4e3a0\u4e2a\u90e8\u5206\uff0c\u5176\u4e2d\u6240\u6709\u90fd\u5927\u4e8eminS\u7684\u5212\u5206\u6570\u4e3a1\u3002\n for (int parts = 1; parts <= m; parts++) {\n var change = new HashMap>();\n var dp0Acc = new long[]{0, 0}; \/\/ [0]:small sum; [1]:large count\n var dp1Acc = new long[]{0, 0}; \/\/ [0]:small sum; [1]:large count\n for (int len = parts; len <= n; len++) {\n int start = len - 1;\n \/\/ \u524d\u9762\u5f00\u59cb\u7684\u5b50\u4e32\uff0c\u5230\u8fd9\u4e00\u6b65\u53ef\u80fd\u6709\u51e0\u4e2a\u53d8\u5316\uff1a\u4e00\u76f4\u662fminS\u524d\u7f00\uff08\u957f\u5ea6\u53ef\u80fd\u662f0\uff09\u7684\uff0c\u53d8\u5927\u4e8e\u3001\u7b49\u4e8e\u3001\u5c0f\u4e8eminS\u4e86\u3002\n \/\/ \u5148\u628a\u5f53\u524d\u8fd9\u4e2a\u52a0\u8fdb\u53bb\n if (compare(start, len - start, minS.from, minS.len, lcp, s) > 0) {\n \/\/ \u7b2c1\u4f4d\u5c31\u5927\u4e8eminS\u7684\uff0c\u65e0\u8bba\u600e\u4e48\u5ef6\u957f\u90fd\u4f1a\u4e00\u76f4\u5927\u4e8eminS\uff0c\u6240\u4ee5\u540e\u9762\u7684len+x(x>=0)\u90fd\u4f1a\u7528\u5230\n add(dp0Acc, dp0[parts - 1][start]);\n add(dp1Acc, dp1[parts - 1][start]);\n } else {\n var common = min(lcp[start][minS.from], minS.len);\n var changePos = common == minSLen ? start + common - 1\n : start + common;\n change.compute(changePos, (k, v) -> {\n if (v == null) {\n v = new ArrayList<>();\n }\n v.add(start);\n return v;\n });\n }\n var equalStarts = new ArrayList();\n for (Integer startToChange : change.getOrDefault(start, List.of())) {\n int compare = compare(startToChange, len - startToChange, minS.from, minS.len, lcp, s);\n if (compare == 0) {\n add(dp0Acc, dp0[parts - 1][startToChange], dp1[parts - 1][startToChange]);\n equalStarts.add(startToChange);\n } else if (compare > 0) {\n add(dp0Acc, dp0[parts - 1][startToChange]);\n add(dp1Acc, dp1[parts - 1][startToChange]);\n }\n }\n dp0[parts][len] = translate(dp0Acc);\n dp1[parts][len] = translate(dp1Acc);\n for (Integer equalStart : equalStarts) {\n \/\/ \u76f8\u7b49\u53ea\u5728\u5f53\u524dlen\u6709\u7528\n minus(dp0Acc, dp0[parts - 1][equalStart], dp1[parts - 1][equalStart]);\n \/\/ len+1\u5c31\u53ef\u80fd\u53d8\u5927\u6216\u8005\u53d8\u5c0f\n change.compute(start + 1, (k, v) -> {\n if (v == null) {\n v = new ArrayList<>();\n }\n v.add(equalStart);\n return v;\n });\n }\n }\n }\n return new long[]{dp0[m][n], dp1[m][n]};\n }\n\n private static int min(int... a) {\n var ans = Integer.MAX_VALUE;\n for (int x : a) {\n ans = Math.min(ans, x);\n }\n return ans;\n }\n\n private static long translate(long[] acc) {\n return acc[0] > K_MAX || acc[1] > 0 ? K_MAX + 1 : acc[0];\n }\n\n private static void minus(long[] acc, long... a) {\n for (long x : a) {\n if (x > K_MAX) {\n acc[1]--;\n } else {\n acc[0] -= x;\n }\n }\n }\n\n static void add(long[] sum, long... a) {\n for (long x : a) {\n if (x > K_MAX) {\n sum[1]++;\n } else {\n sum[0] += x;\n }\n }\n }\n\n private static List subs(int n, char[] s, int[][] lcp) {\n var t = System.nanoTime();\n var tmp = new ArrayList();\n for (int i = 0; i < n; i++) {\n for (int j = i; j < n; j++) {\n tmp.add(new Sub(i, j, s, lcp));\n }\n }\n\/\/ System.out.println(\"sub collect: \" + (System.nanoTime() - t) \/ 1e9);\n t = System.nanoTime();\n var ans = tmp.stream().distinct().sorted(Comparator.reverseOrder()).collect(Collectors.toList());\n\/\/ System.out.println(\"sub distinct and sort: \" + (System.nanoTime() - t) \/ 1e9);\n return ans;\n }\n\n static class Sub implements Comparable {\n final int from;\n final int to;\n final int len;\n final char[] s;\n final int[][] lcp;\n int hash;\n\n Sub(int from, int to, char[] s, int[][] lcp) {\n this.from = from;\n this.to = to;\n this.s = s;\n this.lcp = lcp;\n len = to - from + 1;\n }\n\n @Override\n public int compareTo(Sub o) {\n return compare(from, len, o.from, o.len, lcp, s);\n }\n\n @Override\n public String toString() {\n return \"Sub{\" +\n \"from=\" + from +\n \", to=\" + to +\n \", len=\" + len +\n \", s=\" + Arrays.toString(s) +\n \", sub=\" + new String(s, from, len) +\n '}';\n }\n\n @Override\n public int hashCode() {\n int h = hash;\n if (h == 0 && len > 0) {\n for (int i = from; i <= to; i++) {\n h = 31 * h + (s[i] & 0xff);\n }\n hash = h;\n }\n return h;\n }\n\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n } else if (this == obj) {\n return true;\n } else if (getClass() != obj.getClass()) {\n return false;\n }\n Sub o = (Sub) obj;\n if (len == o.len) {\n for (int i = 0; i < len; i++) {\n if (s[from + i] != s[o.from + i]) {\n return false;\n }\n }\n return true;\n } else {\n return false;\n }\n }\n }\n\n private static int[][] lcp(int n, char[] s) {\n var ans = new int[n + 1][n + 1];\n for (int i = n - 1; i >= 0; i--) {\n for (int j = n - 1; j >= 0; j--) {\n if (s[i] == s[j]) {\n ans[i][j] = ans[i + 1][j + 1] + 1;\n } else {\n ans[i][j] = 0;\n }\n }\n }\n return ans;\n }\n\n\n public static class BufferedScanner {\n BufferedReader br;\n StringTokenizer st;\n\n public BufferedScanner(Reader reader) {\n br = new BufferedReader(reader);\n }\n\n public BufferedScanner() {\n this(new InputStreamReader(System.in));\n }\n\n String next() {\n while (st == null || !st.hasMoreElements()) {\n try {\n st = new StringTokenizer(br.readLine());\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return st.nextToken();\n }\n\n int nextInt() {\n return Integer.parseInt(next());\n }\n\n long nextLong() {\n return Long.parseLong(next());\n }\n\n double nextDouble() {\n return Double.parseDouble(next());\n }\n\n String nextLine() {\n String str = \"\";\n try {\n str = br.readLine();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return str;\n }\n\n void close() {\n try {\n br.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n }\n\n static long gcd(long a, long b) {\n if (a < b) {\n return gcd(b, a);\n }\n while (b > 0) {\n long tmp = b;\n b = a % b;\n a = tmp;\n }\n return a;\n }\n\n static long inverse(long a, long m) {\n long[] ans = extgcd(a, m);\n return ans[0] == 1 ? (ans[1] + m) % m : -1;\n }\n\n private static long[] extgcd(long a, long m) {\n if (m == 0) {\n return new long[]{a, 1, 0};\n } else {\n long[] ans = extgcd(m, a % m);\n long tmp = ans[1];\n ans[1] = ans[2];\n ans[2] = tmp;\n ans[2] -= ans[1] * (a \/ m);\n return ans;\n }\n }\n\n private static List primes(double upperBound) {\n var limit = (int) Math.sqrt(upperBound);\n var isComposite = new boolean[limit + 1];\n var primes = new ArrayList();\n for (int i = 2; i <= limit; i++) {\n if (isComposite[i]) {\n continue;\n }\n primes.add(i);\n int j = i + i;\n while (j <= limit) {\n isComposite[j] = true;\n j += i;\n }\n }\n return primes;\n }\n\n}\n","language":"java"} -{"contest_id":"1320","problem_id":"B","statement":"B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http:\/\/tk.codeforces.com\/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2\u2264n\u2264m\u22642\u22c51052\u2264n\u2264m\u22642\u22c5105) \u2014 the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n, u\u2260vu\u2260v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2\u2264k\u2264n2\u2264k\u2264n) \u2014 the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1\u2264pi\u2264n1\u2264pi\u2264n, all these integers are pairwise distinct) \u2014 the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i\u2208[1,k\u22121]i\u2208[1,k\u22121] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9\n1 5\n5 4\n1 2\n2 3\n3 4\n4 1\n2 6\n6 4\n4 2\n4\n1 2 3 4\nOutputCopy1 2\nInputCopy7 7\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 1\n7\n1 2 3 4 5 6 7\nOutputCopy0 0\nInputCopy8 13\n8 7\n8 6\n7 5\n7 4\n6 5\n6 4\n5 3\n5 2\n4 3\n4 2\n3 1\n2 1\n1 8\n5\n8 7 5 2 1\nOutputCopy0 3\n","tags":["dfs and similar","graphs","shortest paths"],"code":"\/\/some updates in import stuff\n\nimport static java.lang.Math.max;\n\nimport static java.lang.Math.min;\n\nimport static java.lang.Math.abs;\n\n\n\nimport java.util.*;\n\nimport java.io.*;\n\nimport java.math.*;\n\n\n\n\/*\n\n Always check before submitting list\n\n -> int to long conversion needed\n\n -> while loop mein break case shi ho\n\n -> extra kuch output na ho rha free fund mein\n\n\n\n\n\n*\/\n\n\n\n\/\/update this bad boi too\n\npublic class Main{\n\n\n\n static int mod = (int) (Math.pow(10, 9)+7);\n\n\tstatic final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };\n\n\tstatic final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };\n\n\tstatic final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };\n\n\n\n\tstatic final double eps = 1e-10;\n\n\tstatic Set primeNumbers = new HashSet<>();\n\n\n\n public static void main(String[] args) throws IOException{\n\n MyScanner sc = new MyScanner();\n\n \/\/changes in this line of code\n\n out = new PrintWriter(new BufferedOutputStream(System.out));\n\n \/\/ out = new PrintWriter(new BufferedWriter(new FileWriter(\"output.out\"))); \n\n \n\n \/\/Write Code Below\n\n int n = sc.nextInt();\n\n int m = sc.nextInt();\n\n\n\n Graph g = new Graph(n+1);\n\n Graph tg = new Graph(n+1);\n\n for(int i = 0; i < m; i++){\n\n int from = sc.nextInt();\n\n int to = sc.nextInt();\n\n g.addEdge(from, to);\n\n tg.addEdge(to, from);\n\n }\n\n\n\n int k = sc.nextInt();\n\n int[] path = new int[k];\n\n for(int i= 0; i < k; i++){\n\n path[i] = sc.nextInt();\n\n }\n\n\n\n \/\/now solve using BFS and transposed graph baby!!! (sexy, think out of the box type of think)\n\n int[] dist = tg.giveDist(path[k-1]);\n\n\n\n Pair ans = g.minMaxPair(path[k-1],k,path, dist);\n\n out.println(ans.a + \" \" + ans.b);\n\n out.close();\n\n }\n\n\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n\n\n \/\/Updation Required\n\n \/\/Fenwick Tree (customisable)\n\n \/\/Segment Tree (customisable)\n\n\n\n \/\/-----CURRENTLY PRESENT-------\/\/\n\n \/\/Graph\n\n \/\/DSU\n\n \/\/powerMODe\n\n \/\/power\n\n \/\/Segment Tree (work on this one) \n\n \/\/Prime Sieve\n\n \/\/Count Divisors\n\n \/\/Next Permutation \n\n \/\/Get NCR \n\n \/\/isVowel\n\n \/\/Sort (int)\n\n \/\/Sort (long)\n\n \/\/Binomial Coefficient\n\n \/\/Pair\n\n \/\/Triplet\n\n \/\/lcm (int & long)\n\n \/\/gcd (int & long)\n\n \/\/gcd (for binomial coefficient)\n\n \/\/swap (int & char)\n\n \/\/reverse\n\n\n\n \/\/SOME LATEST UPDATIONS!!!\n\n \/\/mod_mul\n\n \/\/mod_div\n\n\n\n \/\/Fast input and output \n\n\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n \/\/-------------------------------------------------------------------\n\n\n\n \/\/finding combinations in O(1) (basically the most basic logic you can think of)\n\n \/\/not that complicated as i though it of\n\n\n\n\n\n \/\/GRAPH (basic structure)\n\n public static class Graph{\n\n public int V;\n\n public ArrayList> edges;\n\n\n\n \/\/2 -> [0,1,2] (current)\n\n Graph(int V){\n\n this.V = V;\n\n edges = new ArrayList<>(V+1);\n\n for(int i= 0; i <= V; i++){\n\n edges.add(new ArrayList<>());\n\n }\n\n }\n\n\n\n public void addEdge(int from , int to){\n\n edges.get(from).add(to);\n\n }\n\n\n\n public int[] giveDist(int fpoint){\n\n int[] visited = new int[V];\n\n int[] dist = new int[V];\n\n\n\n ArrayDeque que = new ArrayDeque<>(); \/\/transpose graph thingie is pretty cool (quality question baby)\n\n que.add(fpoint);\n\n dist[fpoint] = 0;\n\n\n\n while(!que.isEmpty()){\n\n int curr = que.poll();\n\n visited[curr] = 1;\n\n\n\n for(int edge : edges.get(curr)){\n\n if(visited[edge] != 1){\n\n que.add(edge);\n\n visited[edge] = 1;\n\n dist[edge] = dist[curr] + 1;\n\n }\n\n }\n\n }\n\n\n\n \/\/ out.println(Arrays.toString(dist));\n\n return dist;\n\n }\n\n\n\n public Pair minMaxPair(int fpoint, int k, int[] path, int[] dist){\n\n int min = 0; \n\n int max = 0;\n\n\n\n \/\/this function might not be working perfectly, let's think about it now\n\n for(int i = 0; i < k-1; i++){\n\n int curr = path[i];\n\n int next = path[i+1];\n\n \n\n \/\/now let's add in set \n\n Set set = new HashSet<>();\n\n for(int edge : edges.get(curr)){\n\n if(dist[edge] == dist[curr]-1) set.add(edge);\n\n }\n\n\n\n \/\/ out.println(set);\n\n \/\/this bad boi is pretty accurate for sure (now figure out something else)\n\n if(set.contains(next) && set.size() > 1){\n\n max++;\n\n }else if(!set.contains(next)){\n\n max++;\n\n min++;\n\n }\n\n }\n\n\n\n return new Pair(min, max);\n\n \n\n }\n\n\n\n }\n\n\n\n \/\/DSU (path and rank optimised)\n\n public static class DisjointUnionSets {\n\n int[] rank, parent;\n\n int n;\n\n \n\n public DisjointUnionSets(int n)\n\n {\n\n rank = new int[n];\n\n parent = new int[n];\n\n Arrays.fill(rank, 1);\n\n Arrays.fill(parent,-1);\n\n this.n = n;\n\n }\n\n \n\n public int find(int curr){\n\n if(parent[curr] == -1)\n\n return curr;\n\n \n\n \/\/path compression optimisation\n\n return parent[curr] = find(parent[curr]);\n\n }\n\n \n\n public void union(int a, int b){\n\n int s1 = find(a);\n\n int s2 = find(b);\n\n \n\n if(s1 != s2){\n\n if(rank[s1] < rank[s2]){\n\n parent[s1] = s2;\n\n rank[s2] += rank[s1];\n\n }else{\n\n parent[s2] = s1;\n\n rank[s1] += rank[s2];\n\n }\n\n }\n\n }\n\n }\n\n\n\n \/\/with mod\n\n public static long powerMOD(long x, long y)\n\n {\n\n long res = 1L; \n\n while (y > 0)\n\n {\n\n \/\/ If y is odd, multiply x with result\n\n if ((y & 1) != 0){\n\n x %= mod;\n\n res %= mod;\n\n res = (res * x)%mod;\n\n }\n\n \/\/ y must be even now\n\n y = y >> 1; \/\/ y = y\/2\n\n x%= mod;\n\n x = (x * x)%mod; \/\/ Change x to x^2\n\n }\n\n return res%mod;\n\n }\n\n\n\n \/\/without mod\n\n public static long power(long x, long y)\n\n {\n\n long res = 1L; \n\n while (y > 0)\n\n {\n\n \/\/ If y is odd, multiply x with result\n\n if ((y & 1) != 0){\n\n res = (res * x);\n\n }\n\n \/\/ y must be even now\n\n y = y >> 1; \/\/ y = y\/\n\n x = (x * x);\n\n }\n\n return res;\n\n }\n\n\n\n public static class segmentTree{\n\n\n\n public long[] arr;\n\n public long[] tree;\n\n public long[] lazy;\n\n\n\n segmentTree(long[] array){\n\n int n = array.length;\n\n arr = new long[n];\n\n for(int i= 0; i < n; i++) arr[i] = array[i];\n\n tree = new long[4*n + 1];\n\n lazy = new long[4*n + 1];\n\n }\n\n\n\n public void build(int[]arr, int s, int e, int[] tree, int index){\n\n\n\n if(s == e){\n\n tree[index] = arr[s];\n\n return;\n\n }\n\n \n\n \/\/otherwise divide in two parts and fill both sides simply\n\n int mid = (s+e)\/2;\n\n build(arr, s, mid, tree, 2*index);\n\n build(arr, mid+1, e, tree, 2*index+1);\n\n \n\n \/\/who will build the current position dude\n\n tree[index] = Math.min(tree[2*index], tree[2*index+1]);\n\n }\n\n \n\n public int query(int sr, int er, int sc, int ec, int index, int[] tree){\n\n \n\n if(lazy[index] != 0){\n\n tree[index] += lazy[index];\n\n \n\n if(sc != ec){\n\n lazy[2*index+1] += lazy[index];\n\n lazy[2*index] += lazy[index];\n\n }\n\n \n\n lazy[index] = 0;\n\n }\n\n \n\n \/\/no overlap\n\n if(sr > ec || sc > er) return Integer.MAX_VALUE;\n\n \n\n \/\/found the index baby\n\n if(sr <= sc && ec <= er) return tree[index];\n\n \n\n \/\/finding the index on both sides hehehehhe\n\n int mid = (sc + ec)\/2;\n\n int left = query(sr, er, sc, mid, 2*index, tree);\n\n int right = query(sr, er, mid+1, ec, 2*index + 1, tree);\n\n \n\n return Integer.min(left, right);\n\n }\n\n \n\n \/\/now we will do point update implementation\n\n \/\/it should be simple then we expected for sure\n\n public void update(int index, int indexr, int increment, int[] tree, int s, int e){\n\n \n\n if(lazy[index] != 0){\n\n tree[index] += lazy[index];\n\n \n\n if(s != e){\n\n lazy[2*index+1] = lazy[index];\n\n lazy[2*index] = lazy[index];\n\n }\n\n \n\n lazy[index] = 0;\n\n }\n\n \n\n \/\/no overlap\n\n if(indexr < s || indexr > e) return;\n\n \n\n \/\/found the required index\n\n if(s == e){\n\n tree[index] += increment;\n\n return;\n\n } \n\n \n\n \/\/search for the index on both sides\n\n int mid = (s+e)\/2;\n\n update(2*index, indexr, increment, tree, s, mid);\n\n update(2*index+1, indexr, increment, tree, mid+1, e);\n\n \n\n \/\/now update the current range simply\n\n tree[index] = Math.min(tree[2*index+1], tree[2*index]);\n\n }\n\n \n\n public void rangeUpdate(int[] tree , int index, int s, int e, int sr, int er, int increment){\n\n \n\n \/\/if not at all in the same range\n\n if(e < sr || er < s) return;\n\n \n\n \/\/complete then also move forward\n\n if(s == e){\n\n tree[index] += increment;\n\n return;\n\n }\n\n \n\n \/\/otherwise move in both subparts\n\n int mid = (s+e)\/2;\n\n rangeUpdate(tree, 2*index, s, mid, sr, er, increment);\n\n rangeUpdate(tree, 2*index + 1, mid+1, e, sr, er, increment);\n\n \n\n \/\/update current range too na\n\n \/\/i always forget this step for some reasons hehehe, idiot\n\n tree[index] = Math.min(tree[2*index], tree[2*index + 1]);\n\n }\n\n \n\n public void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment){\n\n \n\n \/\/update lazy values\n\n \/\/resolve lazy value before going down\n\n if(lazy[index] != 0){\n\n tree[index] += lazy[index];\n\n \n\n if(s != e){\n\n lazy[2*index+1] += lazy[index];\n\n lazy[2*index] += lazy[index];\n\n }\n\n \n\n lazy[index] = 0;\n\n }\n\n \n\n \/\/no overlap case\n\n if(sr > e || s > er) return;\n\n \n\n \/\/complete overlap\n\n if(sr <= s && er >= e){\n\n tree[index] += increment;\n\n \n\n if(s != e){\n\n lazy[2*index+1] += increment;\n\n lazy[2*index] += increment;\n\n }\n\n return;\n\n }\n\n \n\n \/\/otherwise go on both left and right side and do your shit\n\n int mid = (s + e)\/2;\n\n rangeUpdateLazy(tree, 2*index, s, mid, sr, er, increment);\n\n rangeUpdateLazy(tree, 2*index + 1, mid+1, e, sr, er, increment);\n\n \n\n tree[index] = Math.min(tree[2*index+1], tree[2*index]);\n\n return;\n\n \n\n }\n\n \n\n }\n\n\n\n \/\/prime sieve\n\n public static void primeSieve(int n){\n\n BitSet bitset = new BitSet(n+1);\n\n for(long i = 0; i < n ; i++){\n\n if (i == 0 || i == 1) {\n\n bitset.set((int) i);\n\n continue;\n\n }\n\n if(bitset.get((int) i)) continue;\n\n primeNumbers.add((int)i);\n\n for(long j = i; j <= n ; j+= i)\n\n bitset.set((int)j);\n\n }\n\n }\n\n\n\n \/\/number of divisors\n\n \/\/ public static int countDivisors(long number){\n\n \/\/ if(number == 1) return 1;\n\n \/\/ List primeFactors = new ArrayList<>();\n\n \/\/ int index = 0;\n\n \/\/ long curr = primeNumbers.get(index);\n\n \/\/ while(curr * curr <= number){\n\n \/\/ while(number % curr == 0){\n\n \/\/ number = number\/curr;\n\n \/\/ primeFactors.add((int) curr);\n\n \/\/ } \n\n \/\/ index++;\n\n \/\/ curr = primeNumbers.get(index);\n\n \/\/ }\n\n\n\n \/\/ if(number != 1) primeFactors.add((int) number);\n\n \/\/ int current = primeFactors.get(0);\n\n \/\/ int totalDivisors = 1;\n\n \/\/ int currentCount = 2;\n\n \/\/ for (int i = 1; i < primeFactors.size(); i++) {\n\n \/\/ if (primeFactors.get(i) == current) {\n\n \/\/ currentCount++;\n\n \/\/ } else {\n\n \/\/ totalDivisors *= currentCount;\n\n \/\/ currentCount = 2;\n\n \/\/ current = primeFactors.get(i);\n\n \/\/ }\n\n \/\/ }\n\n \/\/ totalDivisors *= currentCount;\n\n \/\/ return totalDivisors;\n\n \/\/ }\n\n\n\n \/\/now adding next permutation function to java hehe\n\n public static boolean next_permutation(int[] p) {\n\n for (int a = p.length - 2; a >= 0; --a)\n\n if (p[a] < p[a + 1])\n\n for (int b = p.length - 1;; --b)\n\n if (p[b] > p[a]) {\n\n int t = p[a];\n\n p[a] = p[b];\n\n p[b] = t;\n\n for (++a, b = p.length - 1; a < b; ++a, --b) {\n\n t = p[a];\n\n p[a] = p[b];\n\n p[b] = t;\n\n }\n\n return true;\n\n }\n\n return false;\n\n }\n\n\n\n \/\/is vowel function \n\n public static boolean isVowel(char c)\n\n {\n\n return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U');\n\n } \n\n\n\n \/\/to sort the array with better method\n\n\tpublic static void sort(int[] a) {\n\n\t\tArrayList l=new ArrayList<>();\n\n\t\tfor (int i:a) l.add(i);\n\n\t\tCollections.sort(l);\n\n\t\tfor (int i=0; i l=new ArrayList<>();\n\n\t\tfor (long i:a) l.add(i);\n\n\t\tCollections.sort(l);\n\n\t\tfor (int i=0; i 0; j--)\n\n C[j] = C[j] + C[j - 1];\n\n }\n\n return C[k];\n\n }\n\n\n\n \/\/Pair with int int \n\n public static class Pair{\n\n public int a;\n\n public int b;\n\n\n\n Pair(int a , int b){\n\n this.a = a;\n\n this.b = b;\n\n }\n\n\n\n @Override\n\n public String toString(){\n\n return a + \" -> \" + b; \n\n }\n\n }\n\n\n\n \/\/Triplet with int int int\n\n public static class Triplet{\n\n\n\n public int a;\n\n public int b;\n\n public int c;\n\n\n\n Triplet(int a , int b, int c){\n\n this.a = a;\n\n this.b = b;\n\n this.c = c;\n\n }\n\n\n\n @Override\n\n public String toString(){\n\n return a + \" -> \" + b; \n\n }\n\n }\n\n\n\n \/\/Shortcut function\n\n public static long lcm(long a , long b){\n\n return a * (b\/gcd(a,b));\n\n }\n\n\n\n \/\/let's make one for calculating lcm basically\n\n public static int lcm(int a , int b){\n\n return (a * b)\/gcd(a,b);\n\n }\n\n\n\n \/\/int version for gcd\n\n public static int gcd(int a, int b){\n\n if(b == 0)\n\n return a;\n\n \n\n return gcd(b , a%b);\n\n }\n\n\n\n \/\/long version for gcd\n\n public static long gcd(long a, long b){\n\n if(b == 0)\n\n return a;\n\n\n\n return gcd(b , a%b);\n\n }\n\n\n\n \/\/for ncr calculator(ignore this code)\n\n public static long __gcd(long n1, long n2)\n\n {\n\n long gcd = 1;\n\n for (int i = 1; i <= n1 && i <= n2; ++i) {\n\n \/\/ Checks if i is factor of both integers\n\n if (n1 % i == 0 && n2 % i == 0) {\n\n gcd = i;\n\n }\n\n }\n\n return gcd;\n\n }\n\n\n\n \/\/swapping two elements in an array\n\n public static void swap(int[] arr, int left , int right){\n\n int temp = arr[left];\n\n arr[left] = arr[right];\n\n arr[right] = temp;\n\n }\n\n\n\n \/\/for char array\n\n public static void swap(char[] arr, int left , int right){\n\n char temp = arr[left];\n\n arr[left] = arr[right];\n\n arr[right] = temp;\n\n }\n\n\n\n \/\/reversing an array\n\n public static void reverse(int[] arr){\n\n int left = 0;\n\n int right = arr.length-1;\n\n\n\n while(left <= right){\n\n swap(arr, left,right);\n\n left++;\n\n right--;\n\n }\n\n }\n\n \n\n public static long expo(long a, long b, long mod) {\n\n long res = 1; \n\n while (b > 0) {\n\n if ((b & 1) == 1L) res = (res * a) % mod; \/\/think about this one for a second\n\n a = (a * a) % mod;\n\n b = b >> 1;\n\n } \n\n return res;\n\n }\n\n\n\n \/\/SOME EXTRA DOPE FUNCTIONS \n\n public static long mminvprime(long a, long b) {\n\n return expo(a, b - 2, b);\n\n }\n\n\n\n public static long mod_add(long a, long b, long m) {\n\n a = a % m;\n\n b = b % m;\n\n return (((a + b) % m) + m) % m;\n\n }\n\n\n\n public static long mod_sub(long a, long b, long m) {\n\n a = a % m; \n\n b = b % m; \n\n return (((a - b) % m) + m) % m;\n\n }\n\n \n\n public static long mod_mul(long a, long b, long m) {\n\n a = a % m;\n\n b = b % m;\n\n return (((a * b) % m) + m) % m;\n\n }\n\n\n\n public static long mod_div(long a, long b, long m) {\n\n a = a % m;\n\n b = b % m;\n\n return (mod_mul(a, mminvprime(b, m), m) + m) % m;\n\n }\n\n\n\n \/\/O(n) every single time remember that\n\n public static long nCr(long N, long K , long mod){\n\n long upper = 1L;\n\n long lower = 1L;\n\n long lowerr = 1L;\n\n\n\n for(long i = 1; i <= N; i++){\n\n upper = mod_mul(upper, i, mod);\n\n }\n\n\n\n for(long i = 1; i <= K; i++){\n\n lower = mod_mul(lower, i, mod);\n\n }\n\n\n\n for(long i = 1; i <= (N - K); i++){\n\n lowerr = mod_mul(lowerr, i, mod);\n\n }\n\n\n\n \/\/ out.println(upper + \" \" + lower + \" \" + lowerr);\n\n long answer = mod_mul(lower, lowerr, mod);\n\n answer = mod_div(upper, answer, mod);\n\n\n\n return answer;\n\n }\n\n\n\n \/\/ ll *fact = new ll[2 * n + 1];\n\n\t\/\/ ll *ifact = new ll[2 * n + 1];\n\n\t\/\/ fact[0] = 1;\n\n\t\/\/ ifact[0] = 1;\n\n\t\/\/ for (ll i = 1; i <= 2 * n; i++)\n\n\t\/\/ {\n\n\t\/\/ \tfact[i] = mod_mul(fact[i - 1], i, MOD1);\n\n\t\/\/ \tifact[i] = mminvprime(fact[i], MOD1);\n\n\t\/\/ }\n\n \/\/ifact is basically inverse factorial in here!!!!!(imp)\n\n public static long combination(long n, long r, long m, long[] fact, long[] ifact) {\n\n long val1 = fact[(int)n];\n\n long val2 = ifact[(int)(n - r)];\n\n long val3 = ifact[(int)r];\n\n return (((val1 * val2) % m) * val3) % m;\n\n }\n\n\n\n \n\n \n\n \/\/-----------PrintWriter for faster output---------------------------------\n\n public static PrintWriter out;\n\n \n\n \/\/-----------MyScanner class for faster input----------\n\n public static class MyScanner {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public MyScanner() {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n\n\n \/\/ public MyScanner() throws FileNotFoundException {\n\n \/\/ br = new BufferedReader(new FileReader(\"input.in\"));\n\n \/\/ }\n\n \n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n \n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n \n\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n \n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n \n\n String nextLine(){\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n\n\n }\n\n \/\/--------------------------------------------------------\n\n}","language":"java"} -{"contest_id":"1307","problem_id":"A","statement":"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\u2264i,j\u2264n1\u2264i,j\u2264n) such that |i\u2212j|=1|i\u2212j|=1 and ai>0ai>0 and apply ai=ai\u22121ai=ai\u22121, 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\u2264t\u22641001\u2264t\u2264100) \u00a0\u2014 the number of test cases. Next 2t2t lines contain a description of test cases \u00a0\u2014 two lines per test case.The first line of each test case contains integers nn and dd (1\u2264n,d\u22641001\u2264n,d\u2264100) \u2014 the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u22641000\u2264ai\u2264100) \u00a0\u2014 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\n4 5\n1 0 3 2\n2 2\n100 1\n1 8\n0\nOutputCopy3\n101\n0\nNoteIn 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.","tags":["greedy","implementation"],"code":"import java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PrintWriter;\nimport java.util.StringTokenizer;\nimport java.io.IOException;\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.io.InputStream;\n\n\/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n *\n * @author lucasr\n *\/\npublic class Main {\n\tpublic static void main(String[] args) {\n\t\tInputStream inputStream = System.in;\n\t\tOutputStream outputStream = System.out;\n\t\tMyScanner in = new MyScanner(inputStream);\n\t\tPrintWriter out = new PrintWriter(outputStream);\n\t\tACowAndHaybales solver = new ACowAndHaybales();\n\t\tint testCount = Integer.parseInt(in.next());\n\t\tfor (int i = 1; i <= testCount; i++)\n\t\t\tsolver.solve(i, in, out);\n\t\tout.close();\n\t}\n\n\tstatic class ACowAndHaybales {\n\t\tpublic static MyScanner sc;\n\t\tpublic static PrintWriter out;\n\n\t\tpublic void solve(int testNumber, MyScanner sc, PrintWriter out) {\n\t\t\tACowAndHaybales.sc = sc;\n\t\t\tACowAndHaybales.out = out;\n\t\t\tint n = sc.nextInt();\n\t\t\tint d = sc.nextInt();\n\t\t\tint[] piles = sc.nextIntArray(n);\n\t\t\twhile (d > 0) {\n\t\t\t\tboolean found = false;\n\t\t\t\tfor (int j = 1; j < n; j++) {\n\t\t\t\t\tif (piles[j] > 0 && j <= d) {\n\t\t\t\t\t\tpiles[j]--;\n\t\t\t\t\t\tpiles[0]++;\n\t\t\t\t\t\td -= j;\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!found) break;\n\t\t\t}\n\t\t\tout.println(piles[0]);\n\t\t}\n\n\t}\n\n\tstatic class MyScanner {\n\t\tprivate BufferedReader br;\n\t\tprivate StringTokenizer tokenizer;\n\n\t\tpublic MyScanner(InputStream is) {\n\t\t\tbr = new BufferedReader(new InputStreamReader(is));\n\t\t}\n\n\t\tpublic String next() {\n\t\t\twhile (tokenizer == null || !tokenizer.hasMoreTokens()) {\n\t\t\t\ttry {\n\t\t\t\t\ttokenizer = new StringTokenizer(br.readLine());\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tthrow new RuntimeException(e);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn tokenizer.nextToken();\n\t\t}\n\n\t\tpublic int nextInt() {\n\t\t\treturn Integer.parseInt(next());\n\t\t}\n\n\t\tpublic int[] nextIntArray(int n) {\n\t\t\tint[] ret = new int[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tret[i] = nextInt();\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t}\n}\n\n","language":"java"} -{"contest_id":"1296","problem_id":"F","statement":"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\u22121n\u22121 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\u22121n\u22121 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 \u2014 the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,\u2026,fn\u22121f1,f2,\u2026,fn\u22121, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2\u2264n\u226450002\u2264n\u22645000) \u2014 the number of railway stations in Berland.The next n\u22121n\u22121 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1\u2264xi,yi\u2264n,xi\u2260yi1\u2264xi,yi\u2264n,xi\u2260yi), 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\u2264m\u226450001\u2264m\u22645000) \u2014 the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1\u2264aj,bj\u2264n1\u2264aj,bj\u2264n; aj\u2260bjaj\u2260bj; 1\u2264gj\u22641061\u2264gj\u2264106) \u2014 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\u22121n\u22121 integers f1,f2,\u2026,fn\u22121f1,f2,\u2026,fn\u22121 (1\u2264fi\u22641061\u2264fi\u2264106), 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\n1 2\n3 2\n3 4\n2\n1 2 5\n1 3 3\nOutputCopy5 3 5\nInputCopy6\n1 2\n1 6\n3 1\n1 5\n4 1\n4\n6 1 3\n3 4 1\n6 5 2\n1 2 5\nOutputCopy5 3 1 2 1 \nInputCopy6\n1 2\n1 6\n3 1\n1 5\n4 1\n4\n6 1 1\n3 4 3\n6 5 3\n1 2 4\nOutputCopy-1\n","tags":["constructive algorithms","dfs and similar","greedy","sortings","trees"],"code":"import java.io.*;\n\nimport java.util.*;\n\npublic class Sol{\n\n\tpublic static List adj[];\n\n\tpublic static int query[][];\n\n\tpublic static int get[][] = new int[5000][5000];\n\n\tpublic static int edge[];\n\n\tpublic static int par[];\n\n\tpublic static int depth[];\n\n\tpublic static int n, m, D;\n\n\tpublic static void main(String[] args) throws IOException{\n\n\t\tFastIO sc = new FastIO(System.in);\n\n\t\tPrintWriter out = new PrintWriter(System.out);\n\n\t\tboolean poss = true;\n\n\t\tn = sc.nextInt();\n\n\t\tpar = new int[n];\n\n\t\tdepth = new int[n];\n\n\t\tedge = new int[n-1];\n\n\t\tadj = new ArrayList[n];\n\n\t\tfor(int i=0; i();\n\n\t\t}\n\n\t\tint idx = 0;\n\n\t\tfor(int i=0; i=0; --i) {\n\n\t\t\tboolean change = false;\n\n\t\t\tint num = query[i][2];\n\n\t\t\tint curr1 = query[i][0];\n\n\t\t\tint curr2 = query[i][1];\n\n\t\t\twhile(curr1!=curr2) {\n\n\t\t\t\tif(depth[curr1]>depth[curr2]) {\n\n\t\t\t\t\tidx = get[curr1][par[curr1]];\n\n\t\t\t\t\tif(edge[idx]==-1||edge[idx]==num) {\n\n\t\t\t\t\t\tedge[idx] = num;\n\n\t\t\t\t\t\tchange = true;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tcurr1 = par[curr1];\n\n\t\t\t\t}else {\n\n\t\t\t\t\tidx = get[curr2][par[curr2]];\n\n\t\t\t\t\tif(edge[idx]==-1||edge[idx]==num) {\n\n\t\t\t\t\t\tedge[idx] = num;\n\n\t\t\t\t\t\tchange = true;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tcurr2 = par[curr2];\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif(!change) poss = false;\n\n\t\t}\n\n\t\tif(!poss) {\n\n\t\t\tout.println(-1);\n\n\t\t}else {\n\n\t\t\tfor(int i=0; i() { \n\n @Override \n\n public int compare(int[] entry1, \n\n int[] entry2) { \n\n \tInteger a = entry1[col];\n\n \tInteger b = entry2[col];\n\n \treturn a.compareTo(b);\n\n } \n\n }); \n\n } \n\n\tstatic class FastIO {\n\n\t\t \n\n\t\t\/\/ Is your Fast I\/O being bad?\n\n \n\n\t\tInputStream dis;\n\n\t\tbyte[] buffer = new byte[1 << 17];\n\n\t\tint pointer = 0;\n\n \n\n\t\tpublic FastIO(String fileName) throws IOException {\n\n\t\t\tdis = new FileInputStream(fileName);\n\n\t\t}\n\n \n\n\t\tpublic FastIO(InputStream is) throws IOException {\n\n\t\t\tdis = is;\n\n\t\t}\n\n \n\n\t\tint nextInt() throws IOException {\n\n\t\t\tint ret = 0;\n\n \n\n\t\t\tbyte b;\n\n\t\t\tdo {\n\n\t\t\t\tb = nextByte();\n\n\t\t\t} while (b <= ' ');\n\n\t\t\tboolean negative = false;\n\n\t\t\tif (b == '-') {\n\n\t\t\t\tnegative = true;\n\n\t\t\t\tb = nextByte();\n\n\t\t\t}\n\n\t\t\twhile (b >= '0' && b <= '9') {\n\n\t\t\t\tret = 10 * ret + b - '0';\n\n\t\t\t\tb = nextByte();\n\n\t\t\t}\n\n \n\n\t\t\treturn (negative) ? -ret : ret;\n\n\t\t}\n\n \n\n\t\tlong nextLong() throws IOException {\n\n\t\t\tlong ret = 0;\n\n \n\n\t\t\tbyte b;\n\n\t\t\tdo {\n\n\t\t\t\tb = nextByte();\n\n\t\t\t} while (b <= ' ');\n\n\t\t\tboolean negative = false;\n\n\t\t\tif (b == '-') {\n\n\t\t\t\tnegative = true;\n\n\t\t\t\tb = nextByte();\n\n\t\t\t}\n\n\t\t\twhile (b >= '0' && b <= '9') {\n\n\t\t\t\tret = 10 * ret + b - '0';\n\n\t\t\t\tb = nextByte();\n\n\t\t\t}\n\n \n\n\t\t\treturn (negative) ? -ret : ret;\n\n\t\t}\n\n \n\n\t\tbyte nextByte() throws IOException {\n\n\t\t\tif (pointer == buffer.length) {\n\n\t\t\t\tdis.read(buffer, 0, buffer.length);\n\n\t\t\t\tpointer = 0;\n\n\t\t\t}\n\n\t\t\treturn buffer[pointer++];\n\n\t\t}\n\n \n\n\t\tString next() throws IOException {\n\n\t\t\tStringBuffer ret = new StringBuffer();\n\n \n\n\t\t\tbyte b;\n\n\t\t\tdo {\n\n\t\t\t\tb = nextByte();\n\n\t\t\t} while (b <= ' ');\n\n\t\t\twhile (b > ' ') {\n\n\t\t\t\tret.appendCodePoint(b);\n\n\t\t\t\tb = nextByte();\n\n\t\t\t}\n\n \n\n\t\t\treturn ret.toString();\n\n\t\t}\n\n \n\n\t}\n\n}","language":"java"} -{"contest_id":"1316","problem_id":"D","statement":"D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n\u00d7nn\u00d7n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters \u00a0\u2014 UU, DD, LL, RR or XX \u00a0\u2014 instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c\u22121)(r,c\u22121), for UU the player should move to the top cell (r\u22121,c)(r\u22121,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (\u22121\u22121,\u22121\u22121), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1\u2264n\u22641031\u2264n\u2264103) \u00a0\u2014 the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,\u2026,xn,ynx1,y1,x2,y2,\u2026,xn,yn, where (xj,yj)(xj,yj) (1\u2264xj\u2264n,1\u2264yj\u2264n1\u2264xj\u2264n,1\u2264yj\u2264n, or (xj,yj)=(\u22121,\u22121)(xj,yj)=(\u22121,\u22121)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2\n1 1 1 1\n2 2 2 2\nOutputCopyVALID\nXL\nRX\nInputCopy3\n-1 -1 -1 -1 -1 -1\n-1 -1 2 2 -1 -1\n-1 -1 -1 -1 -1 -1\nOutputCopyVALID\nRRD\nUXD\nULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below : ","tags":["constructive algorithms","dfs and similar","graphs","implementation"],"code":"import java.io.BufferedOutputStream;\n\nimport java.io.Closeable;\n\nimport java.io.DataInputStream;\n\nimport java.io.Flushable;\n\nimport java.io.IOException;\n\nimport java.io.InputStream;\n\nimport java.io.OutputStream;\n\nimport java.io.PrintStream;\n\nimport java.util.Arrays;\n\nimport java.util.InputMismatchException;\n\nimport java.util.Objects;\n\n\n\n\/**\n\n * Built using CHelper plug-in\n\n * Actual solution is at the top\n\n *\/\n\npublic class Main {\n\n\tstatic class TaskAdapter implements Runnable {\n\n\t\t@Override\n\n\t\tpublic void run() {\n\n\t\t\tInputStream inputStream = System.in;\n\n\t\t\tOutputStream outputStream = System.out;\n\n\t\t\tFastReader in = new FastReader(inputStream);\n\n\t\t\tOutput out = new Output(outputStream);\n\n\t\t\tDNashMatrix solver = new DNashMatrix();\n\n\t\t\tsolver.solve(1, in, out);\n\n\t\t\tout.close();\n\n\t\t}\n\n\t}\n\n\n\n\tpublic static void main(String[] args) throws Exception {\n\n\t\tThread thread = new Thread(null, new TaskAdapter(), \"\", 1<<28);\n\n\t\tthread.start();\n\n\t\tthread.join();\n\n\t}\n\n\n\n\tstatic class DNashMatrix {\n\n\t\tprivate final int[] ry = new int[] {0, 1, 0, -1};\n\n\t\tprivate final int[] rx = new int[] {-1, 0, 1, 0};\n\n\t\tprivate final char[] dir = new char[] {'U', 'R', 'D', 'L'};\n\n\t\tprivate final char[] rdir = new char[] {'D', 'L', 'U', 'R'};\n\n\t\tPair[][] arr;\n\n\t\tPair p;\n\n\t\tchar[][] ans;\n\n\t\tint n;\n\n\n\n\t\tpublic DNashMatrix() {\n\n\t\t}\n\n\n\n\t\tpublic void dfs(int x, int y) {\n\n\t\t\tUtilities.Debug.dbg(x, y);\n\n\t\t\tfor(int i = 0; i<4; i++) {\n\n\t\t\t\tint cx = x+rx[i], cy = y+ry[i];\n\n\t\t\t\tif(inBounds(cx, cy)&&arr[cx][cy].equals(p)&&ans[cx][cy]==0) {\n\n\t\t\t\t\tans[cx][cy] = rdir[i];\n\n\t\t\t\t\tdfs(cx, cy);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tpublic boolean inBounds(int x, int y) {\n\n\t\t\treturn x>=0&&y>=0&&x(Math.max(in.nextInt()-1, -1), Math.max(in.nextInt()-1, -1));\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tans = new char[n][n];\n\n\t\t\tfor(int i = 0; i(v);\n\n\t\t\t\t\t\t\t\tdfs(i, j);\n\n\t\t\t\t\t\t\t\tcontinue loop;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpw.println(\"INVALID\");\n\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t}else if(v.a==i&&v.b==j) {\n\n\t\t\t\t\t\tans[i][j] = 'X';\n\n\t\t\t\t\t\tp = new Pair<>(i, j);\n\n\t\t\t\t\t\tdfs(i, j);\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tfor(int i = 0; i String ts(T t) {\n\n\t\t\t\tif(t==null) {\n\n\t\t\t\t\treturn \"null\";\n\n\t\t\t\t}\n\n\t\t\t\ttry {\n\n\t\t\t\t\treturn ts((Iterable) t);\n\n\t\t\t\t}catch(ClassCastException e) {\n\n\t\t\t\t\tif(t instanceof int[]) {\n\n\t\t\t\t\t\tString s = Arrays.toString((int[]) t);\n\n\t\t\t\t\t\treturn \"{\"+s.substring(1, s.length()-1)+\"}\";\n\n\t\t\t\t\t}else if(t instanceof long[]) {\n\n\t\t\t\t\t\tString s = Arrays.toString((long[]) t);\n\n\t\t\t\t\t\treturn \"{\"+s.substring(1, s.length()-1)+\"}\";\n\n\t\t\t\t\t}else if(t instanceof char[]) {\n\n\t\t\t\t\t\tString s = Arrays.toString((char[]) t);\n\n\t\t\t\t\t\treturn \"{\"+s.substring(1, s.length()-1)+\"}\";\n\n\t\t\t\t\t}else if(t instanceof double[]) {\n\n\t\t\t\t\t\tString s = Arrays.toString((double[]) t);\n\n\t\t\t\t\t\treturn \"{\"+s.substring(1, s.length()-1)+\"}\";\n\n\t\t\t\t\t}else if(t instanceof boolean[]) {\n\n\t\t\t\t\t\tString s = Arrays.toString((boolean[]) t);\n\n\t\t\t\t\t\treturn \"{\"+s.substring(1, s.length()-1)+\"}\";\n\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\n\t\t\t\t\t\treturn ts((Object[]) t);\n\n\t\t\t\t\t}catch(ClassCastException e1) {\n\n\t\t\t\t\t\treturn t.toString();\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\n\t\t\tprivate static String ts(T[] arr) {\n\n\t\t\t\tStringBuilder ret = new StringBuilder();\n\n\t\t\t\tret.append(\"{\");\n\n\t\t\t\tboolean first = true;\n\n\t\t\t\tfor(T t: arr) {\n\n\t\t\t\t\tif(!first) {\n\n\t\t\t\t\t\tret.append(\", \");\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfirst = false;\n\n\t\t\t\t\tret.append(ts(t));\n\n\t\t\t\t}\n\n\t\t\t\tret.append(\"}\");\n\n\t\t\t\treturn ret.toString();\n\n\t\t\t}\n\n\n\n\t\t\tprivate static String ts(Iterable iter) {\n\n\t\t\t\tStringBuilder ret = new StringBuilder();\n\n\t\t\t\tret.append(\"{\");\n\n\t\t\t\tboolean first = true;\n\n\t\t\t\tfor(T t: iter) {\n\n\t\t\t\t\tif(!first) {\n\n\t\t\t\t\t\tret.append(\", \");\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfirst = false;\n\n\t\t\t\t\tret.append(ts(t));\n\n\t\t\t\t}\n\n\t\t\t\tret.append(\"}\");\n\n\t\t\t\treturn ret.toString();\n\n\t\t\t}\n\n\n\n\t\t\tpublic static void dbg(Object... o) {\n\n\t\t\t\tif(LOCAL) {\n\n\t\t\t\t\tSystem.err.print(\"Line #\"+Thread.currentThread().getStackTrace()[2].getLineNumber()+\": [\");\n\n\t\t\t\t\tfor(int i = 0; i='0'&&c<='9');\n\n\t\t\tif(neg) {\n\n\t\t\t\treturn -ret;\n\n\t\t\t}\n\n\t\t\treturn ret;\n\n\t\t}\n\n\n\n\t\tprivate boolean isDigit(byte b) {\n\n\t\t\treturn b>='0'&&b<='9';\n\n\t\t}\n\n\n\n\t\tprivate byte skipToDigit() {\n\n\t\t\tbyte ret;\n\n\t\t\twhile(!isDigit(ret = read())&&ret!='-') ;\n\n\t\t\treturn ret;\n\n\t\t}\n\n\n\n\t\tprivate void fillBuffer() {\n\n\t\t\ttry {\n\n\t\t\t\tbytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);\n\n\t\t\t}catch(IOException e) {\n\n\t\t\t\te.printStackTrace();\n\n\t\t\t\tthrow new InputMismatchException();\n\n\t\t\t}\n\n\t\t\tif(bytesRead==-1) {\n\n\t\t\t\tbuffer[0] = -1;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tprivate byte read() {\n\n\t\t\tif(bytesRead==-1) {\n\n\t\t\t\tthrow new InputMismatchException();\n\n\t\t\t}else if(bufferPointer==bytesRead) {\n\n\t\t\t\tfillBuffer();\n\n\t\t\t}\n\n\t\t\treturn buffer[bufferPointer++];\n\n\t\t}\n\n\n\n\t}\n\n\n\n\tstatic class Output implements Closeable, Flushable {\n\n\t\tpublic StringBuilder sb;\n\n\t\tpublic OutputStream os;\n\n\t\tpublic int BUFFER_SIZE;\n\n\t\tpublic String lineSeparator;\n\n\n\n\t\tpublic Output(OutputStream os) {\n\n\t\t\tthis(os, 1<<16);\n\n\t\t}\n\n\n\n\t\tpublic Output(OutputStream os, int bs) {\n\n\t\t\tBUFFER_SIZE = bs;\n\n\t\t\tsb = new StringBuilder(BUFFER_SIZE);\n\n\t\t\tthis.os = new BufferedOutputStream(os, 1<<17);\n\n\t\t\tlineSeparator = System.lineSeparator();\n\n\t\t}\n\n\n\n\t\tpublic void println(char[] c) {\n\n\t\t\tprintln(String.valueOf(c));\n\n\t\t}\n\n\n\n\t\tpublic void println(String s) {\n\n\t\t\tsb.append(s);\n\n\t\t\tprintln();\n\n\t\t}\n\n\n\n\t\tpublic void println() {\n\n\t\t\tsb.append(lineSeparator);\n\n\t\t}\n\n\n\n\t\tprivate void flushToBuffer() {\n\n\t\t\ttry {\n\n\t\t\t\tos.write(sb.toString().getBytes());\n\n\t\t\t}catch(IOException e) {\n\n\t\t\t\te.printStackTrace();\n\n\t\t\t}\n\n\t\t\tsb = new StringBuilder(BUFFER_SIZE);\n\n\t\t}\n\n\n\n\t\tpublic void flush() {\n\n\t\t\ttry {\n\n\t\t\t\tflushToBuffer();\n\n\t\t\t\tos.flush();\n\n\t\t\t}catch(IOException e) {\n\n\t\t\t\te.printStackTrace();\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tpublic void close() {\n\n\t\t\tflush();\n\n\t\t\ttry {\n\n\t\t\t\tos.close();\n\n\t\t\t}catch(IOException e) {\n\n\t\t\t\te.printStackTrace();\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t}\n\n\n\n\tstatic class Pair implements Comparable> {\n\n\t\tpublic T1 a;\n\n\t\tpublic T2 b;\n\n\n\n\t\tpublic Pair(Pair p) {\n\n\t\t\tthis(p.a, p.b);\n\n\t\t}\n\n\n\n\t\tpublic Pair(T1 a, T2 b) {\n\n\t\t\tthis.a = a;\n\n\t\t\tthis.b = b;\n\n\t\t}\n\n\n\n\t\tpublic String toString() {\n\n\t\t\treturn a+\" \"+b;\n\n\t\t}\n\n\n\n\t\tpublic int hashCode() {\n\n\t\t\treturn Objects.hash(a, b);\n\n\t\t}\n\n\n\n\t\tpublic boolean equals(Object o) {\n\n\t\t\tif(o instanceof Pair) {\n\n\t\t\t\tPair p = (Pair) o;\n\n\t\t\t\treturn a.equals(p.a)&&b.equals(p.b);\n\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t}\n\n\n\n\t\tpublic int compareTo(Pair p) {\n\n\t\t\tint cmp = ((Comparable) a).compareTo(p.a);\n\n\t\t\tif(cmp==0) {\n\n\t\t\t\treturn ((Comparable) b).compareTo(p.b);\n\n\t\t\t}\n\n\t\t\treturn cmp;\n\n\t\t}\n\n\n\n\t}\n\n}\n\n\n\n","language":"java"} -{"contest_id":"1312","problem_id":"D","statement":"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 ajaj+1aj>aj+1, if j\u2265ij\u2265i). InputThe first line contains two integers nn and mm (2\u2264n\u2264m\u22642\u22c51052\u2264n\u2264m\u22642\u22c5105).OutputPrint one integer \u2014 the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4\nOutputCopy6\nInputCopy3 5\nOutputCopy10\nInputCopy42 1337\nOutputCopy806066790\nInputCopy100000 200000\nOutputCopy707899035\nNoteThe 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]. ","tags":["combinatorics","math"],"code":"import java.io.IOException;\n\nimport java.io.BufferedReader;\n\nimport java.io.InputStreamReader;\n\nimport java.util.StringTokenizer;\n\npublic class Solution {\n\n static final Reader input = new Reader();\n\n static final int MOD = 998244353;\n\n static int n, m;\n\n static long[] fac;\n\n public static void main(String[] args) throws IOException {\n\n n = input.nextInt();\n\n m = input.nextInt();\n\n if(n == 2) {\n\n System.out.println(0);\n\n return;\n\n }\n\n fac = new long[m+1];\n\n fac[0] = 1;\n\n fac[1] = 1;\n\n for(int i = 2; i < fac.length; ++i) fac[i] = (i*fac[i-1]) % MOD;\n\n long common = 0;\n\n for(int x = n-2; x < m; ++x) {\n\n common += (((fac[x-1] * inverse(fac[x-1 - (n-3)])) % MOD) * x ) % MOD;\n\n if(common >= MOD) common -= MOD;\n\n }\n\n long answer = 0;\n\n for(int i = 1; i < n-1; ++i) {\n\n answer += (common * inverse((fac[i-1]*fac[(n-1)-i-1]) % MOD)) % MOD;\n\n if(answer >= MOD) answer -= MOD;\n\n }\n\n System.out.println(answer);\n\n }\n\n static long inverse(long a) {\n\n return power(a, MOD-2);\n\n }\n\n static long power(long a, long b) {\n\n long result = 1;\n\n while(b > 0) {\n\n if(b % 2 == 1) result = (result*a)%MOD;\n\n a = (a*a) % MOD;\n\n b \/= 2;\n\n }\n\n return result;\n\n }\n\n static class Reader {\n\n BufferedReader reader;\n\n StringTokenizer string;\n\n public Reader() {\n\n reader = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n public String next() throws IOException {\n\n while(string == null || ! string.hasMoreElements()) {\n\n string = new StringTokenizer(reader.readLine());\n\n }\n\n return string.nextToken();\n\n }\n\n public int nextInt() throws IOException {\n\n return Integer.parseInt(next());\n\n }\n\n public long nextLong() throws IOException {\n\n return Long.parseLong(next());\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1286","problem_id":"A","statement":"A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the number of light bulbs on the garland.The second line contains nn integers p1,\u00a0p2,\u00a0\u2026,\u00a0pnp1,\u00a0p2,\u00a0\u2026,\u00a0pn (0\u2264pi\u2264n0\u2264pi\u2264n)\u00a0\u2014 the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number\u00a0\u2014 the minimum complexity of the garland.ExamplesInputCopy5\n0 5 0 2 3\nOutputCopy2\nInputCopy7\n1 0 0 5 0 0 2\nOutputCopy1\nNoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. ","tags":["dp","greedy","sortings"],"code":"import java.io.*;\n\nimport java.util.Scanner;\n\nimport java.util.*;\n\n \n\npublic class Solution {\n\n static int mod = (int) 1e9 + 7;\n\n static Kattio io = new Kattio();\n\n static int h = (int) 1e5 * 2 + 2;\n\n \n\n public static void main(String[] args) {\n\n int n = io.nextInt();\n\n int[] arr = new int[n];\n\n boolean[] vis = new boolean[n + 1];\n\n for (int i = 0; i < n; i++) {\n\n arr[i] = io.nextInt();\n\n vis[arr[i]] = true;\n\n }\n\n\n\n new Solution().solve(n, vis, arr);\n\n io.close();\n\n }\n\n \n\n public void solve(int n, boolean[] vis, int[] arr) {\n\n int odd = 0;\n\n int even = 0;\n\n for (int i = 1; i <= n; i++) {\n\n if (!vis[i]) {\n\n if (i % 2 == 0) even++;\n\n else odd++;\n\n }\n\n }\n\n int cur = 0;\n\n for (int i = 1; i < n; i++) {\n\n if (arr[i] == 0 || arr[i - 1] == 0) continue;\n\n if((arr[i] + arr[i - 1]) % 2 == 1) cur++;\n\n }\n\n\n\n List blocks = new ArrayList();\n\n int cnt = 0;\n\n int l = -1;\n\n for (int i = 0; i < n; i++) {\n\n if (arr[i] == 0) {\n\n if (i > 0 && arr[i - 1] != 0) {\n\n l = arr[i - 1] % 2;\n\n }\n\n cnt++;\n\n } else {\n\n if (cnt == 0) continue;\n\n blocks.add(new int[]{cnt, l, arr[i] % 2});\n\n cnt = 0;\n\n }\n\n }\n\n if (cnt > 0) {\n\n blocks.add(new int[]{cnt, l, -1});\n\n }\n\n\n\n List same = new ArrayList();\n\n List edge = new ArrayList();\n\n\n\n for (int[] block : blocks) {\n\n if (block[1] == -1 || block[2] == -1) {\n\n int x = -1;\n\n if (block[1] != -1) x = block[1];\n\n else x = block[2];\n\n\n\n edge.add(new int[]{block[0], x});\n\n } else if ((block[1] + block[2]) % 2 == 0) {\n\n same.add(new int[]{block[0], block[1]});\n\n }\n\n }\n\n\n\n int ans = blocks.size() - edge.size() - same.size();\n\n same.sort((a, b) -> a[0] - b[0]);\n\n for (int[] f : same) {\n\n if (f[1] == 1) {\n\n if (odd >= f[0]) odd -= f[0];\n\n else ans += 2;\n\n } else {\n\n if (even >= f[0]) even -= f[0];\n\n else ans += 2;\n\n }\n\n }\n\n for (int[] f : edge) {\n\n if (f[1] == -1) {\n\n if (n != 1) ans++;\n\n } else if (f[1] == 1) {\n\n if (odd >= f[0]) {\n\n odd -= f[0];\n\n } else ans++;\n\n } else {\n\n if (even >= f[0]) {\n\n even -= f[0];\n\n } else ans++;\n\n }\n\n }\n\n io.println(ans + cur);\n\n }\n\n \n\n public int gcd(int a, int b) {\n\n if (b == 0) return a;\n\n return gcd(b, a % b);\n\n }\n\n \n\n public int countbit(long n) {\n\n int count = 0;\n\n for (int i = 0; i < 64; i++) {\n\n if (((1L << i) & n) != 0) count++;\n\n }\n\n return count;\n\n }\n\n \n\n public int firstbit(int n) {\n\n for (int i = 31; i >= 0; i--) {\n\n if (((1 << i) & n) != 0) return i;\n\n }\n\n return -1;\n\n }\n\n}\n\n \n\n \n\nclass Kattio extends PrintWriter {\n\n private BufferedReader r;\n\n private StringTokenizer st;\n\n \/\/ \u6807\u51c6 IO\n\n public Kattio() { this(System.in, System.out); }\n\n public Kattio(InputStream i, OutputStream o) {\n\n super(o);\n\n r = new BufferedReader(new InputStreamReader(i));\n\n }\n\n \/\/ \u6587\u4ef6 IO\n\n public Kattio(String intput, String output) throws IOException {\n\n super(output);\n\n r = new BufferedReader(new FileReader(intput));\n\n }\n\n \/\/ \u5728\u6ca1\u6709\u5176\u4ed6\u8f93\u5165\u65f6\u8fd4\u56de null\n\n public String next() {\n\n try {\n\n while (st == null || !st.hasMoreTokens())\n\n st = new StringTokenizer(r.readLine());\n\n return st.nextToken();\n\n } catch (Exception e) {}\n\n return null;\n\n }\n\n public int nextInt() { return Integer.parseInt(next()); }\n\n public double nextDouble() { return Double.parseDouble(next()); }\n\n public long nextLong() { return Long.parseLong(next()); }\n\n}","language":"java"} -{"contest_id":"1284","problem_id":"A","statement":"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 (\uacbd\uc790\ub144; 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,\u2026,sns1,s2,s3,\u2026,sn and mm strings t1,t2,t3,\u2026,tmt1,t2,t3,\u2026,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\u2264n,m\u2264201\u2264n,m\u226420).The next line contains nn strings s1,s2,\u2026,sns1,s2,\u2026,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,\u2026,tmt1,t2,\u2026,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\u2264q\u226420201\u2264q\u22642020).In the next qq lines, an integer yy (1\u2264y\u22641091\u2264y\u2264109) 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\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020\nOutputCopysinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja\nNoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.","tags":["implementation","strings"],"code":"import java.util.Scanner;\n\n\n\n\/**\n\n *\n\n * @author eslam\n\n *\/\n\npublic class NewYearAndNaming {\n\n\n\n \/**\n\n * @param args the command line arguments\n\n *\/\n\n public static void main(String[] args) {\n\n Scanner input = new Scanner(System.in);\n\n int n = input.nextInt();\n\n int m = input.nextInt();\n\n String sn[] =new String[n];\n\n String sm[] =new String[m];\n\n for (int i = 0; i < sn.length; i++) {\n\n sn[i] = input.next();\n\n }\n\n for (int i = 0; i < sm.length; i++) {\n\n sm[i] = input.next();\n\n }\n\n int q = input.nextInt();\n\n for (int i = 0; i < q; i++) {\n\n int x = input.nextInt();\n\n String w = \"\";\n\n if(x%n==0){\n\n w = w+sn[n-1];\n\n }else{\n\n w = w +sn[(x%n)-1];\n\n }\n\n if(x%m==0){\n\n w = w+sm[m-1];\n\n }else{\n\n w = w +sm[(x%m)-1];\n\n }\n\n System.out.println(w);\n\n }\n\n }\n\n \n\n}\n\n","language":"java"} -{"contest_id":"1312","problem_id":"E","statement":"E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,\u2026,ana1,a2,\u2026,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1\u2264n\u22645001\u2264n\u2264500) \u2014 the initial length of the array aa.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226410001\u2264ai\u22641000) \u2014 the initial array aa.OutputPrint the only integer \u2014 the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5\n4 3 2 2 3\nOutputCopy2\nInputCopy7\n3 3 4 4 4 3 3\nOutputCopy2\nInputCopy3\n1 3 5\nOutputCopy3\nInputCopy1\n1000\nOutputCopy1\nNoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 \u2192\u2192 44 33 33 33 \u2192\u2192 44 44 33 \u2192\u2192 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 \u2192\u2192 44 44 44 44 33 33 \u2192\u2192 44 44 44 44 44 \u2192\u2192 55 44 44 44 \u2192\u2192 55 55 44 \u2192\u2192 66 44.In the third and fourth tests, you can't perform the operation at all.","tags":["dp","greedy"],"code":"import java.io.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.util.ArrayDeque;\n\nimport java.util.ArrayList;\n\nimport java.util.Arrays;\n\nimport java.util.Collections;\n\nimport java.util.Deque;\n\nimport java.util.HashMap;\n\nimport java.util.HashSet;\n\nimport java.util.List;\n\nimport java.util.Map;\n\nimport java.util.PriorityQueue;\n\nimport java.util.Queue;\n\nimport java.util.Set;\n\nimport java.util.Stack;\n\nimport java.util.StringTokenizer;\n\nimport java.util.function.BiFunction;\n\nimport java.util.function.Function;\n\n \n\npublic class Main {\n\n int a[];\n\n int n;\n\n int ddp[][];\n\n\n\n int getValue(int l, int r) {\n\n if(ddp[l][r] != 0) {\n\n return ddp[l][r];\n\n }\n\n\n\n if(l==r) {\n\n return a[l];\n\n }\n\n\n\n for(int i = l; i < r; i++) {\n\n int x1 = getValue(l, i);\n\n int x2 = getValue(i+1, r);\n\n if(x1 == x2 && x1 != -1) {\n\n ddp[l][r] = x1 +1;\n\n return x1 + 1;\n\n }\n\n }\n\n ddp[l][r] = -1;\n\n return -1;\n\n }\n\n\n\n void solve() {\n\n n = in.nextInt();\n\n ddp = new int[n][n];\n\n a = new int[n];\n\n for(int i = 0; i < n; i++) {\n\n a[i] = in.nextInt();\n\n }\n\n \n\n int dp[] = new int[n];\n\n\n\n dp[0] = 1;\n\n for(int i = 1; i < n; i++) {\n\n dp[i] = Integer.MAX_VALUE;\n\n for(int l = 0; l <= i ; l++) {\n\n int x = getValue(l, i);\n\n if(x == -1) {\n\n continue;\n\n }\n\n\n\n x = 1;\n\n if (l > 0) {\n\n x += dp[l-1];\n\n }\n\n dp[i] = Integer.min(dp[i], x);\n\n\n\n }\n\n }\n\n out(dp[n-1]);\n\n\n\n\n\n }\n\n \n\n public static void main(String[] args)\n\n {\n\n new Main().solve();\/\/.multiple();\n\n }\n\n \n\n final static FastReader in = new FastReader();\n\n private void multiple() {\n\n int t = in.nextInt();\n\n for(; t >0; t--) {\n\n solve();\n\n }\n\n }\n\n \n\n private void out(T s) {\n\n System.out.println(s);\n\n }\n\n\n\n static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n \n\n public FastReader()\n\n {\n\n br = new BufferedReader(\n\n new InputStreamReader(System.in));\n\n }\n\n \n\n String next()\n\n {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n }\n\n catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n \n\n int nextInt() { return Integer.parseInt(next()); }\n\n \n\n long nextLong() { return Long.parseLong(next()); }\n\n \n\n double nextDouble()\n\n {\n\n return Double.parseDouble(next());\n\n }\n\n \n\n String nextLine()\n\n {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n }\n\n catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1296","problem_id":"D","statement":"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\u2264n\u22642\u22c5105,1\u2264a,b,k\u22641091\u2264n\u22642\u22c5105,1\u2264a,b,k\u2264109) \u2014 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,\u2026,hnh1,h2,\u2026,hn (1\u2264hi\u22641091\u2264hi\u2264109), where hihi is the health points of the ii-th monster.OutputPrint one integer \u2014 the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3\n7 10 50 12 1 8\nOutputCopy5\nInputCopy1 1 100 99\n100\nOutputCopy1\nInputCopy7 4 2 1\n1 3 5 4 2 7 6\nOutputCopy6\n","tags":["greedy","sortings"],"code":"import java.io.*;\n\nimport java.util.*;\n\n \n\npublic class ProblemD {\n\n \n\n\tpublic static void main(String[] args) throws Exception {\n\n\t\tScanner s= new Scanner();\n\n\t\tint n = s.readInt();\n\n\t\tint a = s.readInt();\n\n\t\tint b = s.readInt();\n\n\t\tint k = s.readInt();\n\n\t\tint arr[] = new int[n];\n\n\t\tint p = a+b,ans = 0;\n\n\t\tfor(int i = 0;i0){\t\t\t\t\n\n\t\t\t\tarr[i]-=a;\t\n\n\t\t\t \n\n\t\t\t\tif(arr[i]>0 && k>=(arr[i]+a-1)\/a){\n\n\t\t\t\t\tk-=((arr[i]+a-1)\/a);\n\n\t\t\t\t\tarr[i] = 0;\n\n\t\t\t\t}\n\n\t\t\t\t\n\n\t\t\t}\n\n\t\t\tif(arr[i]<=0)ans++;\t\t\t\n\n\t\t}\n\n\t\tSystem.out.println(ans);\n\n\t}\n\n\t\n\n\tpublic static void sort(int arr[]){\n\n\t\tArrayListlist = new ArrayList<>();\n\n\t\tfor(int it:arr)list.add(it);\n\n\t\tCollections.sort(list);\n\n\t\tfor(int i = 0;i Double.toString(Math.atan2(angle.y, angle.x))).collect(Collectors.joining(\", \")));\n\n\n\n int hi = 0;\n\n for (int j = 0; j < m; j++) {\n\n while (hi < j + m && (hi <= j || angles[j].det(angles[hi % m]) > 0)) {\n\n hi++;\n\n }\n\n int cnt = hi - j;\n\n ans -= (cnt - 1L) * (cnt - 2L) * (cnt - 3L) \/ 6;\n\n }\n\n }\n\n out.ans(ans).ln();\n\n }\n\n\n\n }\n\n\n\n static class InsertionSort {\n\n private InsertionSort() {\n\n }\n\n\n\n static void sort(T[] a, int low, int high, Comparator comparator) {\n\n for (int i = low; i < high; i++) {\n\n for (int j = i; j > low && comparator.compare(a[j - 1], a[j]) > 0; j--) {\n\n ArrayUtil.swap(a, j - 1, j);\n\n }\n\n }\n\n }\n\n\n\n }\n\n\n\n static class QuickSort {\n\n private QuickSort() {\n\n }\n\n\n\n private static void med(T[] a, int low, int x, int y, int z, Comparator comparator) {\n\n if (comparator.compare(a[z], a[x]) < 0) {\n\n ArrayUtil.swap(a, low, x);\n\n } else if (comparator.compare(a[y], a[z]) < 0) {\n\n ArrayUtil.swap(a, low, y);\n\n } else {\n\n ArrayUtil.swap(a, low, z);\n\n }\n\n }\n\n\n\n static int step(T[] a, int low, int high, Comparator comparator) {\n\n int x = low + 1, y = low + (high - low) \/ 2, z = high - 1;\n\n if (comparator.compare(a[x], a[y]) < 0) {\n\n med(a, low, x, y, z, comparator);\n\n } else {\n\n med(a, low, y, x, z, comparator);\n\n }\n\n\n\n int lb = low + 1, ub = high;\n\n while (true) {\n\n while (comparator.compare(a[lb], a[low]) < 0) {\n\n lb++;\n\n }\n\n ub--;\n\n while (comparator.compare(a[low], a[ub]) < 0) {\n\n ub--;\n\n }\n\n if (lb >= ub) {\n\n return lb;\n\n }\n\n ArrayUtil.swap(a, lb, ub);\n\n lb++;\n\n }\n\n }\n\n\n\n }\n\n\n\n static interface Verified {\n\n }\n\n\n\n static final class ArrayUtil {\n\n private ArrayUtil() {\n\n }\n\n\n\n public static void swap(T[] a, int x, int y) {\n\n T t = a[x];\n\n a[x] = a[y];\n\n a[y] = t;\n\n }\n\n\n\n }\n\n\n\n static final class BitMath {\n\n private BitMath() {\n\n }\n\n\n\n public static int count(int v) {\n\n v = (v & 0x55555555) + ((v >> 1) & 0x55555555);\n\n v = (v & 0x33333333) + ((v >> 2) & 0x33333333);\n\n v = (v & 0x0f0f0f0f) + ((v >> 4) & 0x0f0f0f0f);\n\n v = (v & 0x00ff00ff) + ((v >> 8) & 0x00ff00ff);\n\n v = (v & 0x0000ffff) + ((v >> 16) & 0x0000ffff);\n\n return v;\n\n }\n\n\n\n public static int msb(int v) {\n\n if (v == 0) {\n\n throw new IllegalArgumentException(\"Bit not found\");\n\n }\n\n v |= (v >> 1);\n\n v |= (v >> 2);\n\n v |= (v >> 4);\n\n v |= (v >> 8);\n\n v |= (v >> 16);\n\n return count(v) - 1;\n\n }\n\n\n\n }\n\n\n\n static class HeapSort {\n\n private HeapSort() {\n\n }\n\n\n\n private static void heapfy(T[] a, int low, int high, int i, T val, Comparator comparator) {\n\n int child = 2 * i - low + 1;\n\n while (child < high) {\n\n if (child + 1 < high && comparator.compare(a[child], a[child + 1]) < 0) {\n\n child++;\n\n }\n\n if (comparator.compare(val, a[child]) >= 0) {\n\n break;\n\n }\n\n a[i] = a[child];\n\n i = child;\n\n child = 2 * i - low + 1;\n\n }\n\n a[i] = val;\n\n }\n\n\n\n static void sort(T[] a, int low, int high, Comparator comparator) {\n\n for (int p = (high + low) \/ 2 - 1; p >= low; p--) {\n\n heapfy(a, low, high, p, a[p], comparator);\n\n }\n\n while (high > low) {\n\n high--;\n\n T pval = a[high];\n\n a[high] = a[low];\n\n heapfy(a, low, high, low, pval, comparator);\n\n }\n\n }\n\n\n\n }\n\n\n\n static class LightWriter implements AutoCloseable {\n\n private final Writer out;\n\n private boolean autoflush = false;\n\n private boolean breaked = true;\n\n\n\n public LightWriter(Writer out) {\n\n this.out = out;\n\n }\n\n\n\n public LightWriter(OutputStream out) {\n\n this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset()));\n\n }\n\n\n\n public LightWriter print(char c) {\n\n try {\n\n out.write(c);\n\n breaked = false;\n\n } catch (IOException ex) {\n\n throw new UncheckedIOException(ex);\n\n }\n\n return this;\n\n }\n\n\n\n public LightWriter print(String s) {\n\n try {\n\n out.write(s, 0, s.length());\n\n breaked = false;\n\n } catch (IOException ex) {\n\n throw new UncheckedIOException(ex);\n\n }\n\n return this;\n\n }\n\n\n\n public LightWriter ans(String s) {\n\n if (!breaked) {\n\n print(' ');\n\n }\n\n return print(s);\n\n }\n\n\n\n public LightWriter ans(long l) {\n\n return ans(Long.toString(l));\n\n }\n\n\n\n public LightWriter ln() {\n\n print(System.lineSeparator());\n\n breaked = true;\n\n if (autoflush) {\n\n try {\n\n out.flush();\n\n } catch (IOException ex) {\n\n throw new UncheckedIOException(ex);\n\n }\n\n }\n\n return this;\n\n }\n\n\n\n public void close() {\n\n try {\n\n out.close();\n\n } catch (IOException ex) {\n\n throw new UncheckedIOException(ex);\n\n }\n\n }\n\n\n\n }\n\n\n\n static class LightScanner {\n\n private BufferedReader reader = null;\n\n private StringTokenizer tokenizer = null;\n\n\n\n public LightScanner(InputStream in) {\n\n reader = new BufferedReader(new InputStreamReader(in));\n\n }\n\n\n\n public String string() {\n\n if (tokenizer == null || !tokenizer.hasMoreTokens()) {\n\n try {\n\n tokenizer = new StringTokenizer(reader.readLine());\n\n } catch (IOException e) {\n\n throw new UncheckedIOException(e);\n\n }\n\n }\n\n return tokenizer.nextToken();\n\n }\n\n\n\n public int ints() {\n\n return Integer.parseInt(string());\n\n }\n\n\n\n public long longs() {\n\n return Long.parseLong(string());\n\n }\n\n\n\n }\n\n\n\n static class Vec2l implements Comparable {\n\n public long x;\n\n public long y;\n\n\n\n public Vec2l(long x, long y) {\n\n this.x = x;\n\n this.y = y;\n\n }\n\n\n\n public long det(Vec2l other) {\n\n return x * other.y - other.x * y;\n\n }\n\n\n\n public boolean equals(Object o) {\n\n if (this == o) return true;\n\n if (o == null || getClass() != o.getClass()) return false;\n\n Vec2l vec2i = (Vec2l) o;\n\n return x == vec2i.x &&\n\n y == vec2i.y;\n\n }\n\n\n\n public int hashCode() {\n\n return Objects.hash(x, y);\n\n }\n\n\n\n public String toString() {\n\n return \"(\" + x + \", \" + y + \")\";\n\n }\n\n\n\n public int compareTo(Vec2l o) {\n\n if (x == o.x) {\n\n return Long.compare(y, o.y);\n\n }\n\n return Long.compare(x, o.x);\n\n }\n\n\n\n public int compareToByAngle(Vec2l o) {\n\n if ((y >= 0) != (o.y >= 0)) {\n\n return y >= 0 ? 1 : -1;\n\n } else if ((x >= 0) != (o.x >= 0)) {\n\n if (y >= 0) return x >= 0 ? -1 : 1;\n\n else return x >= 0 ? 1 : -1;\n\n } else {\n\n return Long.compare(0, x * o.y - o.x * y);\n\n }\n\n }\n\n\n\n }\n\n\n\n static class IntroSort {\n\n private static int INSERTIONSORT_THRESHOLD = 16;\n\n\n\n private IntroSort() {\n\n }\n\n\n\n static void sort(T[] a, int low, int high, int maxDepth, Comparator comparator) {\n\n while (high - low > INSERTIONSORT_THRESHOLD) {\n\n if (maxDepth-- == 0) {\n\n HeapSort.sort(a, low, high, comparator);\n\n return;\n\n }\n\n int cut = QuickSort.step(a, low, high, comparator);\n\n sort(a, cut, high, maxDepth, comparator);\n\n high = cut;\n\n }\n\n InsertionSort.sort(a, low, high, comparator);\n\n }\n\n\n\n public static void sort(T[] a, Comparator comparator) {\n\n if (a.length <= INSERTIONSORT_THRESHOLD) {\n\n InsertionSort.sort(a, 0, a.length, comparator);\n\n } else {\n\n sort(a, 0, a.length, 2 * BitMath.msb(a.length), comparator);\n\n }\n\n }\n\n\n\n }\n\n}\n\n\n\n","language":"java"} -{"contest_id":"13","problem_id":"C","statement":"C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1\u2009\u2264\u2009a2\u2009\u2264\u2009...\u2009\u2264\u2009aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1\u2009\u2264\u2009N\u2009\u2264\u20095000) \u2014 the length of the initial sequence. The following N lines contain one integer each \u2014 elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer \u2014 minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1","tags":["dp","sortings"],"code":"import java.io.*;\n\nimport java.math.BigDecimal;\n\nimport java.math.BigInteger;\n\nimport java.math.RoundingMode;\n\nimport java.util.*;\n\n\n\n\/**\n\n * @author Tran Anh Tai\n\n * @template for CP codes\n\n * What a trick prob!\n\n *\/\n\npublic class ProbC {\n\n public static void main(String[] args) {\n\n InputStream inputStream = System.in;\n\n OutputStream outputStream = System.out;\n\n InputReader in = new InputReader(inputStream);\n\n PrintWriter out = new PrintWriter(outputStream);\n\n Task solver = new Task();\n\n solver.solve(in, out);\n\n out.close();\n\n }\n\n \/\/ main solver\n\n static class Task{\n\n static int MOD = 1000000007;\n\n public void solve(InputReader in, PrintWriter out) {\n\n int n = in.nextInt();\n\n long a[] = new long[n];\n\n for (int i = 0; i < n; i++){\n\n a[i] = in.nextInt();\n\n }\n\n long b[] = a.clone();\n\n Arrays.sort(b);\n\n long[][] dp = new long[2][n];\n\n for (int i = 1; i <= n; i++){\n\n for (int j = 0; j < n; j++){\n\n dp[(i & 1)][j] = dp[(i + 1) & 1][j] + Math.abs(a[i - 1]- b[j]);\n\n if (j > 0){\n\n dp[(i & 1)][j] = Math.min(dp[(i & 1)][j], dp[(i & 1)][j - 1]);\n\n }\n\n }\n\n }\n\n out.println(dp[n & 1][n - 1]);\n\n }\n\n }\n\n \/\/ fast input reader class;\n\n static class InputReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public InputReader(InputStream stream) {\n\n br = new BufferedReader(new InputStreamReader(stream));\n\n }\n\n\n\n public String nextToken() {\n\n while (st == null || !st.hasMoreTokens()) {\n\n String line = null;\n\n try {\n\n line = br.readLine();\n\n } catch (IOException e) {\n\n throw new RuntimeException(e);\n\n }\n\n if (line == null) {\n\n return null;\n\n }\n\n st = new StringTokenizer(line);\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n public int nextInt() {\n\n return Integer.parseInt(nextToken());\n\n }\n\n public long nextLong(){\n\n return Long.parseLong(nextToken());\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1305","problem_id":"D","statement":"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 \u230an2\u230b\u230an2\u230b 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\u2264n\u226410002\u2264n\u22641000), the number of vertices of the tree.Then you will read n\u22121n\u22121 lines, the ii-th of them has two integers xixi and yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n, xi\u2260yixi\u2260yi), 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\u2264u,v\u2264n1\u2264u,v\u2264n) 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 \u230an2\u230b\u230an2\u230b queries, the program will print \u22121\u22121 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 \u230an2\u230b\u230an2\u230b 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\u2264n\u226410002\u2264n\u22641000, 1\u2264r\u2264n1\u2264r\u2264n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n\u22121n\u22121 lines should contain two integers xixi and yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n)\u00a0\u2014 denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4\n\nOutputCopy\n\n\n\n\n\n? 5 6\n\n? 3 1\n\n? 1 2\n\n! 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:","tags":["constructive algorithms","dfs and similar","interactive","trees"],"code":"import java.util.*;\n\nimport java.io.*;\n\n\n\n\n\npublic class Main {\n\n static StringBuilder sb;\n\n static dsu dsu;\n\n static long fact[];\n\n static int mod = (int) (1e9 + 7);\n\n static ArrayList> graph; \/\/ set for o(1) removal\n\n static HashSet leaves;\n\n static void solve() {\n\n int n =i();\n\n graph = new ArrayList();\n\n leaves = new HashSet();\n\n for(int i =0;i1){\n\n int u = leaves.iterator().next();\n\n leaves.remove(u);\n\n \n\n int v = leaves.iterator().next();\n\n leaves.remove(v);\n\n \n\n int w = query(u,v);\n\n if(w==v||w==u){\n\n System.out.println(\"! \"+(w+1));\n\n System.out.flush();\n\n return;\n\n }\n\n \n\n delete(u,-1,w);\n\n delete(v,-1,w);\n\n \n\n if(graph.get(w).size()<=1) leaves.add(w);\n\n }\n\n \n\n int ans = leaves.iterator().next();\n\n System.out.println(\"! \"+(ans+1));\n\n System.out.flush(); \n\n }\n\n \n\n static int query(int u,int v){\n\n u++;\n\n v++;\n\n \n\n System.out.println(\"? \"+u+\" \"+v);\n\n System.out.flush();\n\n \n\n int lca = i()-1;\n\n return lca;\n\n }\n\n \n\n static void delete(int u,int p,int lca){\n\n leaves.remove(u);\n\n for(int e : graph.get(u)){\n\n if(e==p) continue;\n\n if(e==lca){\n\n graph.get(lca).remove(u);\n\n }else delete(e,u,lca);\n\n }\n\n \n\n \/\/ graph.get(u).clear();\n\n }\n\n\n\n public static void main(String[] args) {\n\n sb = new StringBuilder();\n\n int test = 1;\n\n while (test-- > 0) {\n\n solve();\n\n }\n\n System.out.println(sb);\n\n\n\n }\n\n\n\n \/*\n\n * fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i n)\n\n return (long) 0;\n\n\n\n long res = fact[n] % mod;\n\n \/\/ System.out.println(res);\n\n res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;\n\n res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;\n\n \/\/ System.out.println(res);\n\n return res;\n\n\n\n }\n\n\n\n static long p(long x, long y)\/\/ POWER FXN \/\/\n\n {\n\n if (y == 0)\n\n return 1;\n\n\n\n long res = 1;\n\n while (y > 0) {\n\n if (y % 2 == 1) {\n\n res = (res * x) % mod;\n\n y--;\n\n }\n\n\n\n x = (x * x) % mod;\n\n y = y \/ 2;\n\n\n\n }\n\n return res;\n\n }\n\n\n\n\/\/**************END******************\n\n\n\n \/\/ *************Disjoint set\n\n \/\/ union*********\/\/\n\n static class dsu {\n\n int parent[];\n\n\n\n dsu(int n) {\n\n parent = new int[n];\n\n for (int i = 0; i < n; i++)\n\n parent[i] = -1;\n\n }\n\n\n\n int find(int a) {\n\n if (parent[a] < 0)\n\n return a;\n\n else {\n\n int x = find(parent[a]);\n\n parent[a] = x;\n\n return x;\n\n }\n\n }\n\n\n\n void merge(int a, int b) {\n\n a = find(a);\n\n b = find(b);\n\n if (a == b)\n\n return;\n\n parent[b] = a;\n\n }\n\n }\n\n\n\n\/\/**************PRIME FACTORIZE **********************************\/\/\n\n static TreeMap prime(long n) {\n\n TreeMap h = new TreeMap<>();\n\n long num = n;\n\n for (int i = 2; i <= Math.sqrt(num); i++) {\n\n if (n % i == 0) {\n\n int nt = 0;\n\n while (n % i == 0) {\n\n n = n \/ i;\n\n nt++;\n\n }\n\n h.put(i, nt);\n\n }\n\n }\n\n if (n != 1)\n\n h.put((int) n, 1);\n\n return h;\n\n\n\n }\n\n\n\n\/\/****CLASS PAIR ************************************************\n\n static class Pair implements Comparable {\n\n int x;\n\n long y;\n\n\n\n Pair(int x, long y) {\n\n this.x = x;\n\n this.y = y;\n\n }\n\n\n\n public int compareTo(Pair o) {\n\n return (int) (this.y - o.y);\n\n\n\n }\n\n\n\n }\n\n\/\/****CLASS PAIR **************************************************\n\n\n\n static class InputReader {\n\n private InputStream stream;\n\n private byte[] buf = new byte[1024];\n\n private int curChar;\n\n private int numChars;\n\n private SpaceCharFilter filter;\n\n\n\n public InputReader(InputStream stream) {\n\n this.stream = stream;\n\n }\n\n\n\n public int read() {\n\n if (numChars == -1)\n\n throw new InputMismatchException();\n\n if (curChar >= numChars) {\n\n curChar = 0;\n\n try {\n\n numChars = stream.read(buf);\n\n } catch (IOException e) {\n\n throw new InputMismatchException();\n\n }\n\n if (numChars <= 0)\n\n return -1;\n\n }\n\n return buf[curChar++];\n\n }\n\n\n\n public int Int() {\n\n int c = read();\n\n while (isSpaceChar(c))\n\n c = read();\n\n int sgn = 1;\n\n if (c == '-') {\n\n sgn = -1;\n\n c = read();\n\n }\n\n int res = 0;\n\n do {\n\n if (c < '0' || c > '9')\n\n throw new InputMismatchException();\n\n res *= 10;\n\n res += c - '0';\n\n c = read();\n\n } while (!isSpaceChar(c));\n\n return res * sgn;\n\n }\n\n\n\n public String String() {\n\n int c = read();\n\n while (isSpaceChar(c))\n\n c = read();\n\n StringBuilder res = new StringBuilder();\n\n do {\n\n res.appendCodePoint(c);\n\n c = read();\n\n } while (!isSpaceChar(c));\n\n return res.toString();\n\n }\n\n\n\n public boolean isSpaceChar(int c) {\n\n if (filter != null)\n\n return filter.isSpaceChar(c);\n\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n\n }\n\n\n\n public String next() {\n\n return String();\n\n }\n\n\n\n public interface SpaceCharFilter {\n\n public boolean isSpaceChar(int ch);\n\n }\n\n }\n\n\n\n static class OutputWriter {\n\n private final PrintWriter writer;\n\n\n\n public OutputWriter(OutputStream outputStream) {\n\n writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n\n }\n\n\n\n public OutputWriter(Writer writer) {\n\n this.writer = new PrintWriter(writer);\n\n }\n\n\n\n public void print(Object... objects) {\n\n for (int i = 0; i < objects.length; i++) {\n\n if (i != 0)\n\n writer.print(' ');\n\n writer.print(objects[i]);\n\n }\n\n }\n\n\n\n public void printLine(Object... objects) {\n\n print(objects);\n\n writer.println();\n\n }\n\n\n\n public void close() {\n\n writer.close();\n\n }\n\n\n\n public void flush() {\n\n writer.flush();\n\n }\n\n }\n\n\n\n static InputReader in = new InputReader(System.in);\n\n static OutputWriter out = new OutputWriter(System.out);\n\n\n\n public static long[] sort(long[] a2) {\n\n int n = a2.length;\n\n ArrayList l = new ArrayList<>();\n\n for (long i : a2)\n\n l.add(i);\n\n Collections.sort(l);\n\n for (int i = 0; i < l.size(); i++)\n\n a2[i] = l.get(i);\n\n return a2;\n\n }\n\n\n\n public static char[] sort(char[] a2) {\n\n int n = a2.length;\n\n ArrayList l = new ArrayList<>();\n\n for (char i : a2)\n\n l.add(i);\n\n Collections.sort(l);\n\n for (int i = 0; i < l.size(); i++)\n\n a2[i] = l.get(i);\n\n return a2;\n\n }\n\n\n\n public static long pow(long x, long y) {\n\n long res = 1;\n\n while (y > 0) {\n\n if (y % 2 != 0) {\n\n res = (res * x);\/\/ % modulus;\n\n y--;\n\n\n\n }\n\n x = (x * x);\/\/ % modulus;\n\n y = y \/ 2;\n\n }\n\n return res;\n\n }\n\n\n\n\/\/GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n public static long gcd(long x, long y) {\n\n if (x == 0)\n\n return y;\n\n else\n\n return gcd(y % x, x);\n\n }\n\n \/\/ ******LOWEST COMMON MULTIPLE\n\n \/\/ *********************************************\n\n\n\n public static long lcm(long x, long y) {\n\n return (x * (y \/ gcd(x, y)));\n\n }\n\n\n\n\/\/INPUT PATTERN********************************************************\n\n public static int i() {\n\n return in.Int();\n\n }\n\n\n\n public static long l() {\n\n String s = in.String();\n\n return Long.parseLong(s);\n\n }\n\n\n\n public static String s() {\n\n return in.String();\n\n }\n\n\n\n public static int[] readArrayi(int n) {\n\n int A[] = new int[n];\n\n for (int i = 0; i < n; i++) {\n\n A[i] = i();\n\n }\n\n return A;\n\n }\n\n\n\n public static long[] readArray(long n) {\n\n long A[] = new long[(int) n];\n\n for (int i = 0; i < n; i++) {\n\n A[i] = l();\n\n }\n\n return A;\n\n }\n\n\n\n}","language":"java"} -{"contest_id":"1294","problem_id":"B","statement":"B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1\u2264j\u2264n1\u2264j\u2264n that for all ii from 11 to j\u22121j\u22121 si=tisi=ti and sj points = new ArrayList<>();\n\n for (int p = 0; p < n; p++) {\n\n StringTokenizer st = new StringTokenizer(br.readLine());\n\n int x = Integer.parseInt(st.nextToken());\n\n int y = Integer.parseInt(st.nextToken());\n\n points.add(new Point(x, y));\n\n }\n\n Collections.sort(points);\n\n if (!test(points)) pw.println(\"NO\");\n\n }\n\n\n\n pw.close();\n\n }\n\n\n\n static boolean test(ArrayList points) {\n\n Point pos = new Point(0, 0);\n\n\n\n StringBuilder sb = new StringBuilder();\n\n for (Point p : points) {\n\n if (p.x >= pos.x && p.y >= pos.y) {\n\n sb.append(diff(pos, p));\n\n pos = p;\n\n } else return false;\n\n }\n\n\n\n pw.println(\"YES\");\n\n pw.println(sb);\n\n return true;\n\n }\n\n\n\n static StringBuilder diff(Point p1, Point p2) {\n\n StringBuilder res = new StringBuilder();\n\n res.append(\"R\".repeat(Math.max(0, p2.x - p1.x)));\n\n res.append(\"U\".repeat(Math.max(0, p2.y - p1.y)));\n\n return res;\n\n }\n\n\n\n static class Point implements Comparable {\n\n public int x, y;\n\n\n\n public Point(int x, int y) {\n\n this.x = x;\n\n this.y = y;\n\n }\n\n\n\n @Override\n\n public int compareTo(Point o) {\n\n int xComp = Integer.compare(x, o.x);\n\n if (xComp != 0) return xComp;\n\n else return Integer.compare(y, o.y);\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1304","problem_id":"E","statement":"E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3\u2264n\u22641053\u2264n\u2264105), the number of vertices of the tree.Next n\u22121n\u22121 lines contain two integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n, u\u2260vu\u2260v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1\u2264q\u22641051\u2264q\u2264105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1\u2264x,y,a,b\u2264n1\u2264x,y,a,b\u2264n, x\u2260yx\u2260y, 1\u2264k\u22641091\u2264k\u2264109) \u2013 the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print \"YES\" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print \"NO\".You can print each letter in any case (upper or lower).ExampleInputCopy5\n1 2\n2 3\n3 4\n4 5\n5\n1 3 1 2 2\n1 4 1 3 2\n1 4 1 3 3\n4 2 3 3 9\n5 2 3 3 9\nOutputCopyYES\nYES\nNO\nYES\nNO\nNoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with \"YES\" answers are: 11-st query: 11 \u2013 33 \u2013 22 22-nd query: 11 \u2013 22 \u2013 33 44-th query: 33 \u2013 44 \u2013 22 \u2013 33 \u2013 44 \u2013 22 \u2013 33 \u2013 44 \u2013 22 \u2013 33 ","tags":["data structures","dfs and similar","shortest paths","trees"],"code":"\/\/ package TreeQueries;\n\n\n\nimport java.util.*;\n\nimport java.io.*;\n\n\n\npublic class addEdge {\n\n\n\n static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public FastReader() {\n\n br = new BufferedReader(\n\n new InputStreamReader(System.in));\n\n }\n\n\n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n\n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n String nextLine() {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n\n\n public static void main(String[] args) throws java.lang.Exception {\n\n FastReader sc = new FastReader();\n\n BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));\n\n int t = 1;\n\n \/\/ t = sc.nextInt();\n\n while (t-- != 0) {\n\n int n = sc.nextInt();\n\n ArrayList> adj = new ArrayList<>();\n\n for (int i = 0; i <= n; i++)\n\n adj.add(new ArrayList());\n\n for (int i = 0; i < n - 1; i++) {\n\n int u = sc.nextInt();\n\n int v = sc.nextInt();\n\n adj.get(u).add(v);\n\n adj.get(v).add(u);\n\n }\n\n int level[] = new int[n + 1];\n\n int limit = (int) (Math.log(n) \/ Math.log(2));\n\n int parent[][] = new int[n + 1][limit + 1];\n\n\n\n dfs(1, 0, 0, adj, level, parent);\n\n\n\n for (int i = 1; i <= limit; i++) {\n\n for (int j = 1; j <= n; j++) {\n\n int x = parent[j][i - 1];\n\n parent[j][i] = parent[x][i - 1];\n\n }\n\n }\n\n\n\n int q = sc.nextInt();\n\n for (int i = 0; i < q; i++) {\n\n int k = 5;\n\n int qur[] = new int[k];\n\n for (int j = 0; j < k; j++) {\n\n qur[j] = sc.nextInt();\n\n }\n\n int withoutedge = getDist(qur[2], qur[3], parent, level);\n\n int d2 = getDist(qur[2], qur[0], parent, level) + 1 + getDist(qur[1], qur[3], parent, level);\n\n int d3 = getDist(qur[3], qur[0], parent, level) + 1 + getDist(qur[1], qur[2], parent, level);\n\n int withedge = Math.min(d2, d3);\n\n int ans = Integer.MAX_VALUE;\n\n \n\n if (withedge % 2 == qur[4] % 2) {\n\n ans = withedge;\n\n }\n\n if (withoutedge % 2 == qur[4] % 2) {\n\n ans = Math.min(ans, withoutedge);\n\n }\n\n if (ans <= qur[4]) {\n\n w.write(\"YES\\n\");\n\n } else {\n\n w.write(\"NO\\n\");\n\n }\n\n }\n\n\n\n w.flush();\n\n }\n\n w.close();\n\n }\n\n\n\n private static int getDist(int a, int b, int[][] parent, int[] level) {\n\n if (level[a] > level[b]) {\n\n int temp = a;\n\n a = b;\n\n b = temp;\n\n }\n\n int diff = level[b] - level[a];\n\n int ans = 0;\n\n while (diff > 0) {\n\n int log = (int) (Math.log(diff) \/ Math.log(2));\n\n b = parent[b][log];\n\n diff -= (1 << log);\n\n ans += (1 << log);\n\n }\n\n\n\n if(a==b)return ans;\n\n for(int i=parent[0].length-1;i>=0;i--){\n\n if(parent[b][i] != parent[a][i]){\n\n a = parent[a][i];\n\n b = parent[b][i];\n\n ans += 2*(1 << (i));\n\n }\n\n }\n\n return ans+2;\n\n }\n\n\n\n private static void dfs(int i, int p, int l, ArrayList> adj, int[] level, int[][] parent) {\n\n parent[i][0] = p;\n\n level[i] = l;\n\n for (int nbr : adj.get(i)) {\n\n if (nbr == p)\n\n continue;\n\n dfs(nbr, i, l + 1, adj, level, parent);\n\n }\n\n }\n\n\n\n}","language":"java"} -{"contest_id":"1321","problem_id":"C","statement":"C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1\u2264i\u2264|s|1\u2264i\u2264|s| during each operation.For the character sisi adjacent characters are si\u22121si\u22121 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1\u2264|s|\u22641001\u2264|s|\u2264100) \u2014 the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer \u2014 the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8\nbacabcab\nOutputCopy4\nInputCopy4\nbcda\nOutputCopy3\nInputCopy6\nabbbbb\nOutputCopy5\nNoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. ","tags":["brute force","constructive algorithms","greedy","strings"],"code":"import java.util.*;\n\nimport java.io.*;\n\n \n\npublic class Main {\n\n public static void main(String[] args) throws Exception {\n\n \/\/Code here\n\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n PrintWriter wr = new PrintWriter(System.out);\n\n \n\n int n = Integer.parseInt(br.readLine());\n\n String s = br.readLine();\n\n int count = 0;\n\n \n\n for(char ch = 'z';ch>='a';ch--){\n\n for(int i =0;ibi+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\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the number of topics.The second line of the input contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u22641091\u2264bi\u2264109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer \u2014 the number of good pairs of topic.ExamplesInputCopy5\n4 8 2 6 2\n4 5 4 1 3\nOutputCopy7\nInputCopy4\n1 3 2 4\n1 3 2 4\nOutputCopy0\n","tags":["binary search","data structures","sortings","two pointers"],"code":"import java.util.*;\n\nimport java.lang.*;\n\nimport java.io.*;\n\npublic class Main\n\n{\n\n static final PrintWriter out =new PrintWriter(System.out);\n\n static final FastReader sc = new FastReader();\n\n \/\/I invented a new word!Plagiarism!\n\n \/\/Did you hear about the mathematician who\u2019s afraid of negative numbers?He\u2019ll stop at nothing to avoid them\n\n \/\/What do Alexander the Great and Winnie the Pooh have in common? Same middle name.\n\n \/\/I finally decided to sell my vacuum cleaner. All it was doing was gathering dust!\n\n \/\/ArrayList a=new ArrayList ();\n\n \/\/PriorityQueue pq=new PriorityQueue<>();\n\n \/\/char[] a = s.toCharArray();\n\n \/\/ char s[]=sc.next().toCharArray();\n\n public static boolean sorted(int a[])\n\n {\n\n int n=a.length,i;\n\n int b[]=new int[n];\n\n for(i=0;i arr=new ArrayList<>();\n\n\t ArrayList neg=new ArrayList<>();\n\n\t for(i=0;i arr, int low, int high, int x, int n)\n\n {\n\n if (high >= low) {\n\n int mid = low + (high - low) \/ 2;\n\n if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)\n\n return mid;\n\n else if (x > arr.get(mid))\n\n return first(arr, (mid + 1), high, x, n);\n\n else\n\n return first(arr, low, (mid - 1), x, n);\n\n }\n\n return -1;\n\n }\n\n\tpublic static int last(ArrayList arr, int low, int high, int x, int n)\n\n {\n\n if (high >= low) {\n\n int mid = low + (high - low) \/ 2;\n\n if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)\n\n return mid;\n\n else if (x < arr.get(mid))\n\n return last(arr, low, (mid - 1), x, n);\n\n else\n\n return last(arr, (mid + 1), high, x, n);\n\n }\n\n return -1;\n\n }\n\n\tpublic static int lis(int[] arr) {\n\n\tint n = arr.length;\n\n\tArrayList al = new ArrayList();\n\n\tal.add(arr[0]);\n\n\tfor(int i = 1 ; i=x) {\n\n\t\t\tal.add(arr[i]);\n\n\t\t}else {\n\n\t\t\tint v = upper_bound(al, 0, al.size(), arr[i]);\n\n\t\t\tal.set(v, arr[i]);\n\n\t\t}\n\n\t}\n\n\treturn al.size();\n\n}\n\n \n\n\tpublic static int lower_bound(ArrayList ar,int lo , int hi , long k)\n\n{\n\n \/\/Collections.sort(ar);\n\n int s=lo;\n\n int e=hi;\n\n while (s !=e)\n\n {\n\n int mid = s+e>>1;\n\n if (ar.get((int)mid) ar,int lo , int hi, int k)\n\n{\n\n Collections.sort(ar);\n\n int s=lo;\n\n int e=hi;\n\n while (s !=e)\n\n {\n\n int mid = s+e>>1;\n\n if (ar.get(mid) <=k)\n\n {\n\n s=mid+1;\n\n }\n\n else\n\n {\n\n e=mid;\n\n }\n\n }\n\n if(s==ar.size())\n\n {\n\n return -1;\n\n }\n\n return s;\n\n}\n\nstatic boolean isPrime(long N)\n\n {\n\n if (N<=1) return false; \n\n if (N<=3) return true; \n\n if (N%2 == 0 || N%3 == 0) return false; \n\n for (int i=5; i*i<=N; i=i+6) \n\n if (N%i == 0 || N%(i+2) == 0) \n\n return false; \n\n return true; \n\n }\n\n static int countBits(long a)\n\n {\n\n return (int)(Math.log(a)\/Math.log(2)+1);\n\n }\n\n \n\n static long fact(long N)\n\n { \n\n long mod=1000000007;\n\n long n=2; \n\n if(N<=1)return 1;\n\n else\n\n {\n\n for(int i=3; i<=N; i++)n=(n*i)%mod;\n\n }\n\n return n;\n\n }\n\n private static boolean isInteger(String s) {\n\n try {\n\n Integer.parseInt(s);\n\n } catch (NumberFormatException e) {\n\n return false;\n\n } catch (NullPointerException e) {\n\n return false;\n\n }\n\n return true;\n\n }\n\n private static long gcd(long a, long b) {\n\n if (b == 0)\n\n return a;\n\n return gcd(b, a % b);\n\n }\n\n private static long lcm(long a, long b) {\n\n return (a \/ gcd(a, b)) * b;\n\n }\n\n private static boolean isPalindrome(String str) {\n\n int i = 0, j = str.length() - 1;\n\n while (i < j)\n\n if (str.charAt(i++) != str.charAt(j--))\n\n return false;\n\n return true;\n\n }\n\n \n\n private static String reverseString(String str) {\n\n StringBuilder sb = new StringBuilder(str);\n\n return sb.reverse().toString();\n\n } \n\n\tstatic class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n \n\n public FastReader()\n\n {\n\n br = new BufferedReader(\n\n new InputStreamReader(System.in));\n\n }\n\n \n\n String next()\n\n {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n }\n\n catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n \n\n int nextInt() { return Integer.parseInt(next()); }\n\n \n\n long nextLong() { return Long.parseLong(next()); }\n\n \n\n double nextDouble()\n\n {\n\n return Double.parseDouble(next());\n\n }\n\n \n\n String nextLine()\n\n {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n }\n\n catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1315","problem_id":"C","statement":"C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,\u2026,bnb1,b2,\u2026,bn. Find the lexicographically minimal permutation a1,a2,\u2026,a2na1,a2,\u2026,a2n such that bi=min(a2i\u22121,a2i)bi=min(a2i\u22121,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\u2264t\u22641001\u2264t\u2264100).The first line of each test case consists of one integer nn\u00a0\u2014 the number of elements in the sequence bb (1\u2264n\u22641001\u2264n\u2264100).The second line of each test case consists of nn different integers b1,\u2026,bnb1,\u2026,bn\u00a0\u2014 elements of the sequence bb (1\u2264bi\u22642n1\u2264bi\u22642n).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 \u22121\u22121.Otherwise, print 2n2n integers a1,\u2026,a2na1,\u2026,a2n\u00a0\u2014 required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5\n1\n1\n2\n4 1\n3\n4 1 3\n4\n2 3 4 5\n5\n1 5 7 2 8\nOutputCopy1 2 \n-1\n4 5 1 2 3 6 \n-1\n1 3 5 6 7 9 2 4 8 10 \n","tags":["greedy"],"code":"import java.util.*;\n\nimport java.io.*;\n\npublic class Practice {\n\tstatic boolean multipleTC = true;\n\tFastReader in;\n\tPrintWriter out;\n\n\tfinal static int mod = 1000000007;\n\tfinal static int mod2 = 998244353;\n\tfinal double E = 2.7182818284590452354;\n\tfinal double PI = 3.14159265358979323846;\n\tint MAX = 100005;\n\n\tpublic static void main(String[] args) throws Exception {\n\t\tnew Practice().run();\n\t}\n\n\tvoid run() throws Exception {\n\t\tin = new FastReader();\n\t\tout = new PrintWriter(System.out);\n\t\tint T = (multipleTC) ? ni() : 1;\n\t\tpre();\n\t\tfor (int t = 1; t <= T; t++)\n\t\t\tsolve(t);\n\t\tout.flush();\n\t\tout.close();\n\t}\n\n\tvoid pre() throws Exception {\n\t}\n\n\t\/\/ All the best\n\tvoid solve(int TC) throws Exception {\n\t\tint n = ni(), arr[] = readArr(n);\n\t\tint max = 2 * n;\n\t\tboolean used[] = new boolean[max + 1];\n\t\tint res[] = new int[max];\n\t\tboolean possible = true;\n\t\tfor (int i = 0, j = 0; i < n; i++, j += 2) {\n\t\t\tif (arr[i] >= max || used[arr[i]]) {\n\t\t\t\tpossible = false;\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\tres[j] = arr[i];\n\t\t\t\tused[arr[i]] = true;\n\t\t\t}\n\t\t}\n\t\tif (possible) {\n\t\t\tfor (int i = 0, j = 1; i < n; i++, j += 2) {\n\t\t\t\tboolean found = false;\n\t\t\t\tfor (int k = arr[i] + 1; k <= max; k++) {\n\t\t\t\t\tif (!used[k]) {\n\t\t\t\t\t\tres[j] = k;\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tused[k] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!found) {\n\t\t\t\t\tpossible = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (possible) {\n\t\t\t\tStringBuilder ans = new StringBuilder();\n\t\t\t\tfor (int i : res) {\n\t\t\t\t\tans.append(i + \" \");\n\t\t\t\t}\n\t\t\t\tpn(ans);\n\t\t\t}else {\n\t\t\t\tpn(\"-1\");\n\t\t\t}\n\n\t\t} else {\n\t\t\tpn(\"-1\");\n\t\t}\n\t}\n\n\tint[] readArr(int n) throws Exception {\n\t\tint arr[] = new int[n];\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tarr[i] = ni();\n\t\t}\n\t\treturn arr;\n\t}\n\n\tvoid sort(int arr[]) {\n\t\tArrayList list = new ArrayList<>();\n\t\tfor (int i = 0; i < arr.length; i++)\n\t\t\tlist.add(arr[i]);\n\t\tCollections.sort(list);\n\t\tfor (int i = 0; i < arr.length; i++)\n\t\t\tarr[i] = list.get(i);\n\t}\n\n\tpublic long max(long... arr) {\n\t\tlong max = arr[0];\n\t\tfor (long itr : arr)\n\t\t\tmax = Math.max(max, itr);\n\t\treturn max;\n\t}\n\n\tpublic int max(int... arr) {\n\t\tint max = arr[0];\n\t\tfor (int itr : arr)\n\t\t\tmax = Math.max(max, itr);\n\t\treturn max;\n\t}\n\n\tpublic long min(long... arr) {\n\t\tlong min = arr[0];\n\t\tfor (long itr : arr)\n\t\t\tmin = Math.min(min, itr);\n\t\treturn min;\n\t}\n\n\tpublic int min(int... arr) {\n\t\tint min = arr[0];\n\t\tfor (int itr : arr)\n\t\t\tmin = Math.min(min, itr);\n\t\treturn min;\n\t}\n\n\tpublic long sum(long... arr) {\n\t\tlong sum = 0;\n\t\tfor (long itr : arr)\n\t\t\tsum += itr;\n\t\treturn sum;\n\t}\n\n\tpublic long sum(int... arr) {\n\t\tlong sum = 0;\n\t\tfor (int itr : arr)\n\t\t\tsum += itr;\n\t\treturn sum;\n\t}\n\n\tString bin(long n) {\n\t\treturn Long.toBinaryString(n);\n\t}\n\n\tString bin(int n) {\n\t\treturn Integer.toBinaryString(n);\n\t}\n\n\tstatic int bitCount(int x) {\n\t\treturn x == 0 ? 0 : (1 + bitCount(x & (x - 1)));\n\t}\n\n\tstatic void dbg(Object... o) {\n\t\tSystem.err.println(Arrays.deepToString(o));\n\t}\n\n\tint bit(long n) {\n\t\treturn (n == 0) ? 0 : (1 + bit(n & (n - 1)));\n\t}\n\n\tint abs(int a) {\n\t\treturn (a < 0) ? -a : a;\n\t}\n\n\tlong abs(long a) {\n\t\treturn (a < 0) ? -a : a;\n\t}\n\n\tvoid p(Object o) {\n\t\tout.print(o);\n\t}\n\n\tvoid pn(Object o) {\n\t\tout.println(o);\n\t}\n\n\tvoid pni(Object o) {\n\t\tout.println(o);\n\t\tout.flush();\n\t}\n\n\tString n() throws Exception {\n\t\treturn in.next();\n\t}\n\n\tString nln() throws Exception {\n\t\treturn in.nextLine();\n\t}\n\n\tint ni() throws Exception {\n\t\treturn Integer.parseInt(in.next());\n\t}\n\n\tlong nl() throws Exception {\n\t\treturn Long.parseLong(in.next());\n\t}\n\n\tdouble nd() throws Exception {\n\t\treturn Double.parseDouble(in.next());\n\t}\n\n\tclass FastReader {\n\t\tBufferedReader br;\n\t\tStringTokenizer st;\n\n\t\tpublic FastReader() {\n\t\t\tbr = new BufferedReader(new InputStreamReader(System.in));\n\t\t}\n\n\t\tpublic FastReader(String s) throws Exception {\n\t\t\tbr = new BufferedReader(new FileReader(s));\n\t\t}\n\n\t\tString next() throws Exception {\n\t\t\twhile (st == null || !st.hasMoreElements()) {\n\t\t\t\ttry {\n\t\t\t\t\tst = new StringTokenizer(br.readLine());\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tthrow new Exception(e.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn st.nextToken();\n\t\t}\n\n\t\tString nextLine() throws Exception {\n\t\t\tString str = \"\";\n\t\t\ttry {\n\t\t\t\tstr = br.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new Exception(e.toString());\n\t\t\t}\n\t\t\treturn str;\n\t\t}\n\t}\n}","language":"java"} -{"contest_id":"1305","problem_id":"A","statement":"A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1\u2264t\u22641001\u2264t\u2264100) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100) \u00a0\u2014 the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226410001\u2264ai\u22641000) \u00a0\u2014 the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u226410001\u2264bi\u22641000) \u00a0\u2014 the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,\u2026,xnx1,x2,\u2026,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,\u2026,yny1,y2,\u2026,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,\u2026,xn+ynx1+y1,x2+y2,\u2026,xn+yn should all be distinct. The numbers x1,\u2026,xnx1,\u2026,xn should be equal to the numbers a1,\u2026,ana1,\u2026,an in some order, and the numbers y1,\u2026,yny1,\u2026,yn should be equal to the numbers b1,\u2026,bnb1,\u2026,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2\n3\n1 8 5\n8 4 5\n3\n1 7 5\n6 1 2\nOutputCopy1 8 5\n8 4 5\n5 1 7\n6 2 1\nNoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.","tags":["brute force","constructive algorithms","greedy","sortings"],"code":"\/\/ Created on: 10:12:32 PM | 14-Mar-2022\n\n\n\nimport java.util.*;\n\nimport java.io.*;\n\nimport java.math.*;\n\nimport java.lang.*;\n\n\n\npublic class Main {\n\n\tstatic InputStream is;\n\n\tstatic PrintWriter out;\n\n\tstatic String INPUT = \"\";\n\n\n\n\tstatic void solve() {\n\n\t\tint caseNo = 1;\n\n\t\tfor (int T = sc.nextInt(); T > 0; T--, caseNo++) {\n\n\t\t\tsolveIt(caseNo);\n\n\t\t}\n\n\t}\n\n\n\n\t\/\/ Solution\n\n\tstatic void solveIt(int t) {\n\n\t\tint n = sc.nextInt();\n\n\t\tint a[] = sc.readIntArray(n);\n\n\t\tint b[] = sc.readIntArray(n);\n\n\t\tsort(a);\n\n\t\tsort(b);\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tSystem.out.print(a[i] + \" \");\n\n\t\t}\n\n\t\tSystem.out.println();\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tSystem.out.print(b[i] + \" \");\n\n\t\t}\n\n\t\tSystem.out.println();\n\n\t}\n\n\n\n\tstatic void revArray(int a[], int i, int j) {\n\n\t\twhile (i <= j) {\n\n\t\t\tint temp = a[i];\n\n\t\t\ta[i] = a[j];\n\n\t\t\ta[j] = temp;\n\n\t\t\ti++;\n\n\t\t\tj--;\n\n\t\t}\n\n\t}\n\n\n\n\tstatic boolean isSorted(int a[], int s, int e, boolean strict) {\n\n\t\tfor (int i = s + 1; i <= e; i++) {\n\n\t\t\tif (strict && a[i - 1] >= a[i])\n\n\t\t\t\treturn false;\n\n\t\t\tif (!strict && a[i - 1] > a[i])\n\n\t\t\t\treturn false;\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\n\n\tstatic class DSU {\n\n\t\tint rank[];\n\n\t\tint parent[];\n\n\n\n\t\tDSU(int n) {\n\n\t\t\trank = new int[n + 1];\n\n\t\t\tparent = new int[n + 1];\n\n\t\t\tfor (int i = 1; i <= n; i++) {\n\n\t\t\t\tparent[i] = i;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tint findParent(int node) {\n\n\t\t\tif (parent[node] == node)\n\n\t\t\t\treturn node;\n\n\t\t\treturn parent[node] = findParent(parent[node]);\n\n\t\t}\n\n\n\n\t\tboolean union(int x, int y) {\n\n\t\t\tint px = findParent(x);\n\n\t\t\tint py = findParent(y);\n\n\t\t\tif (px == py)\n\n\t\t\t\treturn false;\n\n\t\t\tif (rank[px] < rank[py]) {\n\n\t\t\t\tparent[px] = py;\n\n\t\t\t} else if (rank[px] > rank[py]) {\n\n\t\t\t\tparent[py] = px;\n\n\t\t\t} else {\n\n\t\t\t\tparent[px] = py;\n\n\t\t\t\trank[py]++;\n\n\t\t\t}\n\n\t\t\treturn true;\n\n\t\t}\n\n\t}\n\n\n\n\tstatic void sort(int[] a) {\n\n\t\tArrayList l = new ArrayList<>();\n\n\t\tfor (int i : a)\n\n\t\t\tl.add(i);\n\n\t\tCollections.sort(l);\n\n\t\tfor (int i = 0; i < a.length; i++)\n\n\t\t\ta[i] = l.get(i);\n\n\t}\n\n\n\n\tstatic boolean[] seiveOfEratosthenes(int n) {\n\n\t\tboolean[] isPrime = new boolean[n + 1];\n\n\t\tArrays.fill(isPrime, true);\n\n\t\tfor (int i = 2; i * i <= n; i++) {\n\n\t\t\tfor (int j = i * i; j <= n; j += i) {\n\n\t\t\t\tisPrime[j] = false;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn isPrime;\n\n\t}\n\n\n\n\tpublic static int[] seiveOnlyPrimes(int n) {\n\n\t\tif (n <= 32) {\n\n\t\t\tint[] primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 };\n\n\t\t\tfor (int i = 0; i < primes.length; i++) {\n\n\t\t\t\tif (n < primes[i]) {\n\n\t\t\t\t\treturn Arrays.copyOf(primes, i);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn primes;\n\n\t\t}\n\n\n\n\t\tint u = n + 32;\n\n\t\tdouble lu = Math.log(u);\n\n\t\tint[] ret = new int[(int) (u \/ lu + u \/ lu \/ lu * 1.5)];\n\n\t\tret[0] = 2;\n\n\t\tint pos = 1;\n\n\n\n\t\tint[] isp = new int[(n + 1) \/ 32 \/ 2 + 1];\n\n\t\tint sup = (n + 1) \/ 32 \/ 2 + 1;\n\n\n\n\t\tint[] tprimes = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 };\n\n\t\tfor (int tp : tprimes) {\n\n\t\t\tret[pos++] = tp;\n\n\t\t\tint[] ptn = new int[tp];\n\n\t\t\tfor (int i = (tp - 3) \/ 2; i < tp << 5; i += tp)\n\n\t\t\t\tptn[i >> 5] |= 1 << (i & 31);\n\n\t\t\tfor (int i = 0; i < tp; i++) {\n\n\t\t\t\tfor (int j = i; j < sup; j += tp)\n\n\t\t\t\t\tisp[j] |= ptn[i];\n\n\t\t\t}\n\n\t\t}\n\n\t\tint[] magic = { 0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17,\n\n\t\t\t\t9, 6, 16, 5, 15, 14 };\n\n\t\tint h = n \/ 2;\n\n\t\tfor (int i = 0; i < sup; i++) {\n\n\t\t\tfor (int j = ~isp[i]; j != 0; j &= j - 1) {\n\n\t\t\t\tint pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];\n\n\t\t\t\tint p = 2 * pp + 3;\n\n\t\t\t\tif (p > n)\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tret[pos++] = p;\n\n\t\t\t\tfor (int q = pp; q <= h; q += p)\n\n\t\t\t\t\tisp[q >> 5] |= 1 << (q & 31);\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn Arrays.copyOf(ret, pos);\n\n\t}\n\n\n\n\tstatic int gcd(int a, int b) {\n\n\t\tif (b == 0)\n\n\t\t\treturn a;\n\n\t\treturn gcd(b, a % b);\n\n\t}\n\n\n\n\tstatic boolean isPrime(long n) {\n\n\t\tif (n < 2)\n\n\t\t\treturn false;\n\n\t\tfor (int i = 2; i * i <= n; i++) {\n\n\t\t\tif (n % i == 0)\n\n\t\t\t\treturn false;\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\n\n\tpublic static void main(String[] args) throws Exception {\n\n\t\tlong S = System.currentTimeMillis();\n\n\t\tis = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());\n\n\t\tout = new PrintWriter(System.out);\n\n\n\n\t\tsolve();\n\n\t\tout.flush();\n\n\t\tlong G = System.currentTimeMillis();\n\n\t\tsc.tr(G - S + \"ms\");\n\n\t}\n\n\n\n\tstatic class sc {\n\n\n\n\t\tprivate static boolean endOfFile() {\n\n\t\t\tif (bufferLength == -1)\n\n\t\t\t\treturn true;\n\n\t\t\tint lptr = ptrbuf;\n\n\t\t\twhile (lptr < bufferLength)\n\n\t\t\t\tif (!isThisTheSpaceCharacter(inputBufffferBigBoi[lptr++]))\n\n\t\t\t\t\treturn false;\n\n\n\n\t\t\ttry {\n\n\t\t\t\tis.mark(1000);\n\n\t\t\t\twhile (true) {\n\n\t\t\t\t\tint b = is.read();\n\n\t\t\t\t\tif (b == -1) {\n\n\t\t\t\t\t\tis.reset();\n\n\t\t\t\t\t\treturn true;\n\n\t\t\t\t\t} else if (!isThisTheSpaceCharacter(b)) {\n\n\t\t\t\t\t\tis.reset();\n\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t} catch (IOException e) {\n\n\t\t\t\treturn true;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tprivate static byte[] inputBufffferBigBoi = new byte[1024];\n\n\t\tstatic int bufferLength = 0, ptrbuf = 0;\n\n\n\n\t\tprivate static int justReadTheByte() {\n\n\t\t\tif (bufferLength == -1)\n\n\t\t\t\tthrow new InputMismatchException();\n\n\t\t\tif (ptrbuf >= bufferLength) {\n\n\t\t\t\tptrbuf = 0;\n\n\t\t\t\ttry {\n\n\t\t\t\t\tbufferLength = is.read(inputBufffferBigBoi);\n\n\t\t\t\t} catch (IOException e) {\n\n\t\t\t\t\tthrow new InputMismatchException();\n\n\t\t\t\t}\n\n\t\t\t\tif (bufferLength <= 0)\n\n\t\t\t\t\treturn -1;\n\n\t\t\t}\n\n\t\t\treturn inputBufffferBigBoi[ptrbuf++];\n\n\t\t}\n\n\n\n\t\tprivate static boolean isThisTheSpaceCharacter(int c) {\n\n\t\t\treturn !(c >= 33 && c <= 126);\n\n\t\t}\n\n\n\n\t\tprivate static int skipItBishhhhhhh() {\n\n\t\t\tint b;\n\n\t\t\twhile ((b = justReadTheByte()) != -1 && isThisTheSpaceCharacter(b))\n\n\t\t\t\t;\n\n\t\t\treturn b;\n\n\t\t}\n\n\n\n\t\tprivate static double nextDouble() {\n\n\t\t\treturn Double.parseDouble(next());\n\n\t\t}\n\n\n\n\t\tprivate static char nextChar() {\n\n\t\t\treturn (char) skipItBishhhhhhh();\n\n\t\t}\n\n\n\n\t\tprivate static String next() {\n\n\t\t\tint b = skipItBishhhhhhh();\n\n\t\t\tStringBuilder sb = new StringBuilder();\n\n\t\t\twhile (!(isThisTheSpaceCharacter(b))) {\n\n\t\t\t\tsb.appendCodePoint(b);\n\n\t\t\t\tb = justReadTheByte();\n\n\t\t\t}\n\n\t\t\treturn sb.toString();\n\n\t\t}\n\n\n\n\t\tprivate static char[] readCharArray(int n) {\n\n\t\t\tchar[] buf = new char[n];\n\n\t\t\tint b = skipItBishhhhhhh(), p = 0;\n\n\t\t\twhile (p < n && !(isThisTheSpaceCharacter(b))) {\n\n\t\t\t\tbuf[p++] = (char) b;\n\n\t\t\t\tb = justReadTheByte();\n\n\t\t\t}\n\n\t\t\treturn n == p ? buf : Arrays.copyOf(buf, p);\n\n\t\t}\n\n\n\n\t\tprivate static char[][] readCharMatrix(int n, int m) {\n\n\t\t\tchar[][] map = new char[n][];\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t\tmap[i] = readCharArray(m);\n\n\t\t\treturn map;\n\n\t\t}\n\n\n\n\t\tprivate static int[] readIntArray(int n) {\n\n\t\t\tint[] a = new int[n];\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t\ta[i] = nextInt();\n\n\t\t\treturn a;\n\n\t\t}\n\n\n\n\t\tprivate static long[] readLongArray(int n) {\n\n\t\t\tlong[] a = new long[n];\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t\ta[i] = nextLong();\n\n\t\t\treturn a;\n\n\t\t}\n\n\n\n\t\tprivate static int nextInt() {\n\n\t\t\tint num = 0, b;\n\n\t\t\tboolean minus = false;\n\n\t\t\twhile ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))\n\n\t\t\t\t;\n\n\t\t\tif (b == '-') {\n\n\t\t\t\tminus = true;\n\n\t\t\t\tb = justReadTheByte();\n\n\t\t\t}\n\n\n\n\t\t\twhile (true) {\n\n\t\t\t\tif (b >= '0' && b <= '9') {\n\n\t\t\t\t\tnum = num * 10 + (b - '0');\n\n\t\t\t\t} else {\n\n\t\t\t\t\treturn minus ? -num : num;\n\n\t\t\t\t}\n\n\t\t\t\tb = justReadTheByte();\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tprivate static long nextLong() {\n\n\t\t\tlong num = 0;\n\n\t\t\tint b;\n\n\t\t\tboolean minus = false;\n\n\t\t\twhile ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))\n\n\t\t\t\t;\n\n\t\t\tif (b == '-') {\n\n\t\t\t\tminus = true;\n\n\t\t\t\tb = justReadTheByte();\n\n\t\t\t}\n\n\n\n\t\t\twhile (true) {\n\n\t\t\t\tif (b >= '0' && b <= '9') {\n\n\t\t\t\t\tnum = num * 10 + (b - '0');\n\n\t\t\t\t} else {\n\n\t\t\t\t\treturn minus ? -num : num;\n\n\t\t\t\t}\n\n\t\t\t\tb = justReadTheByte();\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tprivate static void tr(Object... o) {\n\n\t\t\tif (INPUT.length() != 0)\n\n\t\t\t\tSystem.out.println(Arrays.deepToString(o));\n\n\t\t}\n\n\t}\n\n}\n\n","language":"java"} -{"contest_id":"1324","problem_id":"E","statement":"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\u22121ai\u22121 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\u2264n\u22642000,3\u2264h\u22642000,0\u2264l\u2264r= 0; j--) {\n\n long v = (sum - j) % h;\n\n s[j] = s[j] + (v >= l && v <= r ? 1 : 0);\n\n if (j > 0) {\n\n s[j] = Math.max(s[j - 1] + (v >= l && v <= r ? 1 : 0), s[j]);\n\n }\n\n ans = Math.max(ans, s[j]);\n\n }\n\n }\n\n io.println(ans);\n\n io.flush();\n\n }\n\n\n\n\n\n public static class Kattio extends PrintWriter {\n\n private BufferedReader r;\n\n private StringTokenizer st;\n\n\n\n \/\/ \u6807\u51c6 IO\n\n public Kattio() {\n\n this(System.in, System.out);\n\n }\n\n\n\n public Kattio(InputStream i, OutputStream o) {\n\n super(o);\n\n r = new BufferedReader(new InputStreamReader(i));\n\n }\n\n\n\n \/\/ \u6587\u4ef6 IO\n\n public Kattio(String intput, String output) throws IOException {\n\n super(output);\n\n r = new BufferedReader(new FileReader(intput));\n\n }\n\n\n\n \/\/ \u5728\u6ca1\u6709\u5176\u4ed6\u8f93\u5165\u65f6\u8fd4\u56de null\n\n public String next() {\n\n try {\n\n while (st == null || !st.hasMoreTokens())\n\n st = new StringTokenizer(r.readLine());\n\n return st.nextToken();\n\n } catch (Exception e) {\n\n }\n\n return null;\n\n }\n\n\n\n public int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n public double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n public long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n }\n\n}\n\n","language":"java"} -{"contest_id":"1294","problem_id":"F","statement":"F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3\u2264n\u22642\u22c51053\u2264n\u22642\u22c5105) \u2014 the number of vertices in the tree. Next n\u22121n\u22121 lines describe the edges of the tree in form ai,biai,bi (1\u2264ai1\u2264ai, bi\u2264nbi\u2264n, ai\u2260biai\u2260bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres \u2014 the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1\u2264a,b,c\u2264n1\u2264a,b,c\u2264n and a\u2260,b\u2260c,a\u2260ca\u2260,b\u2260c,a\u2260c.If there are several answers, you can print any.ExampleInputCopy8\n1 2\n2 3\n3 4\n4 5\n4 6\n3 7\n3 8\nOutputCopy5\n1 8 6\nNoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.","tags":["dfs and similar","dp","greedy","trees"],"code":"import java.io.BufferedReader;\n\nimport java.io.BufferedWriter;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.io.OutputStreamWriter;\n\nimport java.util.ArrayList;\n\nimport java.util.Arrays;\n\nimport java.util.Collections;\n\nimport java.util.Comparator;\n\nimport java.util.Deque;\n\nimport java.util.HashMap;\n\nimport java.util.HashSet;\n\nimport java.util.LinkedList;\n\nimport java.util.Queue;\n\nimport java.util.Random;\n\nimport java.util.Scanner;\n\nimport java.util.StringTokenizer;\n\nimport java.util.Vector;\n\n\n\npublic class Main {\n\n static int mod = (int) (1e9) + 7;\n\n\n\n \/* ======================DSU===================== *\/\n\n static class dsu {\n\n static int parent[], n;\/\/ min[],value[];\n\n static long size[];\n\n\n\n dsu(int n) {\n\n parent = new int[n + 1];\n\n size = new long[n + 1];\n\n \/\/ min=new int[n+1];\n\n \/\/ value=new int[n+1];\n\n Main.dsu.n = n;\n\n makeSet();\n\n }\n\n\n\n static void makeSet() {\n\n for (int i = 1; i <= n; i++) {\n\n parent[i] = i;\n\n size[i] = 1;\n\n \/\/ min[i]=i;\n\n }\n\n }\n\n\n\n static int find(int a) {\n\n if (parent[a] == a)\n\n return a;\n\n else {\n\n return parent[a] = find(parent[a]);\/\/ Path Compression\n\n }\n\n }\n\n\n\n static void union(int a, int b) {\n\n int setA = find(a);\n\n int setB = find(b);\n\n if (setA == setB)\n\n return;\n\n if (size[setA] >= size[setB]) {\n\n parent[setB] = setA;\n\n size[setA] += size[setB];\n\n } else {\n\n parent[setA] = setB;\n\n size[setB] += size[setA];\n\n }\n\n }\n\n }\n\n\n\n \/* ======================================================== *\/\n\n static class Pair implements Comparator {\n\n X x;\n\n Y y;\n\n\n\n \/\/ Constructor\n\n public Pair(X x, Y y) {\n\n this.x = x;\n\n this.y = y;\n\n }\n\n\n\n public Pair() {\n\n\n\n }\n\n\n\n @Override\n\n public int compare(Main.Pair o1, Main.Pair o2) {\n\n return ((int) (o1.y.intValue() - o2.y.intValue()));\/\/ Ascending Order based on 'y'\n\n }\n\n }\n\n\n\n \/* ===============================Tries================================= *\/\n\n static class TrieNode {\n\n private HashMap children = new HashMap<>();\n\n public int size;\n\n boolean endOfWord;\n\n\n\n public void putChildIfAbsent(char ch) {\n\n children.putIfAbsent(ch, new TrieNode());\n\n }\n\n\n\n public TrieNode getChild(char ch) {\n\n return children.get(ch);\n\n }\n\n }\n\n\n\n static private TrieNode root;\n\n\n\n public static void insert(String str) {\n\n TrieNode curr = root;\n\n for (char ch : str.toCharArray()) {\n\n curr.putChildIfAbsent(ch);\n\n curr = curr.getChild(ch);\n\n curr.size++;\n\n }\n\n \/\/ mark the current nodes endOfWord as true\n\n curr.endOfWord = true;\n\n }\n\n\n\n public static int search(String word) {\n\n TrieNode curr = root;\n\n\n\n for (char ch : word.toCharArray()) {\n\n curr = curr.getChild(ch);\n\n if (curr == null) {\n\n return 0;\n\n }\n\n }\n\n \/\/ size contains words starting with prefix- word\n\n return curr.size;\n\n }\n\n\n\n public boolean delete(TrieNode current, String word, int index) {\n\n if (index == word.length()) {\n\n \/\/ when end of word is reached only delete if currrent.endOfWord is true.\n\n if (!current.endOfWord) {\n\n return false;\n\n }\n\n current.endOfWord = false;\n\n \/\/ if current has no other mapping then return true\n\n return current.children.size() == 0;\n\n }\n\n char ch = word.charAt(index);\n\n TrieNode node = current.children.get(ch);\n\n if (node == null) {\n\n return false;\n\n }\n\n boolean shouldDeleteCurrentNode = delete(node, word, index + 1);\n\n\n\n \/\/ if true is returned then delete the mapping of character and trienode\n\n \/\/ reference from map.\n\n if (shouldDeleteCurrentNode) {\n\n current.children.remove(ch);\n\n \/\/ return true if no mappings are left in the map.\n\n return current.children.size() == 0;\n\n }\n\n return false;\n\n }\n\n\n\n \/* ================================================================= *\/\n\n\n\n static boolean isPrime(long n) {\n\n if (n <= 1)\n\n return false;\n\n if (n <= 3)\n\n return true;\n\n if (n % 2 == 0 || n % 3 == 0)\n\n return false;\n\n for (long i = 5; i * i <= n; i = i + 6)\n\n if (n % i == 0 || n % (i + 2) == 0)\n\n return false;\n\n return true;\n\n }\n\n\n\n static Pair lowerBound(long[] a, long x) { \/\/ x is the target, returns lowerBound. If not found\n\n \/\/ return -1\n\n int l = -1, r = a.length;\n\n while (l + 1 < r) {\n\n int m = (l + r) >>> 1;\n\n if (a[m] == x) {\n\n return new Pair<>(m, 1);\n\n }\n\n if (a[m] >= x)\n\n r = m;\n\n else\n\n l = m;\n\n }\n\n return new Pair<>(r, 0);\n\n }\n\n\n\n static Pair upperBound(long[] a, long x) {\/\/ x is the target, returns upperBound. If not found\n\n int l = -1, r = a.length;\n\n while (l + 1 < r) {\n\n int m = (l + r) >>> 1;\n\n if (a[m] == x) {\n\n return new Pair<>(m, 1);\n\n }\n\n if (a[m] <= x)\n\n l = m;\n\n else\n\n r = m;\n\n }\n\n return new Pair<>(l + 1, 0);\n\n }\n\n\n\n static long gcd(long a, long b) {\n\n if (a == 0)\n\n return b;\n\n return gcd(b % a, a);\n\n }\n\n\n\n static long lcm(long a, long b) {\n\n return (a * b) \/ gcd(a, b);\n\n }\n\n\n\n static long power(long x, long y) {\n\n long res = 1;\n\n while (y > 0) {\n\n if (y % 2 == 1)\n\n res = (res * x);\n\n y >>= 1;\n\n x = (x * x);\n\n }\n\n return res;\n\n }\n\n\n\n public double binPow(double x, int n) {\/\/ binary exponentiation with negative power as well\n\n if (n == 0)\n\n return 1.0;\n\n double binPow = binPow(x, n \/ 2);\n\n if (n % 2 == 0) {\n\n return binPow * binPow;\n\n } else {\n\n return n > 0 ? (binPow * binPow * x) : (binPow * binPow \/ x);\n\n }\n\n }\n\n\n\n static long ceil(long x, long y) {\n\n return (x % y == 0 ? x \/ y : (x \/ y + 1));\n\n }\n\n\n\n \/*\n\n * ===========Modular Operations==================\n\n *\/\n\n static long modPower(long x, long y, long p) {\n\n long res = 1;\n\n x = x % p;\n\n while (y > 0) {\n\n if (y % 2 == 1)\n\n res = (res * x) % p;\n\n y = y >> 1; \/\/ y = y\/2\n\n x = (x * x) % p;\n\n }\n\n return res;\n\n }\n\n\n\n static long modInverse(long n, long p) {\n\n return modPower(n, p - 2, p);\n\n }\n\n\n\n static long modAdd(long a, long b) {\n\n return ((a + b + mod) % mod);\n\n }\n\n\n\n static long modMul(long a, long b) {\n\n return ((a % mod) * (b % mod)) % mod;\n\n }\n\n\n\n static long[] fac = new long[200000 + 5];\n\n static long[] invFac = new long[200000 + 5];\n\n\n\n static long nCrModPFermat(int n, int r) {\n\n if (r == 0)\n\n return 1;\n\n \/\/ return (fac[n] * modInverse(fac[r], mod) % mod * modInverse(fac[n - r], mod)\n\n \/\/ % mod) % mod;\n\n return (fac[n] * invFac[r] % mod * invFac[n - r] % mod) % mod;\n\n }\n\n\n\n \/*\n\n * ===============================================\n\n *\/\n\n\n\n static void ruffleSort(long[] a) {\n\n int n = a.length;\n\n Random r = new Random();\n\n for (int i = 0; i < a.length; i++) {\n\n int oi = r.nextInt(n);\n\n long temp = a[i];\n\n a[i] = a[oi];\n\n a[oi] = temp;\n\n }\n\n Arrays.sort(a);\n\n }\n\n\n\n static void ruffleSort(int[] a) {\n\n int n = a.length;\n\n Random r = new Random();\n\n for (int i = 0; i < a.length; i++) {\n\n int oi = r.nextInt(n);\n\n int temp = a[i];\n\n a[i] = a[oi];\n\n a[oi] = temp;\n\n }\n\n Arrays.sort(a);\n\n }\n\n\n\n static boolean isVowel(char ch) {\n\n return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';\n\n }\n\n\n\n static String binString32(int n) {\n\n StringBuilder str = new StringBuilder(\"\");\n\n String bin = Integer.toBinaryString(n);\n\n if (bin.length() != 32) {\n\n for (int k = 0; k < 32 - bin.length(); k++) {\n\n str.append(\"0\");\n\n }\n\n str.append(bin);\n\n }\n\n return str.toString();\n\n }\n\n\n\n static class sparseTable {\n\n public static int st[][];\n\n public static int log = 4;\n\n\n\n static int func(int a, int b) {\/\/ make func as per question(here min range query)\n\n return (int) gcd(a, b);\n\n }\n\n\n\n void makeTable(int n, int a[]) {\n\n\n\n st = new int[n][log];\n\n for (int i = 0; i < n; i++) {\n\n st[i][0] = a[i];\n\n }\n\n for (int j = 1; j < log; j++) {\n\n for (int i = 0; i + (1 << j) <= n; i++) {\n\n st[i][j] = func(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);\n\n }\n\n }\n\n }\n\n\n\n static int query(int l, int r) {\n\n int length = r - l + 1;\n\n int k = 0;\n\n while ((1 << (k + 1)) <= length) {\n\n k++;\n\n }\n\n return func(st[l][k], st[r - (1 << k) + 1][k]);\n\n }\n\n\n\n static void printTable(int n) {\n\n for (int j = 0; j < log; j++) {\n\n for (int i = 0; i < n; i++) {\n\n System.out.print(st[i][j] + \" \");\n\n }\n\n System.out.println();\n\n }\n\n }\n\n }\n\n\n\n \/*\n\n * ====================================Main=================================\n\n *\/\n\n\n\n \/\/ static int st[], a[];\n\n\n\n \/\/ static void buildTree(int treeIndex, int lo, int hi) {\n\n \/\/ if (hi == lo) {\n\n \/\/ st[treeIndex] = a[lo];\n\n \/\/ return;\n\n \/\/ }\n\n \/\/ int mid = (lo + hi) \/ 2;\n\n \/\/ buildTree(treeIndex * 2 + 1, lo, mid);\n\n \/\/ buildTree(treeIndex * 2 + 2, mid + 1, hi);\n\n \/\/ st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]);\n\n \/\/ }\n\n\n\n \/\/ static void update(int treeIndex, int lo, int hi, int arrIndex, int val) {\n\n \/\/ if (hi == lo) {\n\n \/\/ st[treeIndex] = val;\n\n \/\/ a[arrIndex] = val;\n\n \/\/ return;\n\n \/\/ }\n\n \/\/ int mid = (hi + lo) \/ 2;\n\n \/\/ if (mid < arrIndex) {\n\n \/\/ update(treeIndex * 2 + 2, mid + 1, hi, arrIndex, val);\n\n \/\/ } else {\n\n \/\/ update(treeIndex * 2 + 1, lo, mid, arrIndex, val);\n\n \/\/ }\n\n \/\/ st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]);\n\n \/\/ }\n\n\n\n \/\/ static int query(int treeIndex, int lo, int hi, int l, int r) {\n\n \/\/ if (l <= lo && r >= hi) {\n\n \/\/ return st[treeIndex];\n\n \/\/ }\n\n \/\/ if (l > hi || r < lo) {\n\n \/\/ return 0;\n\n \/\/ }\n\n \/\/ int mid = (hi + lo) \/ 2;\n\n \/\/ return query(treeIndex * 2 + 1, lo, mid, l, Math.min(mid, r));\n\n \/\/ }\n\n\n\n \/\/ static int merge(int a, int b) {\n\n \/\/ return a + b;\n\n \/\/ }\n\n\n\n public static long findKthPositive(long[] A, long k) {\n\n int l = 0, r = A.length, m;\n\n while (l < r) {\n\n m = (l + r) \/ 2;\n\n if (A[m] - 1 - m < k)\n\n l = m + 1;\n\n else\n\n r = m;\n\n }\n\n return l + k;\n\n }\n\n\n\n static int[] z_function(char ar[]) {\n\n int[] z = new int[ar.length];\n\n z[0] = ar.length;\n\n int l = 0;\n\n int r = 0;\n\n for (int i = 1; i < ar.length; i++) {\n\n if (r < i) {\n\n l = i;\n\n r = i;\n\n while (r < ar.length && ar[r - l] == ar[r])\n\n r++;\n\n z[i] = r - l;\n\n r--;\n\n } else {\n\n int k = i - l;\n\n if (z[k] < r - i + 1) {\n\n z[i] = z[k];\n\n } else {\n\n l = i;\n\n while (r < ar.length && ar[r - l] == ar[r])\n\n r++;\n\n z[i] = r - l;\n\n r--;\n\n }\n\n }\n\n }\n\n return z;\n\n }\n\n\n\n static void mergeSort(int a[]) {\n\n int n = a.length;\n\n if (n >= 2) {\n\n int mid = n \/ 2;\n\n int left[] = new int[mid];\n\n int right[] = new int[n - mid];\n\n for (int i = 0; i < mid; i++) {\n\n left[i] = a[i];\n\n }\n\n for (int i = mid; i < n; i++) {\n\n right[i - mid] = a[i];\n\n }\n\n mergeSort(left);\n\n mergeSort(right);\n\n mergeSortedArray(left, right, a);\n\n }\n\n }\n\n\n\n static void mergeSortedArray(int left[], int right[], int a[]) {\n\n int i = 0, j = 0, k = 0, n = left.length, m = right.length;\n\n while (i != n && j != m) {\n\n if (left[i] < right[j]) {\n\n a[k++] = left[i++];\n\n } else {\n\n a[k++] = right[j++];\n\n }\n\n }\n\n while (i != n) {\n\n a[k++] = left[i++];\n\n }\n\n while (j != m) {\n\n a[k++] = right[j++];\n\n }\n\n }\n\n\n\n \/\/ BINARY SEARCH\n\n \/\/ count of set bits in a particular position\n\n \/\/ suffix max array\/ suffix sum array\/ prefix\n\n static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public FastReader() {\n\n br = new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n\n\n String next() {\n\n while (st == null || !st.hasMoreElements()) {\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n\n\n double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n\n\n String nextLine() {\n\n String str = \"\";\n\n try {\n\n str = br.readLine();\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n\n\n int[] intArr(int n) {\n\n int res[] = new int[n];\n\n for (int i = 0; i < n; i++)\n\n res[i] = nextInt();\n\n return res;\n\n }\n\n\n\n long[] longArr(int n) {\n\n long res[] = new long[n];\n\n for (int i = 0; i < n; i++)\n\n res[i] = nextLong();\n\n return res;\n\n }\n\n }\n\n\n\n static FastReader f = new FastReader();\n\n static BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));\n\n static ArrayList> g = new ArrayList<>();\n\n static HashSet set = new HashSet<>();\n\n static int maxLevel = 0, farthestNode = -1;\n\n\n\n public static void main(String args[]) throws Exception {\n\n int t = 1;\n\n \/\/ t = f.nextInt();\n\n int tc = 1;\n\n \/\/ fac[0] = 1;\n\n \/\/ for (int i = 1; i <= 200000; i++) {\n\n \/\/ fac[i] = fac[i - 1] * i % mod;\n\n \/\/ invFac[i] = modInverse(fac[i], mod);\n\n \/\/ }\n\n while (t-- != 0) {\n\n int n = f.nextInt();\n\n for (int i = 0; i <= n; i++) {\n\n g.add(new ArrayList<>());\n\n }\n\n for (int i = 0; i < n - 1; i++) {\n\n int u = f.nextInt();\n\n int v = f.nextInt();\n\n g.get(u).add(v);\n\n g.get(v).add(u);\n\n }\n\n dfs(1, -1, 0);\n\n int endPt1 = farthestNode;\n\n dfs(farthestNode, -1, 0);\n\n int endPt2 = farthestNode;\n\n \/\/ w.write(endPt1 + \" \" + endPt2 + \"\\n\");\n\n Vector stack = new Vector();\n\n nodesInTheDia(endPt1, endPt2, n, stack);\n\n \/\/ w.write(set+\"\\n\");\n\n int max = 0, maxNodeOutsideDiameter = -1;\n\n for (int node : set) {\n\n \/\/ int level[] = new int[n + 1];\n\n \/\/ int vis[] = new int[n + 1];\n\n \/\/ vis[node] = 1;\n\n \/\/ level[node] = 0;\n\n \/\/ Queue q = new LinkedList<>();\n\n \/\/ q.add(node);\n\n \/\/ int flag = 0;\n\n \/\/ while (!q.isEmpty()) {\n\n \/\/ int cur = q.poll();\n\n \/\/ for (int child : g.get(cur)) {\n\n \/\/ if (vis[child] == 0 && !set.contains(child)) {\n\n \/\/ vis[child] = 1;\n\n \/\/ level[child] = level[cur] + 1;\n\n \/\/ q.add(child);\n\n \/\/ flag = 1;\n\n \/\/ }\n\n \/\/ }\n\n \/\/ }\n\n\n\n \/\/ if (flag == 1) {\n\n \/\/ for (int i = 1; i <= n; i++) {\n\n \/\/ if (level[i] > max) {\n\n \/\/ max = level[i];\n\n \/\/ maxNodeOutsideDiameter = i;\n\n \/\/ }\n\n \/\/ }\n\n \/\/ }\n\n Pair p=maxDepthNode(node,0,0);\n\n if(p.y>=max) {\n\n max = p.y;\n\n maxNodeOutsideDiameter = p.x;\n\n }\n\n \/\/ w.write(p.y+\" \"+p.x+\" \"+node+\"\\n\");\n\n }\n\n if(maxNodeOutsideDiameter==-1 || maxNodeOutsideDiameter==endPt1 || maxNodeOutsideDiameter==endPt2) {\n\n for(int i:set){\n\n if(i!=endPt1 && i!=endPt2){\n\n maxNodeOutsideDiameter=i;\n\n break;\n\n }\n\n }\n\n }\n\n w.write((set.size() - 1 + max) + \"\\n\");\n\n w.write(endPt1 + \" \" + endPt2 + \" \" + maxNodeOutsideDiameter + \"\\n\");\n\n }\n\n w.flush();\n\n }\n\n static Pair maxDepthNode(int node,int parent,int depth){\n\n \/\/ if(g.get(node).size()==1){\n\n \/\/ return new Pair<>(node,depth);\n\n \/\/ }\n\n Pair max=new Pair<>(node,depth);\n\n for(int child:g.get(node)){\n\n if(child!=parent && !set.contains(child)){\n\n Pair p=maxDepthNode(child,node,depth+1);\n\n if(p.y>max.y){\n\n max=p;\n\n }\n\n }\n\n }\n\n return max;\n\n }\n\n static void dfs(int node, int parent, int level) {\n\n \/\/ System.out.println(node);\n\n if (level >= maxLevel) {\n\n maxLevel = level;\n\n farthestNode = node;\n\n }\n\n for (int i : g.get(node)) {\n\n if (i != parent) {\n\n dfs(i, node, level + 1);\n\n }\n\n }\n\n }\n\n\n\n static void printPath(Vector stack) {\n\n for (int i = 0; i < stack.size(); i++) {\n\n set.add(stack.get(i));\n\n }\n\n }\n\n\n\n static void DFS(boolean vis[], int x, int y, Vector stack) {\n\n stack.add(x);\n\n if (x == y) {\n\n printPath(stack);\n\n return;\n\n }\n\n vis[x] = true;\n\n if (g.get(x).size() > 0) {\n\n for (int j = 0; j < g.get(x).size(); j++) {\n\n if (vis[g.get(x).get(j)] == false) {\n\n DFS(vis, g.get(x).get(j), y, stack);\n\n }\n\n }\n\n }\n\n stack.remove(stack.size() - 1);\n\n }\n\n\n\n static void nodesInTheDia(int x, int y, int n, Vector stack) {\n\n boolean vis[] = new boolean[n + 1];\n\n DFS(vis, x, y, stack);\n\n }\n\n\n\n}\n\n\/*\n\n \n\n *\/","language":"java"} -{"contest_id":"1285","problem_id":"C","statement":"C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1\u2264X\u226410121\u2264X\u22641012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2\nOutputCopy1 2\nInputCopy6\nOutputCopy2 3\nInputCopy4\nOutputCopy1 4\nInputCopy1\nOutputCopy1 1\n","tags":["brute force","math","number theory"],"code":"\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.util.*;\nimport static java.lang.Math.*;\nimport static java.util.Arrays.sort;\n\n\n\npublic class Codeforces {\n public static void main(String[] args) {\n FastReader fastReader = new FastReader();\n PrintWriter out = new PrintWriter(System.out);\n int tt = 1;\n while(tt--> 0){\n long x =fastReader.nextLong();\n ArrayList left = new ArrayList<>();\n long ans1 = 1, ans2 = x;\n for(long i = 1; i *i <= x ; i++){\n if(x%i == 0 && lcm(i,(x\/i)) == x){\n if(max(ans1,ans2) > max(i,(x\/i))){\n ans1= i;\n ans2 = (x\/i);\n }\n\n }\n }\n\n \/*\n Collections.sort(left);\n for(int i = 0 ;i < left.size() ; i++){\n if(left.get(i) >= max(ans1,ans2)) break;\n for(int j= i; j < left.size(); j++){\n if(left.get(i) >= max(ans1,ans2)) break;\n if(lcm(left.get(i),left.get(j)) == x && max(left.get(i),left.get(j)) < max(ans1,ans2)){\n ans1 = left.get(i);\n ans2 = left.get(j);\n }\n }\n }\n out.println(left.size());\n out.println(sqrt(x));\n\n *\/\n out.println(ans1 + \" \" + ans2);\n\n }\n\n out.close();\n }\n\n\n\n\n static class Pair{\n int x;\n int y;\n Pair(int x, int y){\n this.x = x;\n this.y = y;\n }\n\n }\n\n\n \/\/ constants\n static final int IBIG = 1000000007;\n static final int IMAX = 2147483647;\n static final long LMAX = 9223372036854775807L;\n static Random __r = new Random();\n\n \/\/ math util\n static int minof(int a, int b, int c) {\n return min(a, min(b, c));\n }\n\n static int minof(int... x) {\n if (x.length == 1)\n return x[0];\n if (x.length == 2)\n return min(x[0], x[1]);\n if (x.length == 3)\n return min(x[0], min(x[1], x[2]));\n int min = x[0];\n for (int i = 1; i < x.length; ++i)\n if (x[i] < min)\n min = x[i];\n return min;\n }\n\n static long minof(long a, long b, long c) {\n return min(a, min(b, c));\n }\n\n static long minof(long... x) {\n if (x.length == 1)\n return x[0];\n if (x.length == 2)\n return min(x[0], x[1]);\n if (x.length == 3)\n return min(x[0], min(x[1], x[2]));\n long min = x[0];\n for (int i = 1; i < x.length; ++i)\n if (x[i] < min)\n min = x[i];\n return min;\n }\n\n static int maxof(int a, int b, int c) {\n return max(a, max(b, c));\n }\n\n static int maxof(int... x) {\n if (x.length == 1)\n return x[0];\n if (x.length == 2)\n return max(x[0], x[1]);\n if (x.length == 3)\n return max(x[0], max(x[1], x[2]));\n int max = x[0];\n for (int i = 1; i < x.length; ++i)\n if (x[i] > max)\n max = x[i];\n return max;\n }\n\n static long maxof(long a, long b, long c) {\n return max(a, max(b, c));\n }\n\n static long maxof(long... x) {\n if (x.length == 1)\n return x[0];\n if (x.length == 2)\n return max(x[0], x[1]);\n if (x.length == 3)\n return max(x[0], max(x[1], x[2]));\n long max = x[0];\n for (int i = 1; i < x.length; ++i)\n if (x[i] > max)\n max = x[i];\n return max;\n }\n\n static int powi(int a, int b) {\n if (a == 0)\n return 0;\n int ans = 1;\n while (b > 0) {\n if ((b & 1) > 0)\n ans *= a;\n a *= a;\n b >>= 1;\n }\n return ans;\n }\n\n static long powl(long a, int b) {\n if (a == 0)\n return 0;\n long ans = 1;\n while (b > 0) {\n if ((b & 1) > 0)\n ans *= a;\n a *= a;\n b >>= 1;\n }\n return ans;\n }\n\n static int fli(double d) {\n return (int) d;\n }\n\n static int cei(double d) {\n return (int) ceil(d);\n }\n\n static long fll(double d) {\n return (long) d;\n }\n\n static long cel(double d) {\n return (long) ceil(d);\n }\n\n static int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n\n static int lcm(int a, int b) {\n return (a \/ gcd(a, b)) * b;\n }\n\n static long gcd(long a, long b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n\n static long lcm(long a, long b) {\n return (a \/ gcd(a, b)) * b;\n }\n\n static int[] exgcd(int a, int b) {\n if (b == 0)\n return new int[] { 1, 0 };\n int[] y = exgcd(b, a % b);\n return new int[] { y[1], y[0] - y[1] * (a \/ b) };\n }\n\n static long[] exgcd(long a, long b) {\n if (b == 0)\n return new long[] { 1, 0 };\n long[] y = exgcd(b, a % b);\n return new long[] { y[1], y[0] - y[1] * (a \/ b) };\n }\n\n static int randInt(int min, int max) {\n return __r.nextInt(max - min + 1) + min;\n }\n\n static long mix(long x) {\n x += 0x9e3779b97f4a7c15L;\n x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;\n x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;\n return x ^ (x >> 31);\n }\n\n public static boolean[] findPrimes(int limit) {\n assert limit >= 2;\n\n final boolean[] nonPrimes = new boolean[limit];\n nonPrimes[0] = true;\n nonPrimes[1] = true;\n\n int sqrt = (int) Math.sqrt(limit);\n for (int i = 2; i <= sqrt; i++) {\n if (nonPrimes[i])\n continue;\n for (int j = i; j < limit; j += i) {\n if (!nonPrimes[j] && i != j)\n nonPrimes[j] = true;\n }\n }\n\n return nonPrimes;\n }\n\n \/\/ array util\n static void reverse(int[] a) {\n for (int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {\n int swap = a[i];\n a[i] = a[n - i - 1];\n a[n - i - 1] = swap;\n }\n }\n\n static void reverse(long[] a) {\n for (int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {\n long swap = a[i];\n a[i] = a[n - i - 1];\n a[n - i - 1] = swap;\n }\n }\n\n static void reverse(double[] a) {\n for (int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {\n double swap = a[i];\n a[i] = a[n - i - 1];\n a[n - i - 1] = swap;\n }\n }\n\n static void reverse(char[] a) {\n for (int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {\n char swap = a[i];\n a[i] = a[n - i - 1];\n a[n - i - 1] = swap;\n }\n }\n\n static void shuffle(int[] a) {\n int n = a.length - 1;\n for (int i = 0; i < n; ++i) {\n int ind = randInt(i, n);\n int swap = a[i];\n a[i] = a[ind];\n a[ind] = swap;\n }\n }\n\n static void shuffle(long[] a) {\n int n = a.length - 1;\n for (int i = 0; i < n; ++i) {\n int ind = randInt(i, n);\n long swap = a[i];\n a[i] = a[ind];\n a[ind] = swap;\n }\n }\n\n static void shuffle(double[] a) {\n int n = a.length - 1;\n for (int i = 0; i < n; ++i) {\n int ind = randInt(i, n);\n double swap = a[i];\n a[i] = a[ind];\n a[ind] = swap;\n }\n }\n\n static void rsort(int[] a) {\n shuffle(a);\n sort(a);\n }\n\n static void rsort(long[] a) {\n shuffle(a);\n sort(a);\n }\n\n static void rsort(double[] a) {\n shuffle(a);\n sort(a);\n }\n\n static int[] copy(int[] a) {\n int[] ans = new int[a.length];\n for (int i = 0; i < a.length; ++i)\n ans[i] = a[i];\n return ans;\n }\n\n static long[] copy(long[] a) {\n long[] ans = new long[a.length];\n for (int i = 0; i < a.length; ++i)\n ans[i] = a[i];\n return ans;\n }\n\n static double[] copy(double[] a) {\n double[] ans = new double[a.length];\n for (int i = 0; i < a.length; ++i)\n ans[i] = a[i];\n return ans;\n }\n\n static char[] copy(char[] a) {\n char[] ans = new char[a.length];\n for (int i = 0; i < a.length; ++i)\n ans[i] = a[i];\n return ans;\n }\n\n static class FastReader {\n\n BufferedReader br;\n StringTokenizer st;\n\n public FastReader() {\n br = new BufferedReader(\n new InputStreamReader(System.in));\n }\n\n String next() {\n while (st == null || !st.hasMoreElements()) {\n try {\n st = new StringTokenizer(br.readLine());\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return st.nextToken();\n }\n\n int nextInt() {\n return Integer.parseInt(next());\n }\n\n int[] ria(int n) {\n int[] a = new int[n];\n for (int i = 0; i < n; i++)\n a[i] = Integer.parseInt(next());\n return a;\n }\n\n long nextLong() {\n return Long.parseLong(next());\n }\n\n long[] rla(int n) {\n long[] a = new long[n];\n for (int i = 0; i < n; i++)\n a[i] = Long.parseLong(next());\n return a;\n }\n\n double nextDouble() {\n return Double.parseDouble(next());\n }\n\n String nextLine() {\n String str = \"\";\n try {\n str = br.readLine();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return str;\n }\n }\n}\n","language":"java"} -{"contest_id":"1285","problem_id":"C","statement":"C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1\u2264X\u226410121\u2264X\u22641012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2\nOutputCopy1 2\nInputCopy6\nOutputCopy2 3\nInputCopy4\nOutputCopy1 4\nInputCopy1\nOutputCopy1 1\n","tags":["brute force","math","number theory"],"code":"import java.util.*;\n\npublic class Main{\n\n\n\n\tpublic static void main(String []args){\n\n\t\tScanner sc = new Scanner(System.in);\n\n\t\tlong x = sc.nextLong();\n\n\t\tlong ans = 1;\n\n\t\tfor(long i=1; i<=Math.sqrt(x); i++){\n\n\t\t\tif(x%i==0&&gcd(i,x\/i)==1){\n\n\t\t\t\tans = i;\n\n\t\t\t}\n\n\t\t}\n\n\t\tSystem.out.println(ans+ \" \"+ (x\/ans));\n\n\t}\n\n\n\n\tstatic long gcd(long a, long b){\n\n\t\tif(a%b==0) return b;\n\n\t\treturn gcd(b, a%b);\n\n\t}\n\n}","language":"java"} -{"contest_id":"1303","problem_id":"A","statement":"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\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1\u2264|s|\u22641001\u2264|s|\u2264100); 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\n010011\n0\n1111000\nOutputCopy2\n0\n0\nNoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).","tags":["implementation","strings"],"code":"import java.util.*;\n\npublic class OneRemove {\n\n\tpublic static void main(String [] args) {\n\n\t\tScanner sc=new Scanner(System.in);\n\n\t\tint t=sc.nextInt();\n\n\t\twhile(t-->0)\n\n\t\t{\n\n\t\t\tString s=sc.next();\n\n\t\t\tint one=0;\n\n\t\t\tint zero=0;\n\n\t\t\tint tone=0;\n\n\t\t\tint temp=0;\n\n\t\t\tfor(int i=0;i0 && s.charAt(i)-'0'==0)\n\n\t\t\t\t{\n\n\t\t\t\t\tzero++;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tSystem.out.println(zero);\n\n\t\t}\n\n\t\t\n\n\t}\n\n\n\n}\n\n","language":"java"} -{"contest_id":"1320","problem_id":"A","statement":"A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck\u22121ck>ck\u22121. So, the sequence of visited cities [c1,c2,\u2026,ck][c1,c2,\u2026,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1\u2212ci=bci+1\u2212bcici+1\u2212ci=bci+1\u2212bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1\u2264bi\u22644\u22c51051\u2264bi\u22644\u22c5105), where bibi is the beauty value of the ii-th city.OutputPrint one integer \u2014 the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6\n10 7 1 9 10 15\nOutputCopy26\nInputCopy1\n400000\nOutputCopy400000\nInputCopy7\n8 9 26 11 12 29 14\nOutputCopy55\nNoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].","tags":["data structures","dp","greedy","math","sortings"],"code":"\/\/ ceil using integer division: ceil(x\/y) = (x+y-1)\/y\n\nimport com.sun.source.tree.Tree;\n\n\n\nimport java.lang.reflect.Array;\n\nimport java.util.*;\n\nimport java.lang.*;\n\nimport java.io.*;\n\n\n\npublic class Solution {\n\n\n\n public static void main(String[] args) throws IOException {\n\n Reader.init(System.in);\n\n\n\n int t;\n\n\/\/ t = Reader.nextInt();\n\n t = 1;\n\n\n\n while (t-- > 0) {\n\n int n = Reader.nextInt();\n\n\n\n HashMap map = new HashMap<>();\n\n for(int i = 0;i 0) {\n\n p *= n;\n\n k *= r;\n\n\n\n long m = gcd(p, k);\n\n\n\n p \/= m;\n\n k \/= m;\n\n\n\n n--;\n\n r--;\n\n }\n\n\n\n } else {\n\n p = 1;\n\n }\n\n return p;\n\n }\n\n public static boolean isPrime(long n){\n\n if (n <= 1) return false;\n\n if (n <= 3) return true;\n\n\n\n if (n % 2 == 0 || n % 3 == 0) return false;\n\n\n\n for (int i = 5; (long) i * i <= n; i = i + 6){\n\n if (n % i == 0 || n % (i + 2) == 0) {\n\n return false;\n\n }\n\n }\n\n return true;\n\n }\n\n public static int powOf2JustSmallerThanN(int n) {\n\n n |= n >> 1;\n\n n |= n >> 2;\n\n n |= n >> 4;\n\n n |= n >> 8;\n\n n |= n >> 16;\n\n\n\n return n ^ (n >> 1);\n\n }\n\n\n\n public static int mergeSortAndCount(int[] arr, int l, int r) {\n\n int count = 0;\n\n if (l < r) {\n\n int m = (l + r) \/ 2;\n\n count += mergeSortAndCount(arr, l, m);\n\n count += mergeSortAndCount(arr, m + 1, r);\n\n count += mergeAndCount(arr, l, m, r);\n\n }\n\n return count;\n\n }\n\n\n\n public static int mergeAndCount(int[] arr, int l, int m, int r) {\n\n int[] left = Arrays.copyOfRange(arr, l, m + 1);\n\n int[] right = Arrays.copyOfRange(arr, m + 1, r + 1);\n\n\n\n int i = 0, j = 0, k = l, swaps = 0;\n\n\n\n while (i < left.length && j < right.length) {\n\n if (left[i] <= right[j])\n\n arr[k++] = left[i++];\n\n else {\n\n arr[k++] = right[j++];\n\n swaps += (m + 1) - (l + i);\n\n }\n\n }\n\n while (i < left.length)\n\n arr[k++] = left[i++];\n\n while (j < right.length)\n\n arr[k++] = right[j++];\n\n return swaps;\n\n }\n\n\n\n public static void reverseArray(int[] arr,int start, int end) {\n\n int temp;\n\n\n\n while (start < end) {\n\n temp = arr[start];\n\n arr[start] = arr[end];\n\n arr[end] = temp;\n\n start++;\n\n end--;\n\n }\n\n }\n\n\n\n public static long gcd(long a, long b){\n\n if(a==0){\n\n return b;\n\n }\n\n\n\n return gcd(b%a,a);\n\n }\n\n\n\n public static long lcm(long a, long b){\n\n if(a>b) return a\/gcd(b,a) * b;\n\n return b\/gcd(a,b) * a;\n\n }\n\n\n\n public static long largeExponentMod(long x,long y,long mod){\n\n \/\/ computing (x^y) % mod\n\n x%=mod;\n\n long ans = 1;\n\n while(y>0){\n\n if((y&1)==1){\n\n ans = (ans*x)%mod;\n\n }\n\n x = (x*x)%mod;\n\n y = y >> 1;\n\n }\n\n return ans;\n\n }\n\n\n\n public static boolean[] numOfPrimesInRange(long L, long R){\n\n boolean[] isPrime = new boolean[(int) (R-L+1)];\n\n Arrays.fill(isPrime,true);\n\n long lim = (long) Math.sqrt(R);\n\n for (long i = 2; i <= lim; i++){\n\n for (long j = Math.max(i * i, (L + i - 1) \/ i * i); j <= R; j += i){\n\n isPrime[(int) (j - L)] = false;\n\n }\n\n }\n\n if (L == 1) isPrime[0] = false;\n\n return isPrime;\n\n }\n\n\n\n public static ArrayList primeFactors(long n){\n\n ArrayList factorization = new ArrayList<>();\n\n if(n%2==0){\n\n factorization.add(2L);\n\n }\n\n while(n%2==0){\n\n n\/=2;\n\n }\n\n if(n%3==0){\n\n factorization.add(3L);\n\n }\n\n while(n%3==0){\n\n n\/=3;\n\n }\n\n if(n%5==0){\n\n factorization.add(5L);\n\n }\n\n while(n%5==0){\n\n\/\/ factorization.add(5L);\n\n n\/=5;\n\n }\n\n\n\n int[] increments = {4, 2, 4, 2, 4, 6, 2, 6};\n\n int i = 0;\n\n for (long d = 7; d * d <= n; d += increments[i++]) {\n\n if(n%d==0){\n\n factorization.add(d);\n\n }\n\n while (n % d == 0) {\n\n\/\/ factorization.add(d);\n\n n \/= d;\n\n }\n\n if (i == 8)\n\n i = 0;\n\n }\n\n if (n > 1)\n\n factorization.add(n);\n\n return factorization;\n\n }\n\n}\n\n\n\nclass DSU {\n\n int[] size, parent;\n\n int n;\n\n\n\n public DSU(int n){\n\n this.n = n;\n\n size = new int[n];\n\n parent = new int[n];\n\n\n\n for(int i = 0;isize[v]){\n\n parent[v] = u;\n\n size[u] += size[v];\n\n }\n\n else{\n\n parent[u] = v;\n\n size[v] += size[u];\n\n }\n\n }\n\n }\n\n}\n\nclass Reader {\n\n static BufferedReader reader;\n\n static StringTokenizer tokenizer;\n\n\n\n \/** call this method to initialize reader for InputStream *\/\n\n static void init(InputStream input) {\n\n reader = new BufferedReader(\n\n new InputStreamReader(input) );\n\n tokenizer = new StringTokenizer(\"\");\n\n }\n\n\n\n \/** get next word *\/\n\n static String next() throws IOException {\n\n while ( ! tokenizer.hasMoreTokens() ) {\n\n \/\/TODO add check for eof if necessary\n\n tokenizer = new StringTokenizer(\n\n reader.readLine() );\n\n }\n\n return tokenizer.nextToken();\n\n }\n\n static String nextLine() throws IOException {\n\n return reader.readLine();\n\n }\n\n\n\n static int nextInt() throws IOException {\n\n return Integer.parseInt( next() );\n\n }\n\n static long nextLong() throws IOException{\n\n return Long.parseLong(next() );\n\n }\n\n\n\n static double nextDouble() throws IOException {\n\n return Double.parseDouble( next() );\n\n }\n\n}","language":"java"} -{"contest_id":"1324","problem_id":"E","statement":"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\u22121ai\u22121 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\u2264n\u22642000,3\u2264h\u22642000,0\u2264l\u2264r 0) {\n\n int n = in.nextInt();\n\n int h = in.nextInt();\n\n int l = in.nextInt();\n\n int r = in.nextInt();\n\n int[] a = in.nextArray(n);\n\n\n\n \/\/ f[i][j]\u4ee3\u8868\u5df2\u7ecf\u7761\u4e86i\u6b21\u4e14\u6070\u597d\u65e9\u7761j\u6b21\u65f6\u597d\u7761\u7720\u7684\u6b21\u6570\n\n int[][] f = new int[n + 1][n + 1];\n\n for (int i = 0; i <= n; i++) {\n\n Arrays.fill(f[i], Integer.MIN_VALUE);\n\n }\n\n f[0][0] = 0;\n\n for (int i = 0, sum = 0; i < n; i++) {\n\n sum += a[i];\n\n for (int j = 0; j <= n; j++) {\n\n f[i + 1][j] = max(f[i + 1][j], f[i][j] + check((sum - j) % h, l, r));\n\n if (j < n) {\n\n f[i + 1][j + 1] = max(f[i + 1][j + 1], f[i][j] + check((sum - (j + 1)) % h, l, r));\n\n }\n\n }\n\n }\n\n int maxv = 0;\n\n for (int i = 0; i <= n; i++) {\n\n maxv = max(maxv, f[n][i]);\n\n }\n\n pw.println(maxv);\n\n }\n\n pw.close();\n\n }\n\n\n\n private int check(int x, int l, int r) {\n\n if (x >= l && x <= r) {\n\n return 1;\n\n }\n\n return 0;\n\n }\n\n\n\n private int gcd(int a, int b) {\n\n return b == 0 ? a : gcd(b, a % b);\n\n }\n\n\n\n private int lcm(int a, int b) {\n\n return a \/ gcd(a, b) * b;\n\n }\n\n}\n\n\n\nclass InputReader {\n\n private final BufferedReader reader;\n\n private StringTokenizer tokenizer;\n\n\n\n public InputReader(InputStream stream) {\n\n reader = new BufferedReader(new InputStreamReader(stream), 32768);\n\n tokenizer = null;\n\n }\n\n\n\n public String next() {\n\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n\n try {\n\n tokenizer = new StringTokenizer(reader.readLine());\n\n } catch (IOException e) {\n\n throw new RuntimeException(e);\n\n }\n\n }\n\n return tokenizer.nextToken();\n\n }\n\n\n\n public String nextLine() {\n\n String str;\n\n try {\n\n str = reader.readLine();\n\n } catch (IOException e) {\n\n throw new RuntimeException(e);\n\n }\n\n return str;\n\n }\n\n\n\n public boolean hasNext() {\n\n while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n\n String nextLine = null;\n\n try {\n\n nextLine = reader.readLine();\n\n } catch (IOException e) {\n\n throw new RuntimeException(e);\n\n }\n\n if (nextLine == null)\n\n return false;\n\n tokenizer = new StringTokenizer(nextLine);\n\n }\n\n return true;\n\n }\n\n\n\n public int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n public long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n\n\n public int[] nextArray(int n) {\n\n int[] a = new int[n];\n\n for (int i = 0; i < n; ++i) {\n\n a[i] = nextInt();\n\n }\n\n return a;\n\n }\n\n}","language":"java"} -{"contest_id":"1305","problem_id":"A","statement":"A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1\u2264t\u22641001\u2264t\u2264100) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100) \u00a0\u2014 the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226410001\u2264ai\u22641000) \u00a0\u2014 the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u226410001\u2264bi\u22641000) \u00a0\u2014 the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,\u2026,xnx1,x2,\u2026,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,\u2026,yny1,y2,\u2026,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,\u2026,xn+ynx1+y1,x2+y2,\u2026,xn+yn should all be distinct. The numbers x1,\u2026,xnx1,\u2026,xn should be equal to the numbers a1,\u2026,ana1,\u2026,an in some order, and the numbers y1,\u2026,yny1,\u2026,yn should be equal to the numbers b1,\u2026,bnb1,\u2026,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2\n3\n1 8 5\n8 4 5\n3\n1 7 5\n6 1 2\nOutputCopy1 8 5\n8 4 5\n5 1 7\n6 2 1\nNoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.","tags":["brute force","constructive algorithms","greedy","sortings"],"code":"import java.util.*;\n\npublic class Main{\n\n\tpublic static void main(String args[]){\n\n\t\tScanner sc = new Scanner(System.in);\n\n\t\tint t = sc.nextInt();\n\n\t\twhile(t-- > 0){\n\n\t\t\tint n = sc.nextInt();\n\n\t\t\tint[] a = new int[n];\n\n\t\t\tint[] b = new int[n];\n\n\t\t\tfor(int i=0; i= '0' && c <= '9');\n\n\n\n if (neg)\n\n return -ret;\n\n return ret;\n\n }\n\n\n\n public long nextLong() throws IOException {\n\n long ret = 0;\n\n byte c = read();\n\n while (c <= ' ')\n\n c = read();\n\n boolean neg = (c == '-');\n\n if (neg)\n\n c = read();\n\n do {\n\n ret = ret * 10 + c - '0';\n\n } while ((c = read()) >= '0' && c <= '9');\n\n if (neg)\n\n return -ret;\n\n return ret;\n\n }\n\n\n\n public double nextDouble() throws IOException {\n\n double ret = 0, div = 1;\n\n byte c = read();\n\n while (c <= ' ')\n\n c = read();\n\n boolean neg = (c == '-');\n\n if (neg)\n\n c = read();\n\n\n\n do {\n\n ret = ret * 10 + c - '0';\n\n } while ((c = read()) >= '0' && c <= '9');\n\n\n\n if (c == '.') {\n\n while ((c = read()) >= '0' && c <= '9') {\n\n ret += (c - '0') \/ (div *= 10);\n\n }\n\n }\n\n\n\n if (neg)\n\n return -ret;\n\n return ret;\n\n }\n\n\n\n private void fillBuffer() throws IOException {\n\n bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);\n\n if (bytesRead == -1)\n\n buffer[0] = -1;\n\n }\n\n\n\n private byte read() throws IOException {\n\n if (bufferPointer == bytesRead)\n\n fillBuffer();\n\n return buffer[bufferPointer++];\n\n }\n\n\n\n public void close() throws IOException {\n\n if (din == null)\n\n return;\n\n din.close();\n\n }\n\n }\n\n\n\n static class Sb_Output implements Closeable, Flushable{\n\n StringBuilder sb;\n\n OutputStream os;\n\n int BUFFER_SIZE;\n\n public Sb_Output(String s) throws Exception {\n\n os = new BufferedOutputStream(new FileOutputStream(new File(s)));\n\n BUFFER_SIZE = 1 << 16;\n\n sb = new StringBuilder(BUFFER_SIZE);\n\n }\n\n public void print(String s) {\n\n sb.append(s);\n\n if(sb.length() >= (BUFFER_SIZE>>1)) {\n\n flush();\n\n }\n\n }\n\n public void println(String s) {\n\n print(s);\n\n print(\"\\n\");\n\n }\n\n public void println(int i) {\n\n println(\"\" + i);\n\n }\n\n public void println(long i) {\n\n println(\"\" + i);\n\n }\n\n public void flush() {\n\n try {\n\n os.write(sb.toString().getBytes());\n\n sb = new StringBuilder(BUFFER_SIZE);\n\n }catch(IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n public void close() {\n\n flush();\n\n try {\n\n os.close();\n\n }catch(IOException e) {\n\n e.printStackTrace();\n\n }\n\n }\n\n }\n\n\n\n static ArrayList[] adj;\n\n static int root, c[];\n\n static int[] tin, tout;\n\n static int timer = 0;\n\n static boolean poss = true;\n\n\n\n static ArrayList dfs(int v, int p){\n\n int start = timer++;\n\n ArrayList ret = new ArrayList();\n\n if(c[v] == 0) ret.add(v);\n\n for(int i : adj[v]) {\n\n if(i == p) continue;\n\n ArrayList cur = dfs(i, v);\n\n for(int j : cur) {\n\n ret.add(j);\n\n if(ret.size() == c[v]) {\n\n ret.add(v);\n\n }\n\n }\n\n }\n\n poss &= timer - 1 - start >= c[v];\n\n return ret;\n\n }\n\n\n\n public static void main(String[] args) throws Exception {\n\n Reader in = new Reader();\n\n\/\/\t\tReader in = new Reader(\"poetry.in\");\n\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n\/\/ BufferedReader br = new BufferedReader(new FileReader(\"poetry.in\"));\n\n int n = in.nextInt();\n\n adj = new ArrayList[n];\n\n for(int i = 0; i < n; ++i) {\n\n adj[i] = new ArrayList();\n\n }\n\n c = new int[n];\n\n for(int i = 0; i < n; ++i){\n\n int p = in.nextInt();\n\n c[i] = in.nextInt();\n\n if(p == 0) root = i;\n\n else {\n\n --p;\n\n adj[p].add(i);\n\n adj[i].add(p);\n\n }\n\n }\n\n ArrayList ans = dfs(root, -1);\n\n if(!poss) {\n\n System.out.println(\"NO\");\n\n } else{\n\n System.out.println(\"YES\");\n\n int[] res = new int[n];\n\n for(int i = 0; i < ans.size(); ++i){\n\n res[ans.get(i)] = i + 1;\n\n }\n\n for(int i = 0; i < n; ++i){\n\n System.out.print(res[i] + \" \");\n\n }\n\n System.out.println();\n\n }\n\n in.close();\n\n\n\n }\n\n static class pair{\n\n int x, y;\n\n pair(int a, int b){\n\n x = a; y = b;\n\n }\n\n }\n\n}","language":"java"} -{"contest_id":"1293","problem_id":"B","statement":"B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show \"1 vs. nn\"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0\u2264t\u2264s0\u2264t\u2264s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s\u2212ts\u2212t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10\u2212410\u22124. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a\u2212b|max(1,b)\u226410\u22124|a\u2212b|max(1,b)\u226410\u22124.ExamplesInputCopy1\nOutputCopy1.000000000000\nInputCopy2\nOutputCopy1.500000000000\nNoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.","tags":["combinatorics","greedy","math"],"code":"import java.util.Scanner;\n\n\n\npublic class Second {\n\n public static void main(String[] args) {\n\n Scanner sc = new Scanner(System.in);\n\n double n = sc.nextInt();\n\n double ans = 0;\n\n for(int i = 1; i <= n; i++) {\n\n ans += (1.0 \/ i);\n\n }\n\n System.out.println(ans);\n\n }\n\n}\n\n","language":"java"} -{"contest_id":"1286","problem_id":"A","statement":"A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the number of light bulbs on the garland.The second line contains nn integers p1,\u00a0p2,\u00a0\u2026,\u00a0pnp1,\u00a0p2,\u00a0\u2026,\u00a0pn (0\u2264pi\u2264n0\u2264pi\u2264n)\u00a0\u2014 the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number\u00a0\u2014 the minimum complexity of the garland.ExamplesInputCopy5\n0 5 0 2 3\nOutputCopy2\nInputCopy7\n1 0 0 5 0 0 2\nOutputCopy1\nNoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. ","tags":["dp","greedy","sortings"],"code":"import java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.util.Arrays;\nimport java.io.BufferedWriter;\nimport java.io.Writer;\nimport java.io.OutputStreamWriter;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n\/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n *\/\npublic class Main {\n public static void main(String[] args) {\n InputStream inputStream = System.in;\n OutputStream outputStream = System.out;\n InputReader in = new InputReader(inputStream);\n OutputWriter out = new OutputWriter(outputStream);\n AGarland solver = new AGarland();\n solver.solve(1, in, out);\n out.close();\n }\n\n static class AGarland {\n public void solve(int testNumber, InputReader in, OutputWriter out) {\n int n = in.nextInt();\n int[] a = new int[n];\n int[] cnt = new int[2];\n cnt[0] = n \/ 2;\n cnt[1] = n - cnt[0];\n for (int i = 0; i < n; i++) {\n a[i] = in.nextInt();\n\n }\n int[][][][] dp = new int[n + 1][n + 1][n + 1][2];\n int inf = (int) 1e9;\n for (int i = 0; i < n + 1; i++) {\n for (int j = 0; j < n + 1; j++) {\n for (int k = 0; k < n + 1; k++) {\n Arrays.fill(dp[i][j][k], inf);\n }\n }\n }\n dp[0][0][0][0] = dp[0][0][0][1] = 0;\n\n for (int i = 1; i <= n; i++) {\n if (a[i - 1] == 0 || a[i - 1] % 2 == 1) {\n for (int j = 0; j < i; j++) {\n int k = i - j;\n dp[i][j][k][1] = Math.min(dp[i - 1][j][k - 1][1], dp[i - 1][j][k - 1][0] + 1);\n }\n }\n\n if (a[i - 1] == 0 || a[i - 1] % 2 == 0) {\n for (int j = 1; j <= i; j++) {\n int k = i - j;\n dp[i][j][k][0] = Math.min(dp[i - 1][j - 1][k][0], dp[i - 1][j - 1][k][1] + 1);\n }\n }\n\n }\n out.println(Math.min(dp[n][cnt[0]][cnt[1]][0], dp[n][cnt[0]][cnt[1]][1]));\n }\n\n }\n\n static class InputReader {\n private InputStream stream;\n private byte[] buf = new byte[1024];\n private int curChar;\n private int numChars;\n private InputReader.SpaceCharFilter filter;\n\n public InputReader(InputStream stream) {\n this.stream = stream;\n }\n\n public int read() {\n if (numChars == -1) {\n throw new UnknownError();\n }\n if (curChar >= numChars) {\n curChar = 0;\n try {\n numChars = stream.read(buf);\n } catch (IOException e) {\n throw new UnknownError();\n }\n if (numChars <= 0) {\n return -1;\n }\n }\n return buf[curChar++];\n }\n\n public int nextInt() {\n int c = read();\n while (isSpaceChar(c)) {\n c = read();\n }\n int sgn = 1;\n if (c == '-') {\n sgn = -1;\n c = read();\n }\n int res = 0;\n do {\n if (c < '0' || c > '9') {\n throw new UnknownError();\n }\n res *= 10;\n res += c - '0';\n c = read();\n } while (!isSpaceChar(c));\n return res * sgn;\n }\n\n public boolean isSpaceChar(int c) {\n if (filter != null) {\n return filter.isSpaceChar(c);\n }\n return isWhitespace(c);\n }\n\n public static boolean isWhitespace(int c) {\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n }\n\n public interface SpaceCharFilter {\n public boolean isSpaceChar(int ch);\n\n }\n\n }\n\n static class OutputWriter {\n private final PrintWriter writer;\n\n public OutputWriter(OutputStream outputStream) {\n writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n }\n\n public OutputWriter(Writer writer) {\n this.writer = new PrintWriter(writer);\n }\n\n public void close() {\n writer.close();\n }\n\n public void println(int i) {\n writer.println(i);\n }\n\n }\n}\n\n","language":"java"} -{"contest_id":"1288","problem_id":"E","statement":"E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,\u2026,n1,2,\u2026,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1\u2264n,m\u22643\u22c51051\u2264n,m\u22643\u22c5105) \u2014 the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,\u2026,ama1,a2,\u2026,am (1\u2264ai\u2264n1\u2264ai\u2264n) \u2014 the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4\n3 5 1 4\nOutputCopy1 3\n2 5\n1 4\n1 5\n1 5\nInputCopy4 3\n1 2 4\nOutputCopy1 3\n1 2\n3 4\n1 4\nNoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3] ","tags":["data structures"],"code":"import java.io.*;\n\nimport java.util.*;\n\n\n\nimport static java.lang.Math.*;\n\nimport static java.util.Arrays.*;\n\n\n\npublic class cf1288e {\n\n\n\n public static void main(String[] args) throws IOException {\n\n int n = rni(), m = ni(), block = 550, a[] = riam1(m);\n\n List> q = g(n);\n\n for (int i = 0; i < m; ++i) {\n\n q.get(a[i]).add(i);\n\n }\n\n PriorityQueue pq = new PriorityQueue<>((x, y) -> x[0] \/ block == y[0] \/ block ? x[1] - y[1] : x[0] \/ block - y[0] \/ block);\n\n for (int i = 0; i < n; ++i) {\n\n for (int j = 1, end = q.get(i).size(); j < end; ++j) {\n\n pq.add(new int[] {q.get(i).get(j - 1) + 1, q.get(i).get(j) - 1});\n\n }\n\n if (q.get(i).size() > 0) {\n\n pq.add(new int[] {q.get(i).get(q.get(i).size() - 1) + 1, m - 1});\n\n }\n\n }\n\n int ans[] = new int[n], cnt[] = new int[n], distinct = 0, l = 0, r = -1;\n\n for (int i = 0; i < n; ++i) {\n\n ans[i] = i;\n\n }\n\n while (!pq.isEmpty()) {\n\n int qry[] = pq.poll(), i = qry[0], j = qry[1];\n\n while (l < i) {\n\n if (--cnt[a[l++]] == 0) {\n\n --distinct;\n\n }\n\n }\n\n while (l > i) {\n\n if (++cnt[a[--l]] == 1) {\n\n ++distinct;\n\n }\n\n }\n\n while (r < j) {\n\n if (++cnt[a[++r]] == 1) {\n\n ++distinct;\n\n }\n\n }\n\n while (r > j) {\n\n if (--cnt[a[r--]] == 0) {\n\n --distinct;\n\n }\n\n }\n\n ans[a[i - 1]] = max(ans[a[i - 1]], distinct);\n\n }\n\n bit bit = new bit(n, Integer::sum);\n\n for (int i = 0; i < m; ++i) {\n\n if (i == q.get(a[i]).get(0)) {\n\n \/\/ prln(0, n - a[i], bit.qry(n - a[i]));\n\n ans[a[i]] = max(ans[a[i]], a[i] + bit.qry(n - a[i]));\n\n \/\/ prln(1, n - a[i] - 1);\n\n bit.upd(n - a[i] - 1, 1);\n\n }\n\n }\n\n for (int i = 0; i < n; ++i) {\n\n if (q.get(i).size() == 0) {\n\n ans[i] = i + bit.qry(n - i);\n\n }\n\n }\n\n for (int i = 0; i < n; ++i) {\n\n prln(q.get(i).size() > 0 ? 1 : i + 1, ans[i] + 1);\n\n }\n\n close();\n\n }\n\n\n\n @FunctionalInterface\n\n interface IntOperator {\n\n int merge(int a, int b);\n\n }\n\n\n\n static class bit {\n\n IntOperator op;\n\n int n, bit[];\n\n\n\n bit(int size, IntOperator operator) {\n\n bit = new int[n = size + 1];\n\n op = operator;\n\n }\n\n\n\n bit(int[] arr, IntOperator operator) {\n\n bit = new int[(n = arr.length + 1)];\n\n op = operator;\n\n for (int i = 0; i < n - 1; ++i) upd(i, arr[i]);\n\n ++n;\n\n }\n\n\n\n void upd(int i, int x) {\n\n ++i;\n\n while (i < n) {\n\n bit[i] = op.merge(bit[i], x);\n\n i += i & (-i);\n\n }\n\n }\n\n\n\n int qry(int i) {\n\n int ans = 0;\n\n while (i > 0) {\n\n ans = op.merge(ans, bit[i]);\n\n i -= i & (-i);\n\n }\n\n return ans;\n\n }\n\n }\n\n\n\n static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));\n\n static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));\n\n static StringTokenizer input;\n\n static Random __rand = new Random();\n\n\n\n \/\/ references\n\n \/\/ IBIG = 1e9 + 7\n\n \/\/ IMAX ~= 2e9\n\n \/\/ LMAX ~= 9e18\n\n \n\n \/\/ constants\n\n static final int IBIG = 1000000007;\n\n static final int IMAX = 2147483647;\n\n static final int IMIN = -2147483648;\n\n static final long LMAX = 9223372036854775807L;\n\n static final long LMIN = -9223372036854775808L;\n\n \/\/ math util\n\n static int minof(int a, int b, int c) {return min(a, min(b, c));}\n\n 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;}\n\n static long minof(long a, long b, long c) {return min(a, min(b, c));}\n\n 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;}\n\n static int maxof(int a, int b, int c) {return max(a, max(b, c));}\n\n 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;}\n\n static long maxof(long a, long b, long c) {return max(a, max(b, c));}\n\n 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;}\n\n 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;}\n\n 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;}\n\n static int fli(double d) {return (int)d;}\n\n static int cei(double d) {return (int)ceil(d);}\n\n static long fll(double d) {return (long)d;}\n\n static long cel(double d) {return (long)ceil(d);}\n\n static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}\n\n static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}\n\n static int lcm(int a, int b) {return a * b \/ gcf(a, b);}\n\n static long lcm(long a, long b) {return a * b \/ gcf(a, b);}\n\n static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}\n\n static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}\n\n \/\/ array util\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n 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;}}\n\n static void rsort(int[] a) {shuffle(a); sort(a);}\n\n static void rsort(long[] a) {shuffle(a); sort(a);}\n\n static void rsort(double[] a) {shuffle(a); sort(a);}\n\n 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;}\n\n 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;}\n\n 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;}\n\n 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;}\n\n \/\/ graph util\n\n static List> g(int n) {List> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}\n\n static List> sg(int n) {List> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}\n\n static void c(List> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}\n\n static void cto(List> g, int u, int v) {g.get(u).add(v);}\n\n static void dc(List> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}\n\n static void dcto(List> g, int u, int v) {g.get(u).remove(v);}\n\n \/\/ input\n\n static void r() throws IOException {input = new StringTokenizer(rline());}\n\n static int ri() throws IOException {return Integer.parseInt(rline());}\n\n static long rl() throws IOException {return Long.parseLong(rline());}\n\n 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;}\n\n 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;}\n\n 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;}\n\n static char[] rcha() throws IOException {return rline().toCharArray();}\n\n static String rline() throws IOException {return __in.readLine();}\n\n static String n() {return input.nextToken();}\n\n static int rni() throws IOException {r(); return ni();}\n\n static int ni() {return Integer.parseInt(n());}\n\n static long rnl() throws IOException {r(); return nl();}\n\n static long nl() {return Long.parseLong(n());}\n\n static double rnd() throws IOException {r(); return nd();}\n\n static double nd() {return Double.parseDouble(n());}\n\n static List> rg(int n, int m) throws IOException {List> g = g(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}\n\n static void rg(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}\n\n static List> rdg(int n, int m) throws IOException {List> g = g(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}\n\n static void rdg(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}\n\n static List> rsg(int n, int m) throws IOException {List> g = sg(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}\n\n static void rsg(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}\n\n static List> rdsg(int n, int m) throws IOException {List> g = sg(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}\n\n static void rdsg(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}\n\n \/\/ output\n\n static void pr(int i) {__out.print(i);}\n\n static void prln(int i) {__out.println(i);}\n\n static void pr(long l) {__out.print(l);}\n\n static void prln(long l) {__out.println(l);}\n\n static void pr(double d) {__out.print(d);}\n\n static void prln(double d) {__out.println(d);}\n\n static void pr(char c) {__out.print(c);}\n\n static void prln(char c) {__out.println(c);}\n\n static void pr(char[] s) {__out.print(new String(s));}\n\n static void prln(char[] s) {__out.println(new String(s));}\n\n static void pr(String s) {__out.print(s);}\n\n static void prln(String s) {__out.println(s);}\n\n static void pr(Object o) {__out.print(o);}\n\n static void prln(Object o) {__out.println(o);}\n\n static void prln() {__out.println();}\n\n static void pryes() {__out.println(\"yes\");}\n\n static void pry() {__out.println(\"Yes\");}\n\n static void prY() {__out.println(\"YES\");}\n\n static void prno() {__out.println(\"no\");}\n\n static void prn() {__out.println(\"No\");}\n\n static void prN() {__out.println(\"NO\");}\n\n static void pryesno(boolean b) {__out.println(b ? \"yes\" : \"no\");};\n\n static void pryn(boolean b) {__out.println(b ? \"Yes\" : \"No\");}\n\n static void prYN(boolean b) {__out.println(b ? \"YES\" : \"NO\");}\n\n 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]);}\n\n 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]);}\n\n static void prln(double... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}\n\n static void prln(Collection c) {int n = c.size() - 1; Iterator 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();}\n\n static void h() {__out.println(\"hlfd\"); flush();}\n\n static void flush() {__out.flush();}\n\n static void close() {__out.close();}\n\n}","language":"java"} -{"contest_id":"1141","problem_id":"C","statement":"C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,\u2026,pnp1,p2,\u2026,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,\u2026,pnp1,p2,\u2026,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,\u2026,qn\u22121q1,q2,\u2026,qn\u22121 of length n\u22121n\u22121, where qi=pi+1\u2212piqi=pi+1\u2212pi.Given nn and q=q1,q2,\u2026,qn\u22121q=q1,q2,\u2026,qn\u22121, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the length of the permutation to restore. The second line contains n\u22121n\u22121 integers q1,q2,\u2026,qn\u22121q1,q2,\u2026,qn\u22121 (\u2212nset = new LinkedHashSet<>();\n\n\t\t\tif(ans%n == 0 && ans>0){\n\n\t\t\t\tans\/=n;\n\n\t\t\t\tset.add(ans);\n\n\t\t\t\tfor(int i = 0;in)ok = false;\n\n\t\t\t\t\tset.add(ans);\n\n\t\t\t\t}\n\n\t\t\t}else ok = false;\n\n\t\t\t\n\n\t\t\tif(ok){\n\n\t\t\t\tfor(long it:set)System.out.print(it+\" \");\n\n\t\t\t}else System.out.println(-1);\n\n\t\t\t\t\n\n\t\t\t\t\n\n\t\t\t\t\n\n\t\t\t\t\n\n\t\t\t\n\n\n\n\t\t\t\n\n\t\t}\n\n\t\tpublic static long gcd(long a, long b){\n\n\t\t\treturn b ==0 ?a:gcd(b,a%b);\n\n\t\t}\n\n\t\t\n\n\t\tpublic static long nearest(TreeSet list,long target){\n\n\t\t\tlong nearest = -1,sofar = Integer.MAX_VALUE;\n\n\t\t\tfor(long it:list){\n\n\t\t\t\tif(Math.abs(it - target) factors(long n){\n\n\t\t\tArrayListl = new ArrayList<>();\n\n\t\t\tfor(long i = 1;i*i<=n;i++){\n\n\t\t\t\tif(n%i == 0){\n\n\t\t\t\t\tl.add(i);\n\n\t\t\t\t\tif(n\/i != i)l.add(n\/i);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tCollections.sort(l);\n\n\t\t\treturn l;\n\n\t\t}\n\n\t\t\n\n\t\tpublic static void swap(int a[],int i, int j){\n\n\t\t\tint t = a[i];\n\n\t\t\ta[i] = a[j];\n\n\t\t\ta[j] = t;\n\n\t\t}\n\n\t\t\n\n\t\tpublic static boolean isSorted(long a[]){\n\n\t\t\tfor(int i =0;ia[i+1])return false;\n\n\t\t\t}\n\n\t\t\treturn true;\n\n\t\t}\n\n\t\t\n\n\t\tpublic static int first(ArrayListlist,long target){\n\n\t\t\tint index = -1;\n\n\t\t\tint l = 0,r = list.size()-1;\n\n\t\t\twhile(l<=r){\n\n\t\t\t\tint mid = (l+r)\/2;\n\n\t\t\t\tif(list.get(mid) == target){\n\n\t\t\t\t\tindex = mid;\n\n\t\t\t\t\tr = mid-1;\n\n\t\t\t\t}else if(list.get(mid)>target){\n\n\t\t\t\t\tr = mid-1;\n\n\t\t\t\t}else l = mid+1;\n\n\t\t\t}\n\n\t\t\treturn index;\n\n\t\t}\n\n\t\t\n\n\t\tpublic static int last(ArrayListlist,long target){\n\n\t\t\tint index = -1;\n\n\t\t\tint l = 0,r = list.size()-1;\n\n\t\t\twhile(l<=r){\n\n\t\t\t\tint mid = (l+r)\/2;\n\n\t\t\t\tif(list.get(mid) == target){\n\n\t\t\t\t\tindex= mid;\n\n\t\t\t\t\tl = mid+1;\n\n\t\t\t\t}else if(list.get(mid)list = new ArrayList<>();\n\n\t\t\tfor(int it:arr)list.add(it);\n\n\t\t\tCollections.sort(list);\n\n\t\t\tfor(int i = 0;i