diff --git "a/data/java/validation.jsonl" "b/data/java/validation.jsonl" new file mode 100644--- /dev/null +++ "b/data/java/validation.jsonl" @@ -0,0 +1,195 @@ +{"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":"import java.util.*;\n\n\n\npublic class Main\n\n{\n\n public static void main(String[] args) \n\n {\n\n Scanner sc = new Scanner(System.in);\n\n int n = sc.nextInt();\n\n while(n-- > 0)\n\n {\n\n int no_of_stud = sc.nextInt();\n\n int highest_mar_poss = sc.nextInt();\n\n int[] arr = new int[no_of_stud];\n\n int sum = 0;\n\n for(int i = 0; i < no_of_stud; i++)\n\n {\n\n arr[i] = sc.nextInt();\n\n sum += arr[i];\n\n }\n\n if(sum >= highest_mar_poss)\n\n {\n\n System.out.println(highest_mar_poss);\n\n }\n\n else\n\n {\n\n System.out.println(sum);\n\n }\n\n \/\/System.out.println(arr[no_of_stud - 1]);\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\tprivate static Scanner in = new Scanner(System.in);\n\n\tpublic static void solve(){\n\n\t\tint n=in.nextInt();\n\n\t\tin.nextLine();\n\n\t\tString s=in.nextLine();\n\n\t\tint numOdd=0;\n\n\t\tfor(int i=0;i0){t--;solve();}\n\n\t}\n\n}","language":"java"} +{"contest_id":"1315","problem_id":"B","statement":"B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,\u2026,j\u22121i,i+1,\u2026,j\u22121 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i\u2264t= '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 <= ' ') c = read();\n\n boolean neg = (c == '-');\n\n if (neg) c = read();\n\n \n\n do {\n\n ret = ret * 10 + c - '0';\n\n } while ((c = read()) >= '0' && c <= '9');\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 if (neg) 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,\n\n BUFFER_SIZE);\n\n if (bytesRead == -1)\n\n buffer[0] = -1;\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 static class Kattio extends PrintWriter {\n\n private BufferedReader r;\n\n private StringTokenizer st;\n\n \n\n \/\/ standard input\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 \/\/ USACO-style file input\n\n public Kattio(String problemName) throws IOException {\n\n super(new FileWriter(problemName + \".out\"));\n\n r = new BufferedReader(new FileReader(problemName + \".in\"));\n\n }\n\n \n\n \/\/ returns null if no more input\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 \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 } \n\n \n\n static Kattio sc = new Kattio();\n\n static long mod = (long)1e9+7;\n\n static PrintWriter out =new PrintWriter(System.out);\n\n \n\n \/\/Heapify function to maintain heap property.\n\n public static void swap(int i,int j,int arr[]) {\n\n int temp = arr[i];\n\n arr[i] = arr[j];\n\n arr[j] = temp;\n\n }\n\n static String endl = \"\\n\" , gap = \" \";\n\n public static int ans;\n\n public static void main(String[] args)throws IOException {\n\n int t = ri();\n\n while(t-->0) {\n\n solve();\n\n }\n\n out.close();\n\n }\n\n public static void solve()throws IOException { \n\n int a = ri() , b = ri() , p = ri();\n\n char s[] = rac();\n\n int n = s.length;\n\n int prev = s[n-2];\n\n int sum = 0;\n\n if(s[n-2] == 'A') {\n\n if(p < a) {\n\n System.out.println(n); \n\n return;\n\n }\n\n }\n\n if(s[n-2] == 'B') {\n\n if(p < b) {\n\n System.out.println(n);\n\n return; \n\n } \n\n }\n\n for(int i =n-3;i>=0;i--) {\n\n if(prev == s[i]) {\n\n continue;\n\n } \n\n else {\n\n sum += (prev == 'A'?a : b);\n\n \/\/ System.out.println(\"sum iis \" + sum);\n\n prev = s[i];\n\n if(prev == 'A') {\n\n if(sum + a >p ) {\n\n System.out.println(i + 2);\n\n return;\n\n }\n\n }\n\n if(prev == 'B') {\n\n if(sum + b > p) {\n\n System.out.println(i + 2);\n\n return;\n\n }\n\n }\n\n }\n\n }\n\n System.out.println(1);\n\n }\n\n public static long get(long a) {\n\n long ans = 1;\n\n for(long i = (long)Math.sqrt(a);i>=1;i--) {\n\n if(i*(i+1l)\/2l <= a) return i;\n\n }\n\n return ans;\n\n }\n\n public static long get2(long a) {\n\n long ans = 1;\n\n for(long i = (long)Math.sqrt(a);i>=1;i--) {\n\n if(i*(i+1)\/2 < a ) return ans;\n\n ans = i;\n\n }\n\n return 1l;\n\n }\n\n public static long rl() {\n\n return sc.nextLong();\n\n }\n\n public static char[] rac() {\n\n return sc.next().toCharArray();\n\n }\n\n public static String rs() {\n\n return sc.next();\n\n }\n\n public static int [] rai(int n) {\n\n int ans[] = new int[n];\n\n for(int i =0;i 0) {\n\n ans++;\n\n num = num&(num-1);\n\n }\n\n return ans;\n\n }\n\n public static boolean isValid(int x ,int y , int n,char arr[][],boolean visited[][][][]) {\n\n return x>=0 && x=0 && y b) return 0;\n\n \/\/ if(l > r) return 0;\n\n \/\/ if(tree[node].min >= a && tree[node].max <= b) {\n\n \/\/ return tree[node].count; \n\n \/\/ }\n\n \/\/ int mid = l + (r-l)\/2;\n\n \/\/ int ans = query(node*2 ,l , mid ,a , b , tree) + query(node*2 +1,mid + 1, r , a , b, tree);\n\n \/\/ return ans;\n\n \/\/ }\n\n \/\/ \/\/ segment tree update over range\n\n \/\/ public static void update(int node, int i , int j ,int l , int r,long value, long arr[] ) {\n\n \/\/ if(l >= i && j >= r) {\n\n \/\/ arr[node] += value;\n\n \/\/ return;\n\n \/\/ }\n\n \/\/ if(j < l|| r < i) return;\n\n \/\/ int mid = l + (r-l)\/2;\n\n \/\/ update(node*2 ,i ,j ,l,mid,value, arr);\n\n \/\/ update(node*2 +1,i ,j ,mid + 1,r, value , arr);\n\n \/\/ }\n\n\n\n public static long pow(long a , long b , long mod) {\n\n if(b == 1) return a;\n\n if(b == 0) return 1;\n\n long ans = pow(a , b\/2 , mod)%mod;\n\n if(b%2 == 0) {\n\n return (ans*ans)%mod;\n\n }\n\n else {\n\n return ((ans*ans)%mod*a)%mod;\n\n }\n\n }\n\n \n\n \n\n public static boolean isVowel(char ch) {\n\n if(ch == 'a' || ch == 'e'||ch == 'i' || ch == 'o' || ch == 'u') return true;\n\n return false;\n\n }\n\n\n\n \n\n \n\n public static int getFactor(int num) {\n\n if(num==1) return 1;\n\n int ans = 2;\n\n int k = num\/2;\n\n for(int i = 2;i<=k;i++) {\n\n if(num%i==0) ans++;\n\n }\n\n return Math.abs(ans);\n\n }\n\n\n\n public static int[] readarr()throws IOException {\n\n int n = sc.nextInt();\n\n int arr[] = new int[n];\n\n for(int i =0;i 0 ){\n\n ans++;\n\n H += ar[i%n];\n\n i++;\n\n }\n\n out.println(ans);\n\n return;\n\n }\n\n out.println(\"-1\");\n\n }\n\n \n\n static boolean multipleTestCase = false; static FastScanner fs; static PrintWriter out;\n\n public static void main(String[]args){\n\n try{\n\n fs = new FastScanner();\n\n out = new PrintWriter(System.out);\n\n int tc = (multipleTestCase)?fs.nInt():1;\n\n while (tc-->0)solve();\n\n out.flush();\n\n out.close();\n\n }catch (Exception e){\n\n e.printStackTrace();\n\n }\n\n }\n\n static class FastScanner {\n\n BufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\n StringTokenizer st=new StringTokenizer(\"\");\n\n String n() {\n\n while (!st.hasMoreTokens())\n\n try {\n\n st=new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return st.nextToken();\n\n }\n\n String Line()\n\n {\n\n String str = \"\";\n\n try\n\n {\n\n str = br.readLine();\n\n }catch (IOException e)\n\n {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n int nInt() {return Integer.parseInt(n()); }\n\n long nLong() {return Long.parseLong(n());}\n\n double nDouble(){return Double.parseDouble(n());}\n\n int[]aI(int n){\n\n int[]ar = new int[n];\n\n for(int i=0;iaj+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.util.*;\n\n\n\npublic class countthearrays {\n\n\n\n\tpublic static void main(String[] args) {\n\n\n\n\t\tScanner sc = new Scanner(System.in);\n\n\n\n\t\tint n = sc.nextInt();\n\n\t\tint m = sc.nextInt();\n\n\n\n\t\tint k = 998244353;\n\n\t\tlong pow = 1;\n\n\t\tlong[] fac = new long[m + 1];\n\n\t\tfac[0] = 1;\n\n\t\tfac[1] = 1;\n\n\t\tfor (int i = 2; i <= m; i++) {\n\n\t\t\tfac[i] = ((long) fac[i - 1] * i) % k;\n\n\t\t}\n\n\t\tfor (int i = 1; i < n - 2; i++) {\n\n\t\t\tpow = pow * 2 % k;\n\n\t\t}\n\n\t\tlong ncr = 0;\n\n\t\tncr = fac[m] * modInverse(fac[n - 1], k) % k * modInverse(fac[m - n + 1], k) % k;\n\n\t\tlong ans = ncr * (n - 2) % k;\n\n\t\tans = ans * pow % k;\n\n\t\tSystem.out.println(ans);\n\n\n\n\t}\n\n\n\n\tstatic long power(long x, long y, int p) {\n\n\n\n\t\tlong res = 1;\n\n\n\n\t\tx = x % p;\n\n\n\n\t\twhile (y > 0) {\n\n\n\n\t\t\tif (y % 2 == 1) {\n\n\t\t\t\tres = (res * x) % p;\n\n\t\t\t}\n\n\n\n\t\t\ty = y >> 1;\n\n\t\t\tx = (x * x) % p;\n\n\n\n\t\t}\n\n\n\n\t\treturn res;\n\n\t}\n\n\n\n\tstatic long modInverse(long n, int p) {\n\n\t\treturn power(n, p - 2, p);\n\n\t}\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.io.*;\n\nimport java.util.*;\n\n\n\npublic class A1 {\n\n static final Reader s = new Reader();\n\n static final PrintWriter out = new PrintWriter(System.out);\n\n\n\n public static void main(String[] args) throws IOException {\n\n\/\/ int t = s.nextInt();\n\n int t=1;\n\n for(int i=1; i<=t; ++i) {\n\n\/\/ out.print(\"Case #\"+i+\": \");\n\n new Solver();\n\n }\n\n out.close();\n\n }\n\n static class Solver {\n\n Solver() {\n\n \tScanner sc = new Scanner(System.in); \n\n \tint n = sc.nextInt(),m = sc.nextInt();\n\n \t sc.nextLine();\n\n \tString[] a = sc.nextLine().split(\" \");\n\n \tString[] b = sc.nextLine().split(\" \");\n\n \tint q = sc.nextInt();\n\n\t \twhile(q-->0) {\n\n\t \t\tint q1 = sc.nextInt();\n\n\t \t\tint g = q1%n; \n\n\t \t\tint h = q1%m;\n\n\t \t\tif(g==0)g=n;\n\n\t \t\tif(h==0)h=m;\n\n\t \t\tString ans=\"\";\n\n\t \t\tans+=a[g-1]+b[h-1];\n\n\t \t\tSystem.out.println(ans);\n\n\t \t}\n\n }\n\n }\n\n static class Reader {\n\n BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n\n StringTokenizer st;\n\n String next() {\n\n while(st==null||!st.hasMoreTokens()) {\n\n try {\n\n st=new StringTokenizer(in.readLine());\n\n } catch(Exception e) {}\n\n }\n\n return st.nextToken();\n\n }\n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n }\n\n\n\n}","language":"java"} +{"contest_id":"1295","problem_id":"B","statement":"B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss\u2026t=ssss\u2026 For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q\u2212cnt1,qcnt0,q\u2212cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string \"abcd\" has 5 prefixes: empty string, \"a\", \"ab\", \"abc\" and \"abcd\".InputThe first line contains the single integer TT (1\u2264T\u22641001\u2264T\u2264100) \u2014 the number of test cases.Next 2T2T lines contain descriptions of test cases \u2014 two lines per test case. The first line contains two integers nn and xx (1\u2264n\u22641051\u2264n\u2264105, \u2212109\u2264x\u2264109\u2212109\u2264x\u2264109) \u2014 the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si\u2208{0,1}si\u2208{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers \u2014 one per test case. For each test case print the number of prefixes or \u22121\u22121 if there is an infinite number of such prefixes.ExampleInputCopy4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01\nOutputCopy3\n0\n1\n-1\nNoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.","tags":["math","strings"],"code":"import java.util.*;\n\nimport java.io.*;\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\n\n static void solve() {\n\n int n = i();\n\n int x = i();\n\n \n\n String str = s();\n\n int cnt0 = 0;\n\n for(int i =0;i=0){\n\n ans++;\n\n }\n\n }\n\n if(str.charAt(i)=='0') cbal++;\n\n else cbal--;\n\n }\n\n \n\n System.out.println(ans);\n\n }\n\n\n\n public static void main(String[] args) {\n\n sb = new StringBuilder();\n\n int test = i();\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":"1300","problem_id":"A","statement":"A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,\u2026,ana1,a2,\u2026,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1\u2264i\u2264n1\u2264i\u2264n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ \u2026\u2026 +an\u22600+an\u22600 and a1\u22c5a2\u22c5a1\u22c5a2\u22c5 \u2026\u2026 \u22c5an\u22600\u22c5an\u22600.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u22641031\u2264t\u2264103). The description of the test cases follows.The first line of each test case contains an integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the size of the array.The second line of each test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (\u2212100\u2264ai\u2264100\u2212100\u2264ai\u2264100)\u00a0\u2014 elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1\nOutputCopy1\n2\n0\n2\nNoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,\u22121,\u22121][3,\u22121,\u22121], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [\u22121,1,1,1][\u22121,1,1,1], the sum will be equal to 22 and the product will be equal to \u22121\u22121. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,\u22122,1][2,\u22122,1], the sum will be 11 and the product will be \u22124\u22124.","tags":["implementation","math"],"code":"import java.io.*;\n\nimport java.util.*;\n\npublic class main{\n\n\tpublic static void main(String args[]){\n\n\t\tScanner scn = new Scanner(System.in);\n\n\t\tint t = Integer.parseInt(scn.nextLine());\n\n\n\n\t\twhile(t-->0){\n\n\t\t int n =Integer.parseInt(scn.nextLine()); \n\n\t\t\tString inputs[] = scn.nextLine().split(\" \");\n\n\t\t\tint sum = 0;\n\n\t\t\tint ans = 0;\n\n\t\t\tfor(int i=0;ikk\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\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\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 class Segment {\n\n int start;\n\n int end;\n\n\n\n Segment(int start, int end) {\n\n this.start = start;\n\n this.end = end;\n\n }\n\n }\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 int[] arr = new int[n];\n\n for (int i = 0; i < n; i++) {\n\n arr[i] = sc.nextInt();\n\n }\n\n\n\n \/\/ divide into max subarray-blocks, such that each have same sum.\n\n\n\n Map> segmentsWithParticularSum = new HashMap<>();\n\n \/\/ for each possible subarray-sum\n\n for (int end = 0; end < n; end++) {\n\n long blockSum = 0;\n\n for (int start = end; start >= 0; start--) {\n\n blockSum += arr[start];\n\n if (!segmentsWithParticularSum.containsKey(blockSum)) {\n\n segmentsWithParticularSum.put(blockSum, new ArrayList<>());\n\n }\n\n segmentsWithParticularSum.get(blockSum).add(new Segment(start + 1, end + 1));\n\n }\n\n }\n\n\n\n List bestSegmentsChosen = new ArrayList<>();\n\n int maxTotalBlocks = 0;\n\n for (long blockSum : segmentsWithParticularSum.keySet()) {\n\n List blocksTaken = new ArrayList<>();\n\n int lastBlockEnd = -1, totalBlocks = 0;\n\n for (Segment segment : segmentsWithParticularSum.get(blockSum)) {\n\n if (segment.start > lastBlockEnd) {\n\n totalBlocks++;\n\n blocksTaken.add(segment);\n\n lastBlockEnd = segment.end;\n\n }\n\n }\n\n\n\n if (totalBlocks > maxTotalBlocks) {\n\n maxTotalBlocks = totalBlocks;\n\n bestSegmentsChosen = new ArrayList<>(blocksTaken);\n\n }\n\n }\n\n\n\n out.println(maxTotalBlocks);\n\n for (Segment segment : bestSegmentsChosen) {\n\n out.println(segment.start + \" \" + segment.end);\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":"1311","problem_id":"D","statement":"D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a\u2264b\u2264ca\u2264b\u2264c.In one move, you can add +1+1 or \u22121\u22121 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A\u2264B\u2264CA\u2264B\u2264C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1\u2264a\u2264b\u2264c\u22641041\u2264a\u2264b\u2264c\u2264104).OutputFor each test case, print the answer. In the first line print resres \u2014 the minimum number of operations you have to perform to obtain three integers A\u2264B\u2264CA\u2264B\u2264C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8\n1 2 3\n123 321 456\n5 10 15\n15 18 21\n100 100 101\n1 22 29\n3 19 38\n6 30 46\nOutputCopy1\n1 1 3\n102\n114 228 456\n4\n4 8 16\n6\n18 18 18\n1\n100 100 100\n7\n1 22 22\n2\n1 19 38\n8\n6 24 48\n","tags":["brute force","math"],"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 DThreeIntegers solver = new DThreeIntegers();\n int testCount = Integer.parseInt(in.next());\n for (int i = 1; i <= testCount; i++) {\n solver.solve(i, in, out);\n }\n out.close();\n }\n\n static class DThreeIntegers {\n public void solve(int testNumber, InputReader in, OutputWriter out) {\n int a = in.nextInt();\n int b = in.nextInt();\n int c = in.nextInt();\n int max = 0;\n max = Math.max(max, a);\n max = Math.max(max, b);\n max = Math.max(max, c);\n int min = (int) 1e9;\n int[] res = new int[3];\n for (int i = 1; i <= max; i++) {\n for (int j = 1; i * j <= 2e4; j++) {\n for (int k = 1; i * j * k <= 2e4; k++) {\n int d = Math.abs(a - i) + Math.abs(i * j - b) + Math.abs(i * j * k - c);\n if (d < min) {\n min = d;\n res[0] = i;\n res[1] = i * j;\n res[2] = i * j * k;\n }\n }\n }\n }\n out.println(min);\n out.println(res);\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 String next() {\n return nextString();\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(int[] array) {\n for (int i = 0; i < array.length; i++) {\n if (i != 0) {\n writer.print(' ');\n }\n writer.print(array[i]);\n }\n }\n\n public void println(int[] array) {\n print(array);\n writer.println();\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":"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= lenbuf) {\n\n\t\t\t\tcurbuf = 0;\n\n\t\t\t\ttry {\n\n\t\t\t\t\tlenbuf = in.read(buffer);\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 (lenbuf <= 0)\n\n\t\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t\treturn true;\n\n\t\t}\n\n \n\n\t\tprivate int readByte() {\n\n\t\t\tif (hasNextByte())\n\n\t\t\t\treturn buffer[curbuf++];\n\n\t\t\telse\n\n\t\t\t\treturn -1;\n\n\t\t}\n\n \n\n\t\tprivate boolean isSpaceChar(int c) {\n\n\t\t\treturn !(c >= 33 && c <= 126);\n\n\t\t}\n\n \n\n\t\tprivate void skip() {\n\n\t\t\twhile (hasNextByte() && isSpaceChar(buffer[curbuf]))\n\n\t\t\t\tcurbuf++;\n\n\t\t}\n\n \n\n\t\tpublic boolean hasNext() {\n\n\t\t\tskip();\n\n\t\t\treturn hasNextByte();\n\n\t\t}\n\n \n\n\t\tpublic String next() {\n\n\t\t\tif (!hasNext())\n\n\t\t\t\tthrow new NoSuchElementException();\n\n\t\t\tStringBuilder sb = new StringBuilder();\n\n\t\t\tint b = readByte();\n\n\t\t\twhile (!isSpaceChar(b)) {\n\n\t\t\t\tsb.appendCodePoint(b);\n\n\t\t\t\tb = readByte();\n\n\t\t\t}\n\n\t\t\treturn sb.toString();\n\n\t\t}\n\n \n\n\t\tpublic int nextInt() {\n\n\t\t\tif (!hasNext())\n\n\t\t\t\tthrow new NoSuchElementException();\n\n\t\t\tint c = readByte();\n\n\t\t\twhile (isSpaceChar(c))\n\n\t\t\t\tc = readByte();\n\n\t\t\tboolean minus = false;\n\n\t\t\tif (c == '-') {\n\n\t\t\t\tminus = true;\n\n\t\t\t\tc = readByte();\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 = res * 10 + c - '0';\n\n\t\t\t\tc = readByte();\n\n\t\t\t} while (!isSpaceChar(c));\n\n\t\t\treturn (minus) ? -res : res;\n\n\t\t}\n\n \n\n\t\tpublic long nextLong() {\n\n\t\t\tif (!hasNext())\n\n\t\t\t\tthrow new NoSuchElementException();\n\n\t\t\tint c = readByte();\n\n\t\t\twhile (isSpaceChar(c))\n\n\t\t\t\tc = readByte();\n\n\t\t\tboolean minus = false;\n\n\t\t\tif (c == '-') {\n\n\t\t\t\tminus = true;\n\n\t\t\t\tc = readByte();\n\n\t\t\t}\n\n\t\t\tlong 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 = res * 10 + c - '0';\n\n\t\t\t\tc = readByte();\n\n\t\t\t} while (!isSpaceChar(c));\n\n\t\t\treturn (minus) ? -res : res;\n\n\t\t}\n\n \n\n\t\tpublic double nextDouble() {\n\n\t\t\treturn Double.parseDouble(next());\n\n\t\t}\n\n \n\n\t\tpublic int[] nextIntArray(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\t\tpublic double[] nextDoubleArray(int n) {\n\n\t\t\tdouble[] a = new double[n];\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t\ta[i] = nextDouble();\n\n\t\t\treturn a;\n\n\t\t}\n\n\t\tpublic long[] nextLongArray(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\tpublic char[][] nextCharMap(int n, int m) {\n\n\t\t\tchar[][] map = new char[n][m];\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t\tmap[i] = next().toCharArray();\n\n\t\t\treturn map;\n\n\t\t}\n\n\t}\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.io.OutputStream;\n\nimport java.io.IOException;\n\nimport java.io.InputStream;\n\nimport java.io.PrintWriter;\n\nimport java.util.InputMismatchException;\n\nimport java.io.IOException;\n\nimport java.util.ArrayList;\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\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 FastReader in = new FastReader(inputStream);\n\n PrintWriter out = new PrintWriter(outputStream);\n\n DTimeToRun solver = new DTimeToRun();\n\n solver.solve(1, in, out);\n\n out.close();\n\n }\n\n\n\n static class DTimeToRun {\n\n public void solve(int testNumber, FastReader s, PrintWriter out) {\n\n int n = s.nextInt();\n\n int m = s.nextInt();\n\n int k = s.nextInt();\n\n\n\n if (k > (4 * n * m) - (2 * n) - (2 * m)) {\n\n out.println(\"NO\");\n\n return;\n\n }\n\n\n\n out.println(\"YES\");\n\n ArrayList list = new ArrayList<>();\n\n\n\n if (n == 1) {\n\n if (k >= m - 1) {\n\n list.add(new DTimeToRun.pair(m - 1, \"R\"));\n\n k -= (m - 1);\n\n list.add(new DTimeToRun.pair(k, \"L\"));\n\n } else {\n\n list.add(new DTimeToRun.pair(k, \"R\"));\n\n }\n\n } else if (m == 1) {\n\n if (k >= n - 1) {\n\n list.add(new DTimeToRun.pair(n - 1, \"D\"));\n\n k -= (n - 1);\n\n list.add(new DTimeToRun.pair(k, \"U\"));\n\n } else {\n\n list.add(new DTimeToRun.pair(k, \"D\"));\n\n }\n\n } else {\n\n for (int i = 0; i < n && k > 0; i++) {\n\n if (k >= m - 1) {\n\n list.add(new DTimeToRun.pair(m - 1, \"R\"));\n\n k -= (m - 1);\n\n } else {\n\n list.add(new DTimeToRun.pair(k, \"R\"));\n\n k = 0;\n\n }\n\n\n\n if (k == 0) {\n\n break;\n\n }\n\n\n\n if (i == 0) {\n\n if (k >= m - 1) {\n\n list.add(new DTimeToRun.pair(m - 1, \"L\"));\n\n k -= (m - 1);\n\n } else {\n\n list.add(new DTimeToRun.pair(k, \"R\"));\n\n k = 0;\n\n }\n\n } else {\n\n if (k >= 3 * (m - 1)) {\n\n list.add(new DTimeToRun.pair(m - 1, \"UDL\"));\n\n k = k - (3 * (m - 1));\n\n } else {\n\n if (k >= 3) {\n\n list.add(new DTimeToRun.pair(k \/ 3, \"UDL\"));\n\n }\n\n k %= 3;\n\n if (k == 2) {\n\n list.add(new DTimeToRun.pair(1, \"UD\"));\n\n } else if (k == 1) {\n\n list.add(new DTimeToRun.pair(1, \"U\"));\n\n }\n\n k = 0;\n\n }\n\n }\n\n\n\n if (k == 0) {\n\n break;\n\n }\n\n\n\n if (i == n - 1) {\n\n if (k >= n - 1) {\n\n list.add(new DTimeToRun.pair(n - 1, \"U\"));\n\n k -= (n - 1);\n\n } else {\n\n list.add(new DTimeToRun.pair(k, \"U\"));\n\n k = 0;\n\n }\n\n } else {\n\n if (k >= 1) {\n\n list.add(new DTimeToRun.pair(1, \"D\"));\n\n k--;\n\n }\n\n }\n\n }\n\n }\n\n\n\n out.println(list.size());\n\n out.println(DTimeToRun.arrayLists.print(list));\n\n\n\n\n\n }\n\n\n\n private static class pair {\n\n int val;\n\n String str;\n\n\n\n public pair(int val, String str) {\n\n this.val = val;\n\n this.str = str;\n\n }\n\n\n\n public String toString() {\n\n return this.val + \" \" + this.str;\n\n }\n\n\n\n }\n\n\n\n private static class arrayLists {\n\n static StringBuilder print(ArrayList list) {\n\n StringBuilder ans = new StringBuilder();\n\n for (Object curr : list) {\n\n ans.append(curr.toString()).append(\"\\n\");\n\n }\n\n return ans;\n\n }\n\n\n\n }\n\n\n\n }\n\n\n\n static class FastReader {\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 FastReader.SpaceCharFilter filter;\n\n\n\n public FastReader(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 }\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 }\n\n return buf[curChar++];\n\n }\n\n\n\n public int nextInt() {\n\n int c = read();\n\n while (isSpaceChar(c)) {\n\n c = read();\n\n }\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 }\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 boolean isSpaceChar(int c) {\n\n if (filter != null) {\n\n return filter.isSpaceChar(c);\n\n }\n\n return isWhitespace(c);\n\n }\n\n\n\n public static boolean isWhitespace(int c) {\n\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n\n }\n\n\n\n public interface SpaceCharFilter {\n\n public boolean isSpaceChar(int ch);\n\n\n\n }\n\n\n\n }\n\n}\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.util.*;\nimport java.io.*;\n\npublic class Main{\n \n static int n, m;\n static int[]t;\n static int[][] a;\n static int x, y;\n \n static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));\n static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));\n static int nextInt()throws Exception{\n in.nextToken();\n return (int)in.nval;\n }\n\n \n static boolean check(int v){\n Arrays.fill(t, 0);\n for(int i=1; i<=n; i++){\n int c = 0;\n for(int j=0; j=v?1<0)\n for(int j=i; j<(1<0&&(i|j)==(1<> 1;\n \n if(check(mid)) l = mid;\n \n else r = mid - 1;\n \n }\n check(l);\n System.out.println(x+\" \"+y);\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":"\/*\n\n4 1 2\n\n1 16 10 3\n\n18\n\n19\n\n13\n\n15\n\n\n\nNumber of people, number of players chosen for the team, number of players chosen for the audience \n\nBonus that each person adds if they are put into the audience \n\nFor every person, bonus that they add if they are put into the team at position i \n\n\n\nBitmask DP - dp[i][j] = max score that Alice can get given the first i people and that j slots in the team are filled\n\n*\/\n\nimport java.util.*;\n\nimport java.io.*;\n\n\n\npublic class Main{\n\n public static int n; \/\/total people in town\n\n public static int p; \/\/players for the team\n\n public static int k; \/\/players for the audience\n\n public static Person[] people; \n\n public static void main(String[] args) throws IOException{\n\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n\n\n StringTokenizer details = new StringTokenizer(br.readLine());\n\n n = Integer.parseInt(details.nextToken());\n\n p = Integer.parseInt(details.nextToken());\n\n k = Integer.parseInt(details.nextToken());\n\n people = new Person[n];\n\n StringTokenizer ad = new StringTokenizer(br.readLine());\n\n for(int a = 0; a < n; a++){\n\n StringTokenizer pos = new StringTokenizer(br.readLine());\n\n long[] ps = new long[p];\n\n for(int b = 0; b < p; b++) ps[b] = Long.parseLong(pos.nextToken());\n\n people[a] = new Person(a, Long.parseLong(ad.nextToken()), ps);\n\n }\n\n Arrays.sort(people);\n\n \/\/System.out.println(Arrays.toString(people));\n\n\n\n long[][] dp = new long[n + 1][(1 << p)];\n\n for(long[] row : dp) Arrays.fill(row, -1000000000000000000L);\n\n dp[0][0] = 0;\n\n for(int a = 1; a <= n; a++){\n\n \/\/forward dp? Try putting this person in the team at position b, or putting them in the audience (?) --> how to figure out which people are in the audience and not in the audience?\n\n for(int mask = 0; mask < (1 << p); mask++){\n\n \/\/either occupied or not occupied, try putting this person at position pos\n\n dp[a][mask] = dp[a - 1][mask];\n\n int aud = a - 1 - Integer.bitCount(mask); \/\/size of current audience\n\n if(aud < k) dp[a][mask] = Math.max(dp[a - 1][mask] + people[a - 1].add, dp[a][mask]);\n\n for(int pos = 0; pos < p; pos++){\n\n if((mask & (1 << pos)) > 0){\n\n dp[a][mask] = Math.max(dp[a][mask], dp[a - 1][mask - (1 << pos)] + people[a - 1].pAdd[pos]);\n\n } \n\n \/\/can also try just putting this person in the audience, sorted from greatest contribution to the audience to least contribution to the audience\n\n }\n\n }\n\n }\n\n\n\n System.out.println(dp[n][(1 << p) - 1]);\n\n \n\n br.close();\n\n }\n\n}\n\nclass Person implements Comparable{\n\n int id; \n\n long add; \n\n long[] pAdd; \n\n public Person(int i, long a, long[] pa){\n\n id = i; \n\n add = a; \n\n pAdd = pa; \n\n }\n\n public String toString(){\n\n return id + \" id, adds \" + add + \" to audience, cost for each pos is \" + Arrays.toString(pAdd);\n\n }\n\n public int compareTo(Person p){\n\n if(add > p.add) return -1; \n\n if(add < p.add) return 1; \n\n return id - p.id; \n\n }\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":"import java.io.*;\n\nimport java.util.*;\n\n\n\npublic class Codeforces\n\n{\n\n public static void main(String args[])throws Exception\n\n {\n\n BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));\n\n StringBuilder sb=new StringBuilder();\n\n String s[]=bu.readLine().split(\" \");\n\n int n=Integer.parseInt(s[0]),k=Integer.parseInt(s[1]);\n\n int i,sz[]=new int[n];\n\n ArrayList g[]=new ArrayList[n];\n\n for(i=0;i();\n\n for(i=0;i>1;\n\n if(possible(sz,mid,k))\n\n {\n\n ans=mid;\n\n r=mid-1;\n\n }\n\n else l=mid+1;\n\n }\n\n\n\n fill(g,f,ans);\n\n sb.append(ans+\"\\n\");\n\n for(i=0;im) y++;\n\n if(y>k) return false;\n\n }\n\n return true;\n\n }\n\n\n\n static void fill(ArrayList g[],int f[],int m)\n\n {\n\n Queue q=new LinkedList<>();\n\n boolean v[]=new boolean[f.length];\n\n v[0]=true;\n\n int col=0,y=0,c[]=new int[f.length];\n\n for(Road x:g[0])\n\n {\n\n q.add(x.v);\n\n f[x.i]=col;\n\n v[x.v]=true;\n\n c[x.v]=col;\n\n col++; col%=m;\n\n }\n\n\n\n while(!q.isEmpty())\n\n {\n\n int p=q.poll();\n\n col=c[p];\n\n col++; col%=m;\n\n for(Road x:g[p])\n\n if(!v[x.v])\n\n {\n\n q.add(x.v);\n\n v[x.v]=true;\n\n c[x.v]=col;\n\n f[x.i]=col;\n\n col++; col%=m;\n\n }\n\n }\n\n }\n\n\n\n static class Road\n\n {\n\n int v,i;\n\n Road(int a,int b)\n\n {\n\n v=a;\n\n i=b;\n\n }\n\n }\n\n}","language":"java"} +{"contest_id":"1296","problem_id":"B","statement":"B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1\u2264x\u2264s1\u2264x\u2264s, buy food that costs exactly xx burles and obtain \u230ax10\u230b\u230ax10\u230b burles as a cashback (in other words, Mishka spends xx burles and obtains \u230ax10\u230b\u230ax10\u230b back). The operation \u230aab\u230b\u230aab\u230b means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1\u2264s\u22641091\u2264s\u2264109) \u2014 the number of burles Mishka initially has.OutputFor each test case print the answer on it \u2014 the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6\n1\n10\n19\n9876\n12345\n1000000000\nOutputCopy1\n11\n21\n10973\n13716\n1111111111\n","tags":["math"],"code":"import java.util.ArrayList;\n\nimport java.util.Scanner;\n\npublic class CF0911{\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\tlong currentMoney = scan.nextLong();\n\n\t\t\tint totalSpent = 0;\n\n\t\t\twhile(currentMoney>=10){\n\n\t\t\t\ttotalSpent += currentMoney - currentMoney%10;\n\n\t\t\t\tcurrentMoney = currentMoney\/10 + currentMoney%10;\n\n\t\t\t}\n\n\t\t\tSystem.out.println(currentMoney + totalSpent);\n\n\t\t\ttestCases--;\n\n\t\t}\n\n\t}\n\n\n\n}","language":"java"} +{"contest_id":"1141","problem_id":"F1","statement":"F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],\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\u2264501\u2264n\u226450) \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":["greedy"],"code":"import java.util.*;\n\nimport java.lang.*;\n\nimport java.io.*;\n\nimport java.awt.*;\n\n\n\n\/\/ U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................\n\n\/\/JUst keep faith in ur strengths .................................................. \n\n\n\n\n\n\/\/ ASCII = 48 + i ;\/\/ 2^28 = 268,435,456 > 2* 10^8 \/\/ log 10 base 2 = 3.3219 \n\n\/\/ odd:: (x^2+1)\/2 , (x^2-1)\/2 ; x>=3\/\/ even:: (x^2\/4)+1 ,(x^2\/4)-1 x >=4 \n\n\/\/ FOR ANY ODD NO N : N,N-1,N-2\n\n\/\/ALL ARE PAIRWISE COPRIME \n\n\/\/THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS\n\n\n\n\/\/ two consecutive odds are always coprime to each other\n\n\/\/ two consecutive even have always gcd = 2 ;\n\n\n\n\/\/ Rectangle r = new Rectangle(int x , int y,int widht,int height) \n\n\/\/Creates a rect. with bottom left cordinates as (x, y) and top right as ((x+width),(y+height))\n\n\n\n\/\/BY DEFAULT Priority Queue is MIN in nature in java\n\n\/\/to use as max , just push with negative sign and change sign after removal \n\n\n\n\/\/ We can make a sieve of max size 1e7 .(no time or space issue) \n\n\/\/ In 1e7 starting nos we have about 66*1e4 prime nos \n\n\n\n public class Main\n\n{\n\n \n\n \/\/ static int[] arr = new int[100002] ; \n\n \/\/ static int[] dp = new int[100002] ; \n\n \n\n static PrintWriter out;\n\n \n\n\tstatic class FastReader{\n\n\t\tBufferedReader br;\n\n\t\tStringTokenizer st;\n\n\t\tpublic FastReader(){\n\n\t\t\tbr=new BufferedReader(new InputStreamReader(System.in));\n\n\t\t\tout=new PrintWriter(System.out);\n\n\t\t}\n\n\t\tString next(){\n\n\t\t\twhile(st==null || !st.hasMoreElements()){\n\n\t\t\t\ttry{\n\n\t\t\t\t\tst= new StringTokenizer(br.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}\n\n\t\t\treturn st.nextToken();\n\n\t\t}\n\n\t\tint nextInt(){\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\t\tlong nextLong(){\n\n\t\t\treturn Long.parseLong(next());\n\n\t\t}\n\n\t\tdouble nextDouble(){\n\n\t\t\treturn Double.parseDouble(next());\n\n\t\t}\n\n\t\tString nextLine(){\n\n\t\t\tString str = \"\";\n\n\t\t\ttry{\n\n\t\t\t\tstr=br.readLine();\n\n\t\t\t}\n\n\t\t\tcatch(IOException e){\n\n\t\t\t\te.printStackTrace();\n\n\t\t\t}\n\n\t\t\treturn str;\n\n\t\t}\n\n\t}\n\n\t\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n public static int countDigit(long n) \n\n { \n\n return (int)Math.floor(Math.log10(n) + 1); \n\n } \n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n\n \n\n public static int sumOfDigits(long n)\n\n {\n\n \n\n if( n< 0)return -1 ;\n\n \n\n int sum = 0;\n\n \n\n while( n > 0)\n\n {\n\n sum = sum + (int)( n %10) ;\n\n \n\n n \/= 10 ;\n\n }\n\n \n\n return sum ; \n\n \n\n \n\n \n\n }\n\n \n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\npublic static long arraySum(int[] arr , int start , int end)\n\n{\n\n long ans = 0 ;\n\n \n\n for(int i = start ; i <= end ; i++)ans += arr[i] ;\n\n \n\n return ans ;\n\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\npublic static void swapArray(int[] arr , int start , int end)\n\n{\n\n while(start < end)\n\n {\n\n int temp = arr[start] ;\n\n arr[start] = arr[end];\n\n arr[end] = temp;\n\n start++ ;end-- ;\n\n }\n\n}\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\nstatic long factorial(long a)\n\n{\n\n if(a== 0L || a==1L)return 1L ;\n\n \n\n return a*factorial(a-1L) ;\n\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n\n\npublic static int[][] rotate(int[][] input){\n\n\n\nint n =input.length;\n\nint m = input[0].length ;\n\nint[][] output = new int [m][n];\n\n\n\nfor (int i=0; i= 0 ; i-- )\n\n {\n\n str.append(input.charAt(i));\n\n }\n\n \n\nreturn str.toString() ;\n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\npublic static boolean isPossibleTriangle(int a ,int b , int c)\n\n{\n\n if( a + b > c && c+b > a && a +c > b)return true ;\n\n else return false ;\n\n}\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic long xnor(long num1, long num2) {\n\n\t\tif (num1 < num2) {\n\n\t\t\tlong temp = num1;\n\n\t\t\tnum1 = num2;\n\n\t\t\tnum2 = temp;\n\n\t\t}\n\n\t\tnum1 = togglebit(num1);\n\n\t\treturn num1 ^ num2;\n\n\t}\n\n\n\n\tstatic long togglebit(long n) {\n\n\t\tif (n == 0)\n\n\t\t\treturn 1;\n\n\t\tlong i = n;\n\n\t\tn |= n >> 1;\n\n\t\tn |= n >> 2;\n\n\t\tn |= n >> 4;\n\n\t\tn |= n >> 8;\n\n\t\tn |= n >> 16;\n\n\t\treturn i ^ n;\n\n\t}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\npublic static int xorOfFirstN(int n)\n\n{\n\n \n\n \n\n if( n % 4 ==0)return n ;\n\n \n\n else if( n % 4 == 1)return 1 ;\n\n \n\n else if( n % 4 == 2)return n+1 ;\n\n \n\n else return 0 ;\n\n \n\n \n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\npublic static int gcd(int a, int b )\n\n{\n\n\n\nif(b==0)return a ;\n\n\n\nelse return gcd(b,a%b) ; \n\n\n\n}\n\n\n\n\n\npublic static long gcd(long a, long b )\n\n{\n\n\n\nif(b==0)return a ;\n\n\n\nelse return gcd(b,a%b) ; \n\n\n\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\npublic static int lcm(int a, int b ,int c , int d )\n\n{\n\n\n\nint temp = lcm(a,b , c) ;\n\n\n\n\n\n \n\n int ans = lcm(temp ,d ) ;\n\n\n\nreturn ans ;\n\n\n\n\n\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\npublic static int lcm(int a, int b ,int c )\n\n{\n\n\n\nint temp = lcm(a,b) ;\n\n\n\nint ans = lcm(temp ,c) ;\n\n\n\nreturn ans ;\n\n\n\n\n\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \n\npublic static int lcm(int a , int b )\n\n{\n\n\n\nint gc = gcd(a,b);\n\n\n\nreturn (a\/gc)*b ;\n\n}\n\n\n\n\n\npublic static long lcm(long a , long b )\n\n{\n\n\n\nlong gc = gcd(a,b);\n\n\n\nreturn (a\/gc)*b;\n\n}\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic boolean isPrime(long n)\n\n{\n\n if(n==1)\n\n {\n\n return false ;\n\n }\n\n \n\n boolean ans = true ;\n\n \n\n for(long i = 2L; i*i <= n ;i++)\n\n {\n\n if(n% i ==0)\n\n {\n\n ans = false ;break ;\n\n }\n\n }\n\n \n\n \n\n return ans ;\n\n} \n\n\n\nstatic boolean isPrime(int n)\n\n{\n\n if(n==1)\n\n {\n\n return false ;\n\n }\n\n \n\n boolean ans = true ;\n\n \n\n for(int i = 2; i*i <= n ;i++)\n\n {\n\n if(n% i ==0)\n\n {\n\n ans = false ;break ;\n\n }\n\n }\n\n \n\n \n\n return ans ;\n\n} \n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\nstatic int sieve = 1000000 ;\n\n\n\n \n\nstatic boolean[] prime = new boolean[sieve + 1] ;\n\n\n\npublic static void sieveOfEratosthenes() \n\n { \n\n \/\/ FALSE == prime\n\n \n\n \/\/ TRUE == COMPOSITE\n\n \n\n \/\/ FALSE== 1\n\n \n\n \n\n \/\/ time complexity = 0(NlogLogN)== o(N)\n\n \n\n \/\/ gives prime nos bw 1 to N\n\n \n\n for(int i = 4; i<= sieve ; i++)\n\n {\n\n prime[i] = true ;\n\n i++ ;\n\n }\n\n \n\n for(int p = 3; p*p <= sieve; p++) \n\n { \n\n \n\n if(prime[p] == false) \n\n { \n\n \n\n for(int i = p*p; i <= sieve; i += p) \n\n prime[i] = true; \n\n } \n\n \n\n p++ ;\n\n } \n\n \n\n \n\n \n\n \n\n } \n\n \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n\n\npublic static void sortD(int[] arr , int s , int e)\n\n{\n\n sort(arr ,s , e) ;\n\n \n\n int i =s ; int j = e ;\n\n \n\n while( i < j)\n\n {\n\n int temp = arr[i] ;\n\n arr[i] =arr[j] ;\n\n arr[j] = temp ;\n\n i++ ; j-- ;\n\n }\n\n \n\n \n\n \n\n return ;\n\n}\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\npublic static long countSubarraysSumToK(long[] arr ,long sum )\n\n {\n\n HashMap map = new HashMap<>() ;\n\n \n\n int n = arr.length ;\n\n \n\n long prefixsum = 0 ;\n\n \n\n long count = 0L ;\n\n for(int i = 0; i < n ; i++)\n\n {\n\n prefixsum = prefixsum + arr[i] ;\n\n \n\n if(sum == prefixsum)count = count+1 ;\n\n \n\n if(map.containsKey(prefixsum -sum))\n\n {\n\n count = count + map.get(prefixsum -sum) ;\n\n }\n\n \n\n \n\n if(map.containsKey(prefixsum ))\n\n {\n\n map.put(prefixsum , map.get(prefixsum) +1 );\n\n }\n\n \n\n else{\n\n map.put(prefixsum , 1L );\n\n }\n\n \n\n \n\n }\n\n \n\n \n\n \n\n return count ; \n\n \n\n }\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n\n\n\/\/ KMP ALGORITHM : TIME COMPL:O(N+M) \n\n\/\/ FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING\n\n\/\/RETURN THE ARRAYLIST OF INDEXES \n\n\/\/ IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING\n\n\n\n\n\npublic static ArrayList kmpAlgorithm(String str , String pat)\n\n {\n\n ArrayList list =new ArrayList<>();\n\n \n\n int n = str.length() ;\n\n int m = pat.length() ;\n\n \n\n String q = pat + \"#\" + str ;\n\n \n\n int[] lps =new int[n+m+1] ;\n\n \n\n longestPefixSuffix(lps, q,(n+m+1)) ;\n\n \n\n \n\n for(int i =m+1 ; i < (n+m+1) ; i++ )\n\n {\n\n if(lps[i] == m)\n\n {\n\n list.add(i-2*m) ;\n\n }\n\n }\n\n \n\n return list ; \n\n \n\n \n\n }\n\n \n\n\n\npublic static void longestPefixSuffix(int[] lps ,String str , int n)\n\n {\n\n lps[0] = 0 ;\n\n \n\n for(int i = 1 ; i<= n-1; i++)\n\n {\n\n int l = lps[i-1] ;\n\n \n\n while( l > 0 && str.charAt(i) != str.charAt(l))\n\n {\n\n l = lps[l-1] ;\n\n }\n\n \n\n if(str.charAt(i) == str.charAt(l))\n\n {\n\n l++ ;\n\n }\n\n \n\n \n\n lps[i] = l ; \n\n }\n\n \n\n }\n\n \n\n \n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n \/\/ CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n\n\n \/\/ TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1 \n\n \/\/ or n and the no will be coprime in nature\n\n \/\/time : O(n*(log(logn)))\n\n \n\n public static void eulerTotientFunction(int[] arr ,int n )\n\n {\n\n \n\n for(int i = 1; i <= n ;i++)arr[i] =i ;\n\n \n\n \n\n for(int i= 2 ; i<= n ;i++)\n\n {\n\n if(arr[i] == i)\n\n {\n\n arr[i] =i-1 ;\n\n \n\n for(int j =2*i ; j<= n ; j+= i )\n\n {\n\n arr[j] = (arr[j]*(i-1))\/i ;\n\n }\n\n \n\n }\n\n }\n\n \n\n return ; \n\n \n\n }\n\n\t\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\npublic static long nCr(int n,int k)\n\n{\n\n long ans=1L;\n\n k=k>n-k?n-k:k;\n\n int j=1;\n\n for(;j<=k;j++,n--)\n\n {\n\n if(n%j==0)\n\n {\n\n ans*=n\/j;\n\n }else\n\n if(ans%j==0)\n\n {\n\n ans=ans\/j*n;\n\n }else\n\n {\n\n ans=(ans*n)\/j;\n\n }\n\n }\n\n return ans;\n\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\npublic static ArrayList allFactors(int n)\n\n{ \n\n ArrayList list = new ArrayList<>() ;\n\n \n\n for(int i = 1; i*i <= n ;i++)\n\n {\n\n if( n % i == 0)\n\n {\n\n if(i*i == n)\n\n {\n\n list.add(i) ;\n\n }\n\n else{\n\n list.add(i) ;\n\n list.add(n\/i) ;\n\n \n\n }\n\n }\n\n }\n\n \n\n return list ; \n\n \n\n \n\n}\n\n\n\n\n\npublic static ArrayList allFactors(long n)\n\n{ \n\n ArrayList list = new ArrayList<>() ;\n\n \n\n for(long i = 1L; i*i <= n ;i++)\n\n {\n\n if( n % i == 0)\n\n {\n\n if(i*i == n)\n\n {\n\n list.add(i) ;\n\n }\n\n else{\n\n list.add(i) ;\n\n list.add(n\/i) ;\n\n \n\n }\n\n }\n\n }\n\n \n\n return list ; \n\n \n\n \n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n static final int MAXN = 1000001; \n\n \n\n \n\n static int spf[] = new int[MAXN]; \n\n \n\n static void sieve() \n\n { \n\n spf[1] = 1; \n\n for (int i=2; i getPrimeFactorization(int x) \n\n { \n\n ArrayList ret = new ArrayList(); \n\n while (x != 1) \n\n { \n\n ret.add(spf[x]); \n\n x = x \/ spf[x]; \n\n } \n\n return ret; \n\n } \n\n \n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \n\npublic static void merge(int arr[], int l, int m, int r)\n\n {\n\n \/\/ Find sizes of two subarrays to be merged\n\n int n1 = m - l + 1;\n\n int n2 = r - m;\n\n \n\n \/* Create temp arrays *\/\n\n int L[] = new int[n1];\n\n int R[] = new int[n2];\n\n \n\n \/\/Copy data to temp arrays\n\n for (int i=0; i= weight[i]; j--) \n\n dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]); \n\n \n\n \/*above line finds out maximum of dp[j](excluding ith element value) \n\n and val[i] + dp[j-wt[i]] (including ith element value and the \n\n profit with \"KnapSack capacity - ith element weight\") *\/\n\n return dp[maxWeight]; \n\n\t}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n\n\n\/\/ to return max sum of any subarray in given array\n\npublic static long kadanesAlgorithm(long[] arr)\n\n{\n\n \n\n if(arr.length == 0)return 0 ;\n\n \n\n long[] dp = new long[arr.length] ;\n\n \n\n dp[0] = arr[0] ;\n\n long max = dp[0] ;\n\n \n\n \n\n for(int i = 1; i < arr.length ; i++)\n\n {\n\n if(dp[i-1] > 0)\n\n {\n\n dp[i] = dp[i-1] + arr[i] ;\n\n }\n\n else{\n\n dp[i] = arr[i] ;\n\n }\n\n \n\n if(dp[i] > max)max = dp[i] ;\n\n \n\n }\n\n \n\n return max ;\n\n \n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\npublic static long kadanesAlgorithm(int[] arr)\n\n{\n\n if(arr.length == 0)return 0 ;\n\n \n\n long[] dp = new long[arr.length] ;\n\n \n\n dp[0] = arr[0] ;\n\n long max = dp[0] ;\n\n \n\n \n\n for(int i = 1; i < arr.length ; i++)\n\n {\n\n if(dp[i-1] > 0)\n\n {\n\n dp[i] = dp[i-1] + arr[i] ;\n\n }\n\n else{\n\n dp[i] = arr[i] ;\n\n }\n\n \n\n if(dp[i] > max)max = dp[i] ;\n\n \n\n }\n\n \n\n return max ;\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\/\/TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING\n\n\n\n\n\n\/\/ JUST CALL generatePermutation( str, start, end) start :inclusive ,end : exclusive \n\n\n\n\/\/Function for swapping the characters at position I with character at position j \n\n public static String swapString(String a, int i, int j) { \n\n char[] b =a.toCharArray(); \n\n char ch; \n\n ch = b[i]; \n\n b[i] = b[j]; \n\n b[j] = ch; \n\n return String.valueOf(b); \n\n } \n\n \n\n\/\/Function for generating different permutations of the string \n\n public static void generatePermutation(String str, int start, int end) \n\n { \n\n \/\/Prints the permutations \n\n if (start == end-1) \n\n System.out.println(str); \n\n else \n\n { \n\n for (int i = start; i < end; i++) \n\n { \n\n \/\/Swapping the string by fixing a character \n\n str = swapString(str,start,i); \n\n \/\/Recursively calling function generatePermutation() for rest of the characters \n\n generatePermutation(str,start+1,end); \n\n \/\/Backtracking and swapping the characters again. \n\n str = swapString(str,start,i); \n\n } \n\n } \n\n } \n\n\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\npublic static long factMod(long n, long mod) {\n\n if (n <= 1) return 1;\n\n long ans = 1;\n\n for (int i = 1; i <= n; i++) {\n\n ans = (ans * i) % mod;\n\n }\n\n return ans;\n\n }\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\npublic static long power(int a ,int b)\n\n {\n\n \/\/time comp : o(logn) \n\n \n\n long x = (long)(a) ;\n\n long n = (long)(b) ;\n\n \n\n if(n==0)return 1 ;\n\n if(n==1)return x;\n\n \n\n long ans =1L ;\n\n \n\n while(n>0)\n\n {\n\n if(n % 2 ==1)\n\n {\n\n ans = ans *x ;\n\n }\n\n \n\n n = n\/2L ;\n\n \n\n x = x*x ;\n\n \n\n }\n\n \n\n return ans ;\n\n }\n\n \n\n public static long power(long a ,long b)\n\n {\n\n \/\/time comp : o(logn) \n\n \n\n long x = (a) ;\n\n long n = (b) ;\n\n \n\n if(n==0)return 1L ;\n\n if(n==1)return x;\n\n \n\n long ans =1L ;\n\n \n\n while(n>0)\n\n {\n\n if(n % 2 ==1)\n\n {\n\n ans = ans *x ;\n\n }\n\n \n\n n = n\/2L ;\n\n \n\n x = x*x ;\n\n \n\n }\n\n \n\n return ans ;\n\n }\n\n\n\n \n\n \n\n \n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\npublic static long powerMod(long x, long n, long mod) {\n\n \/\/time comp : o(logn)\n\n \n\n if(n==0)return 1L ;\n\n if(n==1)return x;\n\n \n\n \n\n long ans = 1;\n\n while (n > 0) {\n\n if (n % 2 == 1) ans = (ans * x) % mod;\n\n x = (x * x) % mod;\n\n n \/= 2;\n\n }\n\n return ans;\n\n }\n\n \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n\/*\n\nlowerBound - finds largest element equal or less than value paased\n\nupperBound - finds smallest element equal or more than value passed\n\n\n\nif not present return -1;\n\n\n\n*\/\n\n\n\npublic static long lowerBound(long[] arr,long k)\n\n\t{\n\n\t\tlong ans=-1;\n\n\t\t\n\n\t\tint start=0;\n\n\t\tint end=arr.length-1;\n\n\t\t\n\n\t\twhile(start<=end)\n\n\t\t{\n\n\t\t\tint mid=(start+end)\/2;\n\n\t\t\t\n\n\t\t\tif(arr[mid]<=k)\n\n\t\t\t{\n\n\t\t\t\tans=arr[mid];\n\n\t\t\t\tstart=mid+1;\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tend=mid-1;\n\n\t\t\t}\n\n\t\t\t\n\n\t\t}\n\n\t\t\n\n\t\treturn ans;\n\n\t\t\n\n\t}\n\n\t\n\n\tpublic static int lowerBound(int[] arr,int k)\n\n\t{\n\n\t\tint ans=-1;\n\n\t\t\n\n\t\tint start=0;\n\n\t\tint end=arr.length-1;\n\n\t\t\n\n\t\twhile(start<=end)\n\n\t\t{\n\n\t\t\tint mid=(start+end)\/2;\n\n\t\t\t\n\n\t\t\tif(arr[mid]<=k)\n\n\t\t\t{\n\n\t\t\t\tans=arr[mid];\n\n\t\t\t\tstart=mid+1;\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tend=mid-1;\n\n\t\t\t}\n\n\t\t\t\n\n\t\t}\n\n\t\t\n\n\t\treturn ans;\n\n\t\t\n\n\t}\n\n\t\n\n\t\n\n\tpublic static long upperBound(long[] arr,long k)\n\n\t{\n\n\t\tlong ans=-1;\n\n\t\t\n\n\t\tint start=0;\n\n\t\tint end=arr.length-1;\n\n\t\t\n\n\t\twhile(start<=end)\n\n\t\t{\n\n\t\t\tint mid=(start+end)\/2;\n\n\t\t\t\n\n\t\t\tif(arr[mid]>=k)\n\n\t\t\t{\n\n\t\t\t\tans=arr[mid];\n\n\t\t\t\tend=mid-1;\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tstart=mid+1;\n\n\t\t\t}\n\n\t\t\t\n\n\t\t}\n\n\t\t\n\n\t\treturn ans;\n\n\t}\n\n\t\n\n\t\n\n\tpublic static int upperBound(int[] arr,int k)\n\n\t{\n\n\t\tint ans=-1;\n\n\t\t\n\n\t\tint start=0;\n\n\t\tint end=arr.length-1;\n\n\t\t\n\n\t\twhile(start<=end)\n\n\t\t{\n\n\t\t\tint mid=(start+end)\/2;\n\n\t\t\t\n\n\t\t\tif(arr[mid]>=k)\n\n\t\t\t{\n\n\t\t\t\tans=arr[mid];\n\n\t\t\t\tend=mid-1;\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tstart=mid+1;\n\n\t\t\t}\n\n\t\t\t\n\n\t\t}\n\n\t\t\n\n\t\treturn ans;\n\n\t}\n\n\t\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\npublic static void printArray(int[] arr , int si ,int ei)\n\n{\n\n for(int i = si ; i <= ei ; i++)\n\n {\n\n out.print(arr[i] +\" \") ;\n\n }\n\n \n\n}\n\n\n\npublic static void printArrayln(int[] arr , int si ,int ei)\n\n{\n\n for(int i = si ; i <= ei ; i++)\n\n {\n\n out.print(arr[i] +\" \") ;\n\n }\n\n out.println() ;\n\n}\n\n\n\n\n\npublic static void printLArray(long[] arr , int si , int ei)\n\n{\n\n for(int i = si ; i <= ei ; i++)\n\n {\n\n out.print(arr[i] +\" \") ;\n\n }\n\n \n\n}\n\n\n\n\n\n\n\n\n\npublic static void printLArrayln(long[] arr , int si , int ei)\n\n{\n\n for(int i = si ; i <= ei ; i++)\n\n {\n\n out.print(arr[i] +\" \") ;\n\n }\n\n out.println() ;\n\n \n\n}\n\n\n\npublic static void printtwodArray(int[][] ans)\n\n{\n\n for(int i = 0; i< ans.length ; i++)\n\n {\n\n for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +\" \");\n\n out.println() ;\n\n }\n\n out.println() ;\n\n \n\n}\n\n\n\n \n\n static long modPow(long a, long x, long p) {\n\n \/\/calculates a^x mod p in logarithmic time.\n\n \n\n a = a % p ;\n\n \n\n if(a == 0)return 0L ;\n\n \n\n \n\n long res = 1L;\n\n while(x > 0) {\n\n if( x % 2 != 0) {\n\n res = (res * a) % p;\n\n }\n\n a = (a * a) % p;\n\n x =x\/2;\n\n }\n\n return res;\n\n}\n\n \n\n \n\n \n\n static long modInverse(long a, long p) {\n\n \/\/calculates the modular multiplicative of a mod p.\n\n \/\/(assuming p is prime).\n\n return modPow(a, p-2, p);\n\n}\n\n \n\n static long[] factorial = new long[1000001] ;\n\n \n\n static void modfac(long mod)\n\n {\n\n factorial[0]=1L ; factorial[1]=1L ;\n\n \n\n for(int i = 2; i<= 1000000 ;i++)\n\n {\n\n factorial[i] = factorial[i-1] *(long)(i) ;\n\n factorial[i] = factorial[i] % mod ;\n\n }\n\n \n\n \n\n }\n\n \n\n\n\n \n\n \n\n \n\nstatic long modBinomial(long n, long r, long p) {\n\n\/\/ calculates C(n,r) mod p (assuming p is prime).\n\n \n\n if(n < r) return 0L ; \n\n \n\n long num = factorial[(int)(n)] ;\n\n \n\n long den = (factorial[(int)(r)]*factorial[(int)(n-r)]) % p ;\n\n \n\n \n\n long ans = num*(modInverse(den,p)) ;\n\n \n\n ans = ans % p ;\n\n \n\n return ans ;\n\n \n\n \n\n}\n\n \n\n \n\n static void update(int val , long[] bit ,int n)\n\n {\n\n for( ; val <= n ; val += (val &(-val)) )\n\n {\n\n bit[val]++ ;\n\n }\n\n \n\n \n\n }\n\n \n\n \n\n static long query(int val , long[] bit , int n)\n\n {\n\n long ans = 0L; \n\n for( ; val >=1 ; val-=(val&(-val)) )ans += bit[val];\n\n \n\n return ans ;\n\n }\n\n\n\n\n\n\n\nstatic int countSetBits(long n) \n\n { \n\n int count = 0; \n\n while (n > 0) { \n\n n = (n) & (n - 1L); \n\n count++; \n\n } \n\n return count; \n\n } \n\n\n\n\n\nstatic int abs(int x)\n\n{\n\n if(x < 0)x = -1*x ;\n\n \n\n return x ;\n\n}\n\n\n\n\n\nstatic long abs(long x)\n\n{\n\n if(x < 0)x = -1L*x ;\n\n \n\n return x ;\n\n\n\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void p(int val)\n\n{\n\n out.print(val) ;\n\n}\n\n\n\nstatic void p()\n\n{\n\n out.print(\" \") ;\n\n}\n\n\n\nstatic void pln(int val)\n\n{\n\n out.println(val) ;\n\n}\n\n\n\nstatic void pln()\n\n{\n\n out.println() ;\n\n}\n\n\n\n\n\nstatic void p(long val)\n\n{\n\n out.print(val) ;\n\n}\n\n\n\n\n\n\n\nstatic void pln(long val)\n\n{\n\n out.println(val) ;\n\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n \/\/ calculate total no of nos greater than or equal to key in sorted array arr\n\n \n\nstatic int bs(int[] arr, int s ,int e ,int key)\n\n{\n\n if( s> e)return 0 ;\n\n \n\n int mid = (s+e)\/2 ;\n\n \n\n if(arr[mid] [] adj ;\n\n\/\/ static int mod= 1000000007 ;\n\n\n\n\n\n \n\n\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\npublic static void solve()\n\n{\n\nFastReader scn = new FastReader() ;\n\n\n\n\/\/Scanner scn = new Scanner(System.in);\n\n\/\/int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ;\n\n\n\n\/\/ product of first 11 prime nos is greater than 10 ^ 12;\n\n\/\/sieve() ;\n\n\/\/ArrayList arr[] = new ArrayList[n] ;\n\nArrayList list = new ArrayList<>() ;\n\nArrayList lista = new ArrayList<>() ;\n\nArrayList listb = new ArrayList<>() ;\n\n\/\/ ArrayList lista = new ArrayList<>() ;\n\n\/\/ ArrayList listb = new ArrayList<>() ;\n\n\/\/ArrayList lists = new ArrayList<>() ;\n\n\n\nHashMap> map = new HashMap<>() ;\n\n\/\/HashMap map = new HashMap<>() ;\n\nHashMap mapx = new HashMap<>() ;\n\nHashMap mapy = new HashMap<>() ;\n\n\/\/HashMap maps = new HashMap<>() ;\n\n\/\/HashMap mapb = new HashMap<>() ;\n\n\/\/HashMap point = new HashMap<>() ; \n\n\n\n Set set = new HashSet<>() ;\n\n Set setx = new HashSet<>() ;\n\n Set sety = new HashSet<>() ;\n\n\n\nStringBuilder sb =new StringBuilder(\"\") ;\n\n\n\n\/\/Collections.sort(list);\n\n\n\n\/\/if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ;\n\n\/\/else map.put(arr[i],1) ;\n\n\n\n\/\/ if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ;\n\n\/\/ else map.put(temp,1) ;\n\n\n\n\/\/int bit =Integer.bitCount(n);\n\n\/\/ gives total no of set bits in n;\n\n\n\n\/\/ Arrays.sort(arr, new Comparator() {\n\n\/\/ \t\t\t@Override\n\n\/\/ \t\t\tpublic int compare(Pair a, Pair b) {\n\n\/\/ \t\t\t\tif (a.first != b.first) {\n\n\/\/ \t\t\t\t\treturn a.first - b.first; \/\/ for increasing order of first\n\n\/\/ \t\t\t\t}\n\n\/\/ \t\t\t\treturn a.second - b.second ; \/\/if first is same then sort on second basis\n\n\/\/ \t\t\t}\n\n\/\/ \t\t});\n\n\n\n\n\nint testcase = 1;\n\n \/\/testcase = scn.nextInt() ;\n\nfor(int testcases =1 ; testcases <= testcase ;testcases++)\n\n{\n\n \n\n \/\/if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ;\n\n \/\/if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ;\n\n \n\n \/\/adj = new ArrayList[n] ;\n\n\n\n\/\/ for(int i = 0; i< n; i++)\n\n\/\/ {\n\n\/\/ adj[i] = new ArrayList();\n\n\/\/ }\n\n\n\n\/\/ long n = scn.nextLong() ;\n\n\/\/String s = scn.next() ;\n\n\n\nint n= scn.nextInt() ;\n\nint[] arr= new int[n] ;\n\n\n\nfor(int i=0; i < n;i++)\n\n{\n\n arr[i]= scn.nextInt();\n\n}\n\n\n\nfor(int r= 0 ; r < n ;r++)\n\n{\n\n int sum = 0 ;\n\n for(int l =r ;l>= 0 ;l--)\n\n {\n\n sum = sum + arr[l] ;\n\n \n\n if(map.containsKey(sum))\n\n {\n\n map.get(sum).add(new Pair(l,r)) ;\n\n }\n\n else{\n\n \n\n map.put(sum,new ArrayList());\n\n map.get(sum).add(new Pair(l,r)) ;\n\n }\n\n }\n\n}\n\n\n\n\n\n ArrayList ans = null ;\n\n \n\n int bestcount = 0 ;\n\n\n\nfor(int x : map.keySet())\n\n{\n\n \n\n ArrayList curr = map.get(x) ;\n\n ArrayList now = new ArrayList() ;\n\n \n\n int r=-1 ;\n\n \n\n int count = 0 ;\n\n \n\n for(Pair seg : curr)\n\n {\n\n \n\n \n\n if(seg.first > r)\n\n {\n\n count++ ;\n\n now.add(seg) ;\n\n r= seg.second ;\n\n }\n\n \n\n \n\n }\n\n \n\n \n\n if(count > bestcount)\n\n {\n\n ans = now ;\n\n bestcount = count ;\n\n }\n\n \n\n \n\n}\n\n\n\n\n\npln(bestcount) ;\n\n\n\nif(bestcount >0)\n\n{\n\nfor(Pair x : ans)\n\n{\n\n out.println((x.first+1) +\" \" +( x.second+1)) ;\n\n}\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\/\/out.println(ans) ;\n\n\/\/out.println(ans+\" \"+in) ;\n\n\n\n\/\/out.println(\"Case #\" + testcases + \": \" + ans ) ;\n\n\/\/out.println(\"@\") ;\n\nset.clear() ;\n\nsb.delete(0 , sb.length()) ;\n\nlist.clear() ;lista.clear() ;listb.clear() ;\n\nmap.clear() ;\n\nmapx.clear() ;\n\nmapy.clear() ;\n\nsetx.clear() ;sety.clear() ;\n\n\n\n} \/\/ test case end loop\n\n\n\n\n\nout.flush() ; \n\n} \/\/ solve fn ends\n\n\n\n\n\npublic static void main (String[] args) throws java.lang.Exception\n\n{\n\n \n\n\n\nsolve() ;\n\n \n\n}\n\n\n\n\n\n}\n\n \n\n class Pair \n\n{\n\n int first ;\n\n \n\nint second ;\n\n \n\n \n\n \n\n public Pair(int l , int r)\n\n {\n\n first = l ;second = r ;\n\n }\n\n \n\n@Override\n\n\tpublic String toString() {\n\n\t\n\n\tString ans = \"\" ;\n\n\tans += this.first ;\n\n\tans += \" \";\n\n\tans += this.second ;\n\n\t\n\n\treturn ans ;\n\n\t}\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":"import java.io.*;\n\nimport java.util.*;\n\n\n\npublic class Main {\n\n static List[] g;\n\n static void bfs(int u, int[] dis) {\n\n dis[u] = 0;\n\n Queue q = new LinkedList<>();\n\n q.add(u);\n\n while(!q.isEmpty()) {\n\n int v = q.peek();\n\n q.remove();\n\n for(int w: g[v]) \n\n if(dis[w] > dis[v] + 1) {\n\n dis[w] = dis[v] + 1;\n\n q.add(w);\n\n }\n\n }\n\n }\n\n public static void main(String[] args) throws Exception {\n\n Scanner in = new Scanner(System.in);\n\n int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();\n\n g = new List[n];\n\n for(int i = 0; i < n; ++i)\n\n g[i] = new ArrayList();\n\n ArrayList a = new ArrayList<>();\n\n for(int i = 0; i < k; ++i)\n\n a.add(in.nextInt() - 1);\n\n for(int i = 0; i < m; ++i) {\n\n int u = in.nextInt() - 1, v = in.nextInt() - 1;\n\n g[u].add(v);\n\n g[v].add(u);\n\n }\n\n int[] d1 = new int[n];\n\n int[] dn = new int[n];\n\n Arrays.fill(d1, 100000000);\n\n Arrays.fill(dn, 100000000);\n\n bfs(0, d1);\n\n bfs(n - 1, dn);\n\n int best = 0, mx = -100000000;\n\n Collections.sort(a, new Comparator() {\n\n @Override public int compare(Integer b, Integer c) {\n\n return d1[b] - dn[b] - d1[c] + dn[c];\n\n } \n\n });\n\n for(int e: (List) a) {\n\n best = Math.max(best, mx + dn[e]);\n\n mx = Math.max(mx, d1[e]);\n\n }\n\n System.out.println(Math.min(best + 1, d1[n - 1]));\n\n }\n\n}","language":"java"} +{"contest_id":"1311","problem_id":"D","statement":"D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a\u2264b\u2264ca\u2264b\u2264c.In one move, you can add +1+1 or \u22121\u22121 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A\u2264B\u2264CA\u2264B\u2264C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1\u2264a\u2264b\u2264c\u22641041\u2264a\u2264b\u2264c\u2264104).OutputFor each test case, print the answer. In the first line print resres \u2014 the minimum number of operations you have to perform to obtain three integers A\u2264B\u2264CA\u2264B\u2264C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8\n1 2 3\n123 321 456\n5 10 15\n15 18 21\n100 100 101\n1 22 29\n3 19 38\n6 30 46\nOutputCopy1\n1 1 3\n102\n114 228 456\n4\n4 8 16\n6\n18 18 18\n1\n100 100 100\n7\n1 22 22\n2\n1 19 38\n8\n6 24 48\n","tags":["brute force","math"],"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\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 = 20000, INF = (int) 1e9;\n\n static List list = new ArrayList<>();\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 precompute();\n\n\n\n int test = sc.nextInt();\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 precompute() {\n\n for (int i = 1; i <= MAX; i++) {\n\n for (int j = i; j <= MAX; j += i) {\n\n for (int k = j; k <= MAX; k += j) {\n\n list.add(new int[]{i, j, k});\n\n }\n\n }\n\n }\n\n }\n\n\n\n private static void solve() {\n\n int a = sc.nextInt();\n\n int b = sc.nextInt();\n\n int c = sc.nextInt();\n\n\n\n int[] res = new int[]{0, 0, 0};\n\n int minOperations = INF;\n\n for (int i = 0; i < list.size(); i++) {\n\n int[] curr = list.get(i);\n\n int operations = Math.abs(curr[0] - a) + Math.abs(curr[1] - b) + Math.abs(curr[2] - c);\n\n if (minOperations > operations) {\n\n minOperations = operations;\n\n res = curr;\n\n }\n\n }\n\n\n\n out.println(minOperations);\n\n out.println(res[0] + \" \" + res[1] + \" \" + res[2]);\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":"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;\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.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.StringTokenizer;\n\npublic class C1316D {\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 target = new int[n + 1][n + 1];\n var blocks = new ArrayList();\n var starts = new HashMap>();\n for (int x = 1; x <= n; x++) {\n for (int y = 1; y <= n; y++) {\n var h = hash(n, x, y);\n var x1 = scanner.nextInt();\n var y1 = scanner.nextInt();\n int h1 = hash(n, x1, y1);\n target[x][y] = h1;\n if (x == x1 && y == y1) {\n blocks.add(h1);\n } else if (x1 >= 1) {\n starts.compute(h1, (k, v) -> {\n if (v == null) {\n v = new ArrayList<>();\n }\n v.add(h);\n return v;\n });\n }\n }\n }\n var ans = new char[n + 1][n + 1];\n var valid = true;\n \/\/ \u6700\u8d77\u7801\uff0c\u6240\u6709starts\u7684\u7ec8\u70b9\u7684\u7ec8\u70b9\u90fd\u662f\u81ea\u5df1\n for (Integer t : starts.keySet()) {\n if (t < 0) {\n valid = false;\n break;\n }\n var xy = dehash(t, n);\n if (target[xy[0]][xy[1]] != t) {\n valid = false;\n break;\n }\n }\n if (!valid) {\n writer.println(\"INVALID\");\n } else {\n \/\/ \u9996\u5148\uff0c\u6240\u6709\u7684blocks\u8981\u80fd\u591f\u8d70\u5230\u5230\u81ea\u5df1\u7684\u6240\u6709\u51fa\u53d1\u70b9\u3002\n for (Integer block : blocks) {\n bfs(block, ans, n, target);\n if (!allStartsReach(block, starts, ans, n)) {\n valid = false;\n break;\n }\n }\n if (!valid) {\n writer.println(\"INVALID\");\n } else {\n \/\/ \u5176\u6b21\u6240\u6709\u7684(-1,-1)\u4e0d\u80fd\u662f\u5b64\u7acb\u7684\u3002\n if (!fillInfinite(ans, n)) {\n writer.println(\"INVALID\");\n } else {\n writer.println(\"VALID\");\n for (int x = 1; x <= n; x++) {\n writer.println(Arrays.copyOfRange(ans[x], 1, n + 1));\n }\n }\n }\n }\n\n scanner.close();\n writer.flush();\n writer.close();\n }\n\n private static boolean fillInfinite(char[][] ans, int n) {\n for (int x = 1; x <= n; x++) {\n for (int y = 1; y <= n; y++) {\n if (ans[x][y] == 0) {\n var q = new LinkedList();\n q.add(new int[]{x, y});\n {\n for (int i = 0; i < 4; i++) {\n var x1 = x + dx[i];\n var y1 = y + dy[i];\n if (1 <= x1 && x1 <= n && 1 <= y1 && y1 <= n && ans[x1][y1] == 0) {\n q.add(new int[]{x1, y1});\n ans[x][y] = dn[i];\n ans[x1][y1] = dn[3 - i];\n break;\n }\n }\n }\n if (q.size() < 2) {\n return false;\n }\n while (!q.isEmpty()) {\n var xy = q.poll();\n for (int i = 0; i < 4; i++) {\n var x1 = xy[0] + dx[i];\n var y1 = xy[1] + dy[i];\n if (1 <= x1 && x1 <= n && 1 <= y1 && y1 <= n && ans[x1][y1] == 0) {\n ans[x1][y1] = dn[3 - i];\n q.add(new int[]{x1, y1});\n }\n }\n }\n }\n }\n }\n return true;\n }\n\n private static boolean allStartsReach(Integer block, HashMap> starts, char[][] ans, int n) {\n List ss = starts.get(block);\n if (ss == null) {\n return true;\n }\n for (Integer start : ss) {\n var xy = dehash(start, n);\n if (ans[xy[0]][xy[1]] == 0) {\n return false;\n }\n }\n return true;\n }\n\n static int[] dx = new int[]{1, 0, 0, -1};\n static int[] dy = new int[]{0, 1, -1, 0};\n static char[] dn = new char[]{'D', 'R', 'L', 'U'};\n\n private static void bfs(int block, char[][] ans, int n, int[][] target) {\n var q = new LinkedList();\n {\n var xy = dehash(block, n);\n ans[xy[0]][xy[1]] = 'X';\n q.add(xy);\n }\n while (!q.isEmpty()) {\n var xy = q.poll();\n for (int i = 0; i < 4; i++) {\n var x1 = xy[0] + dx[i];\n var y1 = xy[1] + dy[i];\n if (1 <= x1 && x1 <= n && 1 <= y1 && y1 <= n && target[x1][y1] == block && ans[x1][y1] == 0) {\n ans[x1][y1] = dn[3 - i];\n q.add(new int[]{x1, y1});\n }\n }\n }\n }\n\n private static int[] dehash(int block, int n) {\n return new int[]{block \/ (n + 1), block % (n + 1)};\n }\n\n private static int hash(int n, int x, int y) {\n return x * (n + 1) + y;\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":"import java.io.*;\n\nimport java.util.*;\n\npublic class Main {\n\n\tpublic static void main(String[] args) throws IOException \n\n\t{ \n\n\t\tFastScanner f = new FastScanner(); \n\n\t\tint ttt=1;\n\n\t\tttt=f.nextInt();\n\n\t\tPrintWriter out=new PrintWriter(System.out);\n\n\t\tfor(int tt=0;tt')\n\n\t\t\t\t{\n\n\t\t\t\t\tfor (int j = i; j >= last; j--)\n\n\t\t\t\t\t\tans[j] = num--;\n\n\t\t\t\t\tlast = i + 1;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tfor (int i:ans) out.print(i+\" \");\n\n\t\t\tout.println();\n\n\t\t\tans=new int[n];\n\n\t\t\tnum = 1;\n\n\t\t\tlast = 0;\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t{\n\n\t\t\t\tif (i == n - 1 || l[i] == '<')\n\n\t\t\t\t{\n\n\t\t\t\t\tfor (int j = i; j >= last; j--)\n\n\t\t\t\t\t\tans[j] = num++;\n\n\t\t\t\t\tlast = i + 1;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tfor (int i:ans) out.print(i+\" \");\n\n\t\t\tout.println();\n\n\t\t}\n\n\t\tout.close();\n\n\t} \n\n\tstatic void sort(int[] p) {\n\n ArrayList q = new ArrayList<>();\n\n for (int i: p) q.add( i);\n\n Collections.sort(q);\n\n for (int i = 0; i < p.length; i++) p[i] = q.get(i);\n\n }\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\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\t\t\n\n\t\tint nextInt() {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\t\tint[] readArray(int n) {\n\n\t\t\tint[] a=new int[n];\n\n\t\t\tfor (int i=0; i j + 1;--k) {\n if (items[j].equals(items[k])) {\n found = true;\n break;\n }\n }\n if (found) {\n sb.append(\"YES\").append(\"\\n\");\n break;\n } else {\n ++j;\n }\n }\n if (!found) sb.append(\"NO\").append(\"\\n\");\n }\n System.out.print(sb.substring(0, sb.length() - 1));\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 {\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 string 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\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\tStringBuilder sb = new StringBuilder();\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 m=sc.nextInt();\n\n\t\t\tlong arr[]=new long[n];\n\n\t\t\tlong brr[]=new long[m];\n\n\t\t\tfor(int i=0;i x=new ArrayList();\n\n\t\t\tArrays.sort(brr);\n\n\t\t\tfor(int i=0;ii1)\n\n\t\t\t\t{\n\n\t\t\t\t\tlong crr[]=Arrays.copyOfRange(arr,i1, i2+1);\n\n\t\t\t\t\tArrays.sort(crr);\n\n\t\t\t\t\tint k=0;\n\n\t\t\t\t\tfor(int i3=i1;i3<=i2;i3++)\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\tarr[i3]=crr[k];\n\n\t\t\t\t\t\tk++;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\telse\n\n\t\t\t\t{\n\n\t\t\t\t\tlong a=Math.max(arr[i1],arr[i1+1]);\n\n\t\t\t\t\tlong b=Math.min(arr[i1],arr[i1+1]);\n\n\t\t\t\t\tarr[i1+1]=a;\n\n\t\t\t\t\tarr[i1]=b;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tlong crr[]=Arrays.copyOf(arr, n);\n\n\t\t\tArrays.sort(crr);\n\n\t\t\tif(Arrays.equals(arr,crr))\n\n\t\t\t{\n\n\t\t\t\tout.println(\"YES\");\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tout.println(\"NO\");\n\n\t\t\t}\n\n\t\t}\n\n\t\tout.close();\n\n\t}\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 buf[ptr++] = (byte) c;\n\n if (ptr == BUF_SIZE) innerflush();\n\n });\n\n return this;\n\n }\n\n\n\n private static int countDigits(int l) {\n\n if (l >= 1000000000) return 10;\n\n if (l >= 100000000) return 9;\n\n if (l >= 10000000) return 8;\n\n if (l >= 1000000) return 7;\n\n if (l >= 100000) return 6;\n\n if (l >= 10000) return 5;\n\n if (l >= 1000) return 4;\n\n if (l >= 100) return 3;\n\n if (l >= 10) return 2;\n\n return 1;\n\n }\n\n\n\n public FastWriter write(int x) {\n\n if (x == Integer.MIN_VALUE) {\n\n return write((long) x);\n\n }\n\n if (ptr + 12 >= BUF_SIZE) innerflush();\n\n if (x < 0) {\n\n write((byte) '-');\n\n x = -x;\n\n }\n\n int d = countDigits(x);\n\n for (int i = ptr + d - 1; i >= ptr; i--) {\n\n buf[i] = (byte) ('0' + x % 10);\n\n x \/= 10;\n\n }\n\n ptr += d;\n\n return this;\n\n }\n\n\n\n private static int countDigits(long l) {\n\n if (l >= 1000000000000000000L) return 19;\n\n if (l >= 100000000000000000L) return 18;\n\n if (l >= 10000000000000000L) return 17;\n\n if (l >= 1000000000000000L) return 16;\n\n if (l >= 100000000000000L) return 15;\n\n if (l >= 10000000000000L) return 14;\n\n if (l >= 1000000000000L) return 13;\n\n if (l >= 100000000000L) return 12;\n\n if (l >= 10000000000L) return 11;\n\n if (l >= 1000000000L) return 10;\n\n if (l >= 100000000L) return 9;\n\n if (l >= 10000000L) return 8;\n\n if (l >= 1000000L) return 7;\n\n if (l >= 100000L) return 6;\n\n if (l >= 10000L) return 5;\n\n if (l >= 1000L) return 4;\n\n if (l >= 100L) return 3;\n\n if (l >= 10L) return 2;\n\n return 1;\n\n }\n\n\n\n public FastWriter write(long x) {\n\n if (x == Long.MIN_VALUE) {\n\n return write(\"\" + x);\n\n }\n\n if (ptr + 21 >= BUF_SIZE) innerflush();\n\n if (x < 0) {\n\n write((byte) '-');\n\n x = -x;\n\n }\n\n int d = countDigits(x);\n\n for (int i = ptr + d - 1; i >= ptr; i--) {\n\n buf[i] = (byte) ('0' + x % 10);\n\n x \/= 10;\n\n }\n\n ptr += d;\n\n return this;\n\n }\n\n\n\n public FastWriter write(double x, int precision) {\n\n if (x < 0) {\n\n write('-');\n\n x = -x;\n\n }\n\n x += Math.pow(10, -precision) \/ 2;\n\n \/\/\t\tif(x < 0){ x = 0; }\n\n write((long) x).write(\".\");\n\n x -= (long) x;\n\n for (int i = 0; i < precision; i++) {\n\n x *= 10;\n\n write((char) ('0' + (int) x));\n\n x -= (int) x;\n\n }\n\n return this;\n\n }\n\n\n\n public FastWriter writeln(char c) {\n\n return write(c).writeln();\n\n }\n\n\n\n public FastWriter writeln(int x) {\n\n return write(x).writeln();\n\n }\n\n\n\n public FastWriter writeln(long x) {\n\n return write(x).writeln();\n\n }\n\n\n\n public FastWriter writeln(double x, int precision) {\n\n return write(x, precision).writeln();\n\n }\n\n\n\n public FastWriter write(int... xs) {\n\n boolean first = true;\n\n for (int x : xs) {\n\n if (!first) write(' ');\n\n first = false;\n\n write(x);\n\n }\n\n return this;\n\n }\n\n\n\n public FastWriter write(long... xs) {\n\n boolean first = true;\n\n for (long x : xs) {\n\n if (!first) write(' ');\n\n first = false;\n\n write(x);\n\n }\n\n return this;\n\n }\n\n\n\n public FastWriter writeln() {\n\n return write((byte) '\\n');\n\n }\n\n\n\n public FastWriter writeln(int... xs) {\n\n return write(xs).writeln();\n\n }\n\n\n\n public FastWriter writeln(long... xs) {\n\n return write(xs).writeln();\n\n }\n\n\n\n public FastWriter writeln(char[] line) {\n\n return write(line).writeln();\n\n }\n\n\n\n public FastWriter writeln(char[]... map) {\n\n for (char[] line : map) write(line).writeln();\n\n return this;\n\n }\n\n\n\n public FastWriter writeln(String s) {\n\n return write(s).writeln();\n\n }\n\n\n\n private void innerflush() {\n\n try {\n\n out.write(buf, 0, ptr);\n\n ptr = 0;\n\n } catch (IOException e) {\n\n throw new RuntimeException(\"innerflush\");\n\n }\n\n }\n\n\n\n public void flush() {\n\n innerflush();\n\n try {\n\n out.flush();\n\n } catch (IOException e) {\n\n throw new RuntimeException(\"flush\");\n\n }\n\n }\n\n\n\n public FastWriter print(byte b) {\n\n return write(b);\n\n }\n\n\n\n public FastWriter print(char c) {\n\n return write(c);\n\n }\n\n\n\n public FastWriter print(char[] s) {\n\n return write(s);\n\n }\n\n\n\n public FastWriter print(String s) {\n\n return write(s);\n\n }\n\n\n\n public FastWriter print(int x) {\n\n return write(x);\n\n }\n\n\n\n public FastWriter print(long x) {\n\n return write(x);\n\n }\n\n\n\n public FastWriter print(double x, int precision) {\n\n return write(x, precision);\n\n }\n\n\n\n public FastWriter println(char c) {\n\n return writeln(c);\n\n }\n\n\n\n public FastWriter println(int x) {\n\n return writeln(x);\n\n }\n\n\n\n public FastWriter println(long x) {\n\n return writeln(x);\n\n }\n\n\n\n public FastWriter println(double x, int precision) {\n\n return writeln(x, precision);\n\n }\n\n\n\n public FastWriter print(int... xs) {\n\n return write(xs);\n\n }\n\n\n\n public FastWriter print(long... xs) {\n\n return write(xs);\n\n }\n\n\n\n public FastWriter println(int... xs) {\n\n return writeln(xs);\n\n }\n\n\n\n public FastWriter println(long... xs) {\n\n return writeln(xs);\n\n }\n\n\n\n public FastWriter println(char[] line) {\n\n return writeln(line);\n\n }\n\n\n\n public FastWriter println(char[]... map) {\n\n return writeln(map);\n\n }\n\n\n\n public FastWriter println(String s) {\n\n return writeln(s);\n\n }\n\n\n\n public FastWriter println() {\n\n return writeln();\n\n }\n\n }\n\n\n\n\n\n static final class InputReader {\n\n private final InputStream stream;\n\n private final byte[] buf = new byte[1024];\n\n private int curChar;\n\n private int numChars;\n\n\n\n public InputReader(InputStream stream) {\n\n this.stream = stream;\n\n }\n\n\n\n private int read() throws IOException {\n\n if (curChar >= numChars) {\n\n curChar = 0;\n\n numChars = stream.read(buf);\n\n if (numChars <= 0) {\n\n return -1;\n\n }\n\n }\n\n return buf[curChar++];\n\n }\n\n\n\n public final int readInt() throws IOException {\n\n return (int) readLong();\n\n }\n\n\n\n public final long readLong() throws IOException {\n\n int c = read();\n\n while (isSpaceChar(c)) {\n\n c = read();\n\n if (c == -1) throw new IOException();\n\n }\n\n boolean negative = false;\n\n if (c == '-') {\n\n negative = true;\n\n c = read();\n\n }\n\n long res = 0;\n\n do {\n\n res *= 10;\n\n res += c - '0';\n\n c = read();\n\n } while (!isSpaceChar(c));\n\n return negative ? -res : res;\n\n }\n\n\n\n public final int[] readIntArray(int size) throws IOException {\n\n int[] array = new int[size];\n\n for (int i = 0; i < size; i++) {\n\n array[i] = readInt();\n\n }\n\n return array;\n\n }\n\n\n\n public final long[] readLongArray(int size) throws IOException {\n\n long[] array = new long[size];\n\n for (int i = 0; i < size; i++) {\n\n array[i] = readLong();\n\n }\n\n return array;\n\n }\n\n\n\n public final String readString() throws IOException {\n\n int c = read();\n\n while (isSpaceChar(c)) {\n\n c = read();\n\n }\n\n StringBuilder res = new StringBuilder();\n\n do {\n\n res.append((char) c);\n\n c = read();\n\n } while (!isSpaceChar(c));\n\n return res.toString();\n\n }\n\n\n\n private boolean isSpaceChar(int c) {\n\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n\n }\n\n }\n\n\n\n static long mulmod(long a, long b,\n\n long mod) {\n\n long res = 0; \/\/ Initialize result\n\n a = a % mod;\n\n while (b > 0) {\n\n \/\/ If b is odd, add 'a' to result\n\n if (b % 2 == 1) {\n\n res = (res + a) % mod;\n\n }\n\n\n\n \/\/ Multiply 'a' with 2\n\n a = (a * 2) % mod;\n\n\n\n \/\/ Divide b by 2\n\n b \/= 2;\n\n }\n\n\n\n \/\/ Return result\n\n return res % mod;\n\n }\n\n\n\n static long pow(long a, long b, long MOD) {\n\n long x = 1, y = a;\n\n while (b > 0) {\n\n if (b % 2 == 1) {\n\n x = (x * y);\n\n if (x > MOD) x %= MOD;\n\n }\n\n y = (y * y);\n\n if (y > MOD) y %= MOD;\n\n b \/= 2;\n\n }\n\n return x;\n\n }\n\n\n\n static long[] f = new long[200001];\n\n\n\n static long InverseEuler(long n, long MOD) {\n\n return pow(n, MOD - 2, MOD);\n\n }\n\n\n\n static long C(int n, int r, long MOD) {\n\n\n\n return (f[n] * ((InverseEuler(f[r], MOD) * InverseEuler(f[n - r], MOD)) % MOD)) % MOD;\n\n }\n\n\n\n\n\n static int[] h = {0, 0, -1, 1};\n\n static int[] v = {1, -1, 0, 0};\n\n\n\n\n\n public static class Pair {\n\n public int a;\n\n\n\n public int b;\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 a == pair.a &&\n\n b == pair.b;\n\n }\n\n\n\n @Override\n\n public int hashCode() {\n\n return Objects.hash(a, b);\n\n }\n\n\n\n public Pair(int a, int b) {\n\n this.a = a;\n\n this.b = b;\n\n }\n\n }\n\n\n\n static class Pair2 {\n\n public long cost;\n\n int node;\n\n\n\n public Pair2(long cos, int node) {\n\n this.cost = cos;\n\n this.node = node;\n\n }\n\n }\n\n\n\n static long compute_hash(String s) {\n\n int p = 31;\n\n int m = 1000000007;\n\n long hash_value = 0;\n\n long p_pow = 1;\n\n for (int i = 0; i < s.length(); ++i) {\n\n char c = s.charAt(i);\n\n hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;\n\n p_pow = (p_pow * p) % m;\n\n }\n\n return hash_value;\n\n }\n\n\n\n public static class SegmentTree {\n\n long[][] tree;\n\n int n;\n\n\n\n public SegmentTree(int[] nodes) {\n\n tree = new long[nodes.length * 4][2];\n\n n = nodes.length;\n\n build(0, n - 1, 0, nodes);\n\n\n\n }\n\n\n\n private void build(int l, int r, int pos, int[] nodes) {\n\n if (l == r) {\n\n tree[pos][0] = nodes[l];\n\n tree[pos][1] = l;\n\n return;\n\n }\n\n int mid = (l + r) \/ 2;\n\n build(l, mid, 2 * pos + 1, nodes);\n\n build(mid + 1, r, 2 * pos + 2, nodes);\n\n if (tree[2 * pos + 1][0] > tree[2 * pos + 2][0]) {\n\n tree[pos][1] = tree[2 * pos + 1][1];\n\n } else {\n\n tree[pos][1] = tree[2 * pos + 2][1];\n\n }\n\n tree[pos][0] = Math.max(tree[2 * pos + 1][0], tree[2 * pos + 2][0]);\n\n }\n\n\n\n \/\/ public void update(int pos, int val) {\n\n \/\/ updateUtil(0, n - 1, 0, pos, val);\n\n \/\/ }\n\n\n\n public long[] get(int l, int r) {\n\n return getUtil(0, n - 1, 0, l, r);\n\n }\n\n\n\n private long[] getUtil(int l, int r, int pos, int ql, int qr) {\n\n if (ql > r || qr < l) {\n\n return new long[]{-1, -1};\n\n }\n\n if (l >= ql && r <= qr) {\n\n return tree[pos];\n\n }\n\n\n\n int mid = (l + r) \/ 2;\n\n long[] left = getUtil(l, mid, 2 * pos + 1, ql, qr);\n\n long[] right = getUtil(mid + 1, r, 2 * pos + 2, ql, qr);\n\n long choice = right[1];\n\n if (left[0] > right[0]) choice = left[1];\n\n return new long[]{Math.max(left[0], right[0]), choice};\n\n\n\n }\n\n\n\n \/\/ private void updateUtil(int l, int r, int pos, int i, int val) {\n\n \/\/ if (i < l || i > r) {\n\n \/\/ return;\n\n \/\/ }\n\n \/\/ if (l == r) {\n\n \/\/ tree[pos] = val;\n\n \/\/ return;\n\n \/\/ }\n\n \/\/ int mid = (l + r) \/ 2;\n\n \/\/ updateUtil(l, mid, 2 * pos + 1, i, val);\n\n \/\/ updateUtil(mid + 1, r, 2 * pos + 2, i, val);\n\n \/\/ tree[pos] = tree[2 * pos + 1] + tree[2 * pos + 2];\n\n \/\/ }\n\n }\n\n\n\n static int counter = 0;\n\n static int[] rIn;\n\n static int[] rOut;\n\n static int[] lIn;\n\n static int[] lOut;\n\n private static int[] flatten;\n\n private static int[] lFlatten;\n\n static long answer = 0;\n\n\n\n static int VISITED = 1;\n\n static int VISITING = 2;\n\n\n\n static int[] DIRX = new int[]{0, 0, 1, -1};\n\n static int[] DIRY = new int[]{1, -1, 0, 0};\n\n\n\n public static class Pair22 {\n\n int num, pos;\n\n\n\n public Pair22(int x, int y) {\n\n this.num = x;\n\n this.pos = y;\n\n }\n\n }\n\n\n\n public static long sumofdig(long n) {\n\n long sum = 0;\n\n while (n > 0) {\n\n sum += n % 10;\n\n n \/= 10;\n\n }\n\n return sum;\n\n }\n\n\n\n public static class DK {\n\n int D, K;\n\n\n\n public DK(int d, int k) {\n\n D = d;\n\n K = k;\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 DK dk = (DK) o;\n\n return D == dk.D &&\n\n K == dk.K;\n\n }\n\n\n\n @Override\n\n public int hashCode() {\n\n return Objects.hash(D, K);\n\n }\n\n }\n\n\n\n public static void main(String[] args) throws Exception {\n\n \/\/https:\/\/i...content-available-to-author-only...e.com\/ebRGa6\n\n InputReader in = new InputReader(System.in);\n\n\n\n\n\n FastWriter out = new FastWriter(System.out);\n\n\n\n\n\n\/\/\n\n\/\/ f[0] = 1;\n\n\/\/ f[1] = 1;\n\n\/\/ for (int i = 2; i < 200001; ++i) {\n\n\/\/ f[i] = f[i-1] * i;\n\n\/\/ f[i] %= 100000000000000007L;\n\n\/\/ }\n\n int t = 1;\n\n\n\n while (t-- > 0) {\n\n\n\n int n = in.readInt();\n\n\n\n List> g = new ArrayList<>();\n\n for (int i = 0; i < n; ++i) g.add(new ArrayList<>());\n\n\n\n int[] cost = new int[n];\n\n\n\n int parent = 0;\n\n\n\n for (int i = 0; i < n; ++i) {\n\n int from = i;\n\n int to = in.readInt();\n\n cost[i] = in.readInt();\n\n to--;\n\n if (to != -1) {\n\n g.get(from).add(to);\n\n g.get(to).add(from);\n\n } else {\n\n parent = i;\n\n }\n\n\n\n }\n\n\n\n List val = dfs(g, parent, -1, cost);\n\n if (val.size() != n) {\n\n System.out.println(\"NO\");\n\n } else {\n\n\n\n System.out.println(\"YES\");\n\n int[] ans = new int[n];\n\n for (int i = 0; i < n; ++i) {\n\n ans[val.get(i)] = i + 1;\n\n }\n\n for (int i = 0; i < n; ++i) {\n\n out.print(ans[i] + \" \");\n\n }\n\n }\n\n out.flush();\n\n\n\n\n\n }\n\n\n\n }\n\n\n\n private static List dfs(List> g, int cur, int last, int[] cost) {\n\n List nodes = new ArrayList<>();\n\n\n\n for (int i = 0; i < g.get(cur).size(); ++i) {\n\n int ntb = g.get(cur).get(i);\n\n\n\n if (ntb != last) {\n\n nodes.addAll(dfs(g, ntb, cur, cost));\n\n }\n\n }\n\n List ans = new ArrayList<>();\n\n\n\n for (int i = 0; i < nodes.size(); i++) {\n\n if (cost[cur] == i) {\n\n ans.add(cur);\n\n ans.add(nodes.get(i));\n\n } else {\n\n ans.add(nodes.get(i));\n\n }\n\n }\n\n if (cost[cur] == nodes.size()) {\n\n ans.add(cur);\n\n }\n\n if (cost[cur] > nodes.size()) {\n\n return new ArrayList<>();\n\n }\n\n return ans;\n\n }\n\n\n\n\/\/ private static Pair22 dfss(List> g, int node, HashSet vis, int[] dis, int[] dis2) {\n\n\/\/ if (vis.contains(node)) return new Pair22(dis[node], dis2[node], -1);\n\n\/\/ vis.add(node);\n\n\/\/ int min = dis[node];\n\n\/\/ for (Integer ntb : g.get(node)) {\n\n\/\/ if (dis[ntb] > dis[node])\n\n\/\/ dfss(g, ntb, vis, dis, dis2);\n\n\/\/ if (dis[ntb] <= dis[node]) {\n\n\/\/ min = Math.min(min, dis[ntb]);\n\n\/\/ } else {\n\n\/\/ min = Math.min(min, dis2[ntb]);\n\n\/\/ }\n\n\/\/ }\n\n\/\/ \/\/ if (dis)\n\n\/\/ dis2[node] = min;\n\n\/\/ return new Pair22(dis[node], min, -1);\n\n\/\/ }\n\n\n\n private static int solver(int[] nums, int pos, int[] dp) {\n\n if (pos >= nums.length) return 0;\n\n if (dp[pos] != Integer.MAX_VALUE) return dp[pos];\n\n int min = solver(nums, pos + 2, dp) + nums[pos];\n\n min = Math.min(solver(nums, pos + 3, dp) + nums[pos], min);\n\n if (pos + 1 < nums.length) min = Math.min(min, nums[pos] + nums[pos + 1] + solver(nums, pos + 3, dp));\n\n if (pos + 1 < nums.length) min = Math.min(min, nums[pos] + nums[pos + 1] + solver(nums, pos + 4, dp));\n\n\n\n \/\/ System.out.println(pos + \" \" + min);\n\n return dp[pos] = min;\n\n }\n\n\n\n\n\n static int countFreq(String pattern, String text) {\n\n int m = pattern.length();\n\n int n = text.length();\n\n int res = 0;\n\n\n\n for (int i = 0; i <= n - m; i++) {\n\n int j;\n\n for (j = 0; j < m; j++) {\n\n if (text.charAt(i + j) != pattern.charAt(j)) {\n\n break;\n\n }\n\n }\n\n if (j == m) {\n\n res++;\n\n j = 0;\n\n }\n\n }\n\n return res;\n\n }\n\n\n\n private static void dfsR(List> g, int node, int[] v) {\n\n rIn[node] = counter;\n\n flatten[counter++] = v[node];\n\n\n\n for (int i = 0; i < g.get(node).size(); ++i) {\n\n dfsR(g, g.get(node).get(i), v);\n\n }\n\n\n\n rOut[node] = counter;\n\n flatten[counter++] = v[node] * -1;\n\n }\n\n\n\n private static void dfsL(List> g, int node, int[] v) {\n\n lIn[node] = counter;\n\n lFlatten[counter++] = v[node];\n\n\n\n for (int i = 0; i < g.get(node).size(); ++i) {\n\n dfsL(g, g.get(node).get(i), v);\n\n }\n\n\n\n lOut[node] = counter;\n\n lFlatten[counter++] = v[node] * -1;\n\n\n\n TreeMap map = new TreeMap<>();\n\n }\n\n\n\n\n\n private static void preprocess(int pos, int[][] pre, List> tree, int[] traverse, int depth, int last, int[] tin, int[] tout) {\n\n tin[pos] = counter++;\n\n traverse[depth] = pos;\n\n\n\n for (int i = 0; depth - (1 << i) >= 0; ++i) {\n\n pre[pos][i] = traverse[depth - (1 << i)];\n\n }\n\n\n\n for (int i = 0; i < tree.get(pos).size(); ++i) {\n\n if (tree.get(pos).get(i) != last)\n\n preprocess(tree.get(pos).get(i), pre, tree, traverse, depth + 1, pos, tin, tout);\n\n }\n\n tout[pos] = counter++;\n\n }\n\n\n\n static long gcd(long a, long b) {\n\n\n\n while (b != 0) {\n\n long t = a;\n\n a = b;\n\n b = t % b;\n\n }\n\n return a;\n\n }\n\n\n\n static long lcm(long a, long b) {\n\n\n\n return a * b \/ gcd(a, b);\n\n }\n\n\n\n\n\n static boolean submit = true;\n\n\n\n static void debug(String s) {\n\n if (!submit)\n\n System.out.println(s);\n\n }\n\n\n\n static void debug(int s) {\n\n LinkedHashSet exist = new LinkedHashSet<>();\n\n \/*\n\n\n\n 4 2 3 _ 2 4 3 _\n\n *\/\n\n }\n\n\n\n\n\n\n\n\n\n\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.*;\n\nimport java.util.*;\n\n\n\npublic class Main {\n\n\tstatic Scanner sc = new Scanner(System.in);\n\n\tstatic PrintWriter out = new PrintWriter(System.out);\n\n\tstatic int n, grid[][], dx[], dy[];\n\n\tstatic Pair adj[][];\n\n\n\n\tstatic boolean valid(int r, int c) {\n\n\t\treturn r >= 0 && r < n && c >= 0 && c < n;\n\n\t}\n\n\n\n\tstatic boolean dfs(int r, int c) {\n\n\t\tfor (int i = 0; i < 4; i++) {\n\n\t\t\tint nr = r + dx[i], nc = c + dy[i];\n\n\t\t\tif (valid(nr, nc) && adj[nr][nc].r == -2) {\n\n\t\t\t\tgrid[r][c] = i;\n\n\t\t\t\treturn true;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn false;\n\n\t}\n\n\n\n\tstatic void dfs2(int r, int c) {\n\n\t\tfor (int i = 0; i < 4; i++) {\n\n\t\t\tint nr = r + dx[i], nc = c + dy[i];\n\n\t\t\tif (valid(nr, nc) && grid[nr][nc] == -1) {\n\n\t\t\t\tif (adj[nr][nc].r == adj[r][c].r && adj[nr][nc].c == adj[r][c].c) {\n\n\t\t\t\t\tgrid[nr][nc] = (i + 2) % 4;\n\n\t\t\t\t\tdfs2(nr, nc);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\tstatic void bfs(Pair p) {\n\n\t\tQueue q = new LinkedList<>();\n\n\t\tq.add(p);\n\n\t\twhile (!q.isEmpty()) {\n\n\t\t\tPair u = q.poll();\n\n\t\t\tfor (int i = 0; i < 4; i++) {\n\n\t\t\t\tint nr = u.r + dx[i], nc = u.c + dy[i];\n\n\t\t\t\tif (valid(nr, nc) && grid[nr][nc] == -1) {\n\n\t\t\t\t\tif (adj[nr][nc].r == adj[u.r][u.c].r && adj[nr][nc].c == adj[u.r][u.c].c) {\n\n\t\t\t\t\t\tgrid[nr][nc] = (i + 2) % 4;\n\n\t\t\t\t\t\tq.add(new Pair(nr,nc));\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}\n\n\n\n\tpublic static void main(String[] args) throws Exception {\n\n\t\tn = sc.nextInt();\n\n\t\tgrid = new int[n][n];\n\n\t\tadj = new Pair[n][n];\n\n\t\tdx = new int[] { 0, 1, 0, -1 };\n\n\t\tdy = new int[] { 1, 0, -1, 0 };\n\n\n\n\t\tfor (int[] arr : grid)\n\n\t\t\tArrays.fill(arr, -1);\n\n\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tfor (int j = 0; j < n; j++) {\n\n\t\t\t\tadj[i][j] = new Pair(sc.nextInt() - 1, sc.nextInt() - 1);\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tboolean flag = true;\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tfor (int j = 0; j < n; j++) {\n\n\t\t\t\tif (grid[i][j] == -1) {\n\n\t\t\t\t\tif (adj[i][j].r == -2) {\n\n\t\t\t\t\t\tflag &= dfs(i, j);\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tif (adj[i][j].r == i && adj[i][j].c == j) {\n\n\t\t\t\t\t\t\tgrid[i][j] = 4;\n\n\t\t\t\t\t\t\tbfs(new Pair(i,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}\n\n\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tfor (int j = 0; j < n; j++) {\n\n\t\t\t\tif (grid[i][j] == -1)\n\n\t\t\t\t\tflag = false;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tout.println(flag ? \"VALID\" : \"INVALID\");\n\n\t\tif (flag) {\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tfor (int j = 0; j < n; j++) {\n\n\t\t\t\t\tint x = grid[i][j];\n\n\t\t\t\t\tif (x == 0)\n\n\t\t\t\t\t\tout.print(\"R\");\n\n\t\t\t\t\telse if (x == 1)\n\n\t\t\t\t\t\tout.print(\"D\");\n\n\t\t\t\t\telse if (x == 2)\n\n\t\t\t\t\t\tout.print(\"L\");\n\n\t\t\t\t\telse if (x == 3)\n\n\t\t\t\t\t\tout.print(\"U\");\n\n\t\t\t\t\telse\n\n\t\t\t\t\t\tout.print(\"X\");\n\n\t\t\t\t}\n\n\t\t\t\tout.println();\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tout.close();\n\n\t}\n\n\n\n\tstatic class Pair {\n\n\t\tint r, c;\n\n\n\n\t\tpublic Pair(int r, int c) {\n\n\t\t\tthis.r = r;\n\n\t\t\tthis.c = c;\n\n\t\t}\n\n\t}\n\n\n\n}\n\n\n\nclass Scanner {\n\n\tStringTokenizer st;\n\n\tBufferedReader br;\n\n\n\n\tpublic Scanner(InputStream system) {\n\n\t\tbr = new BufferedReader(new InputStreamReader(system));\n\n\t}\n\n\n\n\tpublic Scanner(String file) throws Exception {\n\n\t\tbr = new BufferedReader(new FileReader(file));\n\n\t}\n\n\n\n\tpublic String next() throws IOException {\n\n\t\twhile (st == null || !st.hasMoreTokens())\n\n\t\t\tst = new StringTokenizer(br.readLine());\n\n\t\treturn st.nextToken();\n\n\t}\n\n\n\n\tpublic String nextLine() throws IOException {\n\n\t\treturn br.readLine();\n\n\t}\n\n\n\n\tpublic int nextInt() throws IOException {\n\n\t\treturn Integer.parseInt(next());\n\n\t}\n\n\n\n\tpublic double nextDouble() throws IOException {\n\n\t\treturn Double.parseDouble(next());\n\n\t}\n\n\n\n\tpublic Long nextLong() throws IOException {\n\n\t\treturn Long.parseLong(next());\n\n\t}\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.io.PrintWriter;\n\nimport java.util.*;\n\n\n\nimport static java.lang.Double.parseDouble;\n\nimport static java.lang.Integer.parseInt;\n\nimport static java.lang.Long.parseLong;\n\nimport static java.lang.System.in;\n\nimport static java.lang.System.out;\n\n\n\npublic class SolutionE extends Thread {\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\n\n InputStreamReader(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 parseInt(next());\n\n }\n\n\n\n long nextLong() {\n\n return parseLong(next());\n\n }\n\n\n\n double nextDouble() {\n\n return 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 private static final FastReader scanner = new FastReader();\n\n private static final PrintWriter out = new PrintWriter(System.out);\n\n\n\n public static void main(String[] args) {\n\n new Thread(null, new SolutionE(), \"Main\", 1 << 28).start();\n\n }\n\n\n\n public void run() {\n\n solve();\n\n out.close();\n\n }\n\n\n\n private static void solve() {\n\n int n = scanner.nextInt();\n\n int[] a = new int[n];\n\n for (int i = 0; i < n; i++) {\n\n a[i] = scanner.nextInt();\n\n }\n\n\n\n int[][] dp = new int[n][n+1];\n\n\n\n for (int size = 1; size <= n; size++) {\n\n for (int l = 0; l < n; l++) {\n\n if (l + size > n) {\n\n break;\n\n }\n\n int r = l + size;\n\n\n\n dp[l][r] = -1;\n\n if (size == 1) {\n\n dp[l][r] = a[l];\n\n continue;\n\n }\n\n\n\n\n\n for (int j = l+1; j < r; j++) {\n\n if (dp[l][j] == dp[j][r] && dp[l][j] != -1) {\n\n dp[l][r] = dp[l][j] + 1;\n\n }\n\n }\n\n }\n\n }\n\n\n\n int[] dp2 = new int[n+1];\n\n\n\n for (int i = 1; i <= n; i++) {\n\n int minValue = 2000;\n\n\n\n if (dp[0][i] != -1) {\n\n minValue = 1;\n\n }\n\n for (int j = 1; j < i; j++) {\n\n if (dp[j][i] != -1) {\n\n int value = 1 + dp2[j];\n\n minValue = Math.min(minValue, value);\n\n }\n\n }\n\n dp2[i] = minValue;\n\n }\n\n\n\n out.println(dp2[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; i--) {\n int v = a[i];\n for (int j = 0; j < h; j++) {\n \/\/ if sleep v hours\n {\n int hour = (j + v) % h;\n int w = (hour >= l && hour <= r ? 1 : 0) + (i == n - 1 ? 0 : dp[i+1][hour]);\n dp[i][j] = w;\n }\n \/\/ if sleep v - 1 hours\n {\n int hour = (j + v + h - 1) % h;\n int w = (hour >= l && hour <= r ? 1 : 0) + (i == n - 1 ? 0 : dp[i+1][hour]);\n dp[i][j] = Math.max(dp[i][j], w);\n }\n }\n }\n int ans = 0;\n for (int j = 0; j < h; j++) {\n ans = Math.max(ans, dp[0][j]);\n }\n return dp[0][0];\n }\n\n static String trace(int[][] a) {\n return Arrays.deepToString(a).replace(\" \", \"\").replace('[', '{').replace(']', '}');\n }\n\n static String trace(int[] a) {\n return Arrays.toString(a).replace(\" \", \"\").replace('[', '{').replace(']', '}');\n }\n\n static boolean test = false;\n static void doTest() {\n if (!test) {\n return;\n }\n long t0 = System.currentTimeMillis();\n System.out.format(\"%d msec\\n\", System.currentTimeMillis() - t0);\n System.exit(0);\n }\n\n public static void main(String[] args) {\n doTest();\n MyScanner in = new MyScanner();\n int n = in.nextInt();\n int h = in.nextInt();\n int l = in.nextInt();\n int r = in.nextInt();\n int[] a = new int[n];\n for (int i = 0; i < n; i++) {\n a[i] = in.nextInt();\n }\n int ans = solve(a, h, l, r);\n System.out.println(ans);\n }\n\n static void output(int[] a) {\n if (a == null) {\n System.out.println(\"-1\");\n return;\n }\n StringBuilder sb = new StringBuilder();\n for (int v : a) {\n sb.append(v);\n sb.append(' ');\n if (sb.length() > 4000) {\n System.out.print(sb.toString());\n sb.setLength(0);\n }\n }\n System.out.println(sb.toString());\n }\n\n static void myAssert(boolean cond) {\n if (!cond) {\n throw new RuntimeException(\"Unexpected\");\n }\n }\n\n static class MyScanner {\n BufferedReader br;\n StringTokenizer st;\n\n public MyScanner() {\n try {\n final String USERDIR = System.getProperty(\"user.dir\");\n String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(\".MyScanner\", \"\");\n cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;\n final File fin = new File(USERDIR + \"\/io\/c\" + cname.substring(1,5) + \"\/\" + cname + \".in\");\n br = new BufferedReader(new InputStreamReader(fin.exists()\n ? new FileInputStream(fin) : System.in));\n } catch (Exception e) {\n br = new BufferedReader(new InputStreamReader(System.in));\n }\n }\n\n public String next() {\n try {\n while (st == null || !st.hasMoreElements()) {\n st = new StringTokenizer(br.readLine());\n }\n return st.nextToken();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public int nextInt() {\n return Integer.parseInt(next());\n }\n\n public long nextLong() {\n return Long.parseLong(next());\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":"import java.util.*;\n\n\n\npublic class Main {\n\n\n\n public static void main(String[] args) {\n\n Scanner input = new Scanner(System.in);\n\n String s = input.nextLine();\n\n\n\n int[][] count = new int[s.length() + 1][26];\n\n\n\n for (int i = 0; i < s.length(); ++i) {\n\n count[i + 1] = count[i].clone();\n\n count[i + 1][s.charAt(i) - 'a'] += 1;\n\n }\n\n\n\n int q = input.nextInt();\n\n while (q-- != 0) {\n\n int l = input.nextInt() - 1, r = input.nextInt() - 1;\n\n int distinct = 0;\n\n for (int i = 0; i < 26; ++i) {\n\n distinct += (count[r + 1][i] != count[l][i] ? 1 : 0);\n\n }\n\n if (l != r && s.charAt(l) == s.charAt(r) && distinct < 3) {\n\n System.out.println(\"No\");\n\n } else {\n\n System.out.println(\"Yes\");\n\n }\n\n }\n\n }\n\n}\n\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.io.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.util.StringTokenizer;\n\npublic class Solution {\n\n static long n;\n\n static int m;\n\n static int[] a, map, v, needs;\n\n public static void main(String[] args) throws IOException {\n\n Reader input = new Reader();\n\n StringBuilder output = new StringBuilder();\n\n int t = input.nextInt();\n\n while(t > 0) {\n\n n = input.nextLong();\n\n m = input.nextInt();\n\n a = new int[m];\n\n for(int i = 0; i < m; ++i) a[i] = input.nextInt();\n\n long sum = 0;\n\n for(int i = 0; i < m; ++i) sum += (long)a[i];\n\n if(sum < n) {\n\n output.append(-1);\n\n } else {\n\n output.append(solve());\n\n }\n\n --t;\n\n output.append(\"\\n\");\n\n }\n\n System.out.print(output);\n\n }\n\n static long solve() {\n\n map = new int[30];\n\n v = new int[30];\n\n v[0] = 1;\n\n for(int i = 1; i < 30; ++i) {\n\n v[i] = v[i-1]*2;\n\n }\n\n for(int i = 0; i < m; ++i) {\n\n int left = 0, right = 30, middle;\n\n while(left < right) {\n\n middle = left+right>>1;\n\n if(v[middle] == a[i]) {\n\n ++map[middle];\n\n break;\n\n } else if(v[middle] > a[i]) {\n\n right = middle;\n\n } else {\n\n left = middle+1;\n\n }\n\n }\n\n }\n\n needs = new int[30];\n\n for(int i = 29; i > -1; --i) {\n\n needs[i] = (int)(n\/v[i]);\n\n n -= (n\/v[i])*(long)v[i];\n\n }\n\n for(int i = 29; i > -1; --i) {\n\n if(map[i] >= needs[i]) {\n\n map[i] -= needs[i];\n\n needs[i] = 0;\n\n } else {\n\n needs[i] -= map[i];\n\n map[i] = 0;\n\n }\n\n }\n\n long count = 0;\n\n for(int i = 0; i < 30; ++i) {\n\n if(map[i] >= needs[i]) {\n\n map[i] -= needs[i];\n\n needs[i] = 0;\n\n if(i+1 < 30) {\n\n int temp = map[i]\/2;\n\n map[i+1] += temp;\n\n map[i] -= temp*2;\n\n }\n\n } else {\n\n needs[i] -= map[i];\n\n map[i] = 0;\n\n for(int j = i+1; j < 30; ++j) {\n\n if(map[j] > needs[j]) {\n\n for(int k = j-1; k >= i; --k) {\n\n ++map[k];\n\n ++count;\n\n }\n\n ++map[i];\n\n --map[j];\n\n break;\n\n }\n\n }\n\n --i;\n\n }\n\n }\n\n return count;\n\n }\n\n static class Reader {\n\n BufferedReader bufferedReader;\n\n StringTokenizer string;\n\n public Reader() {\n\n InputStreamReader inr = new InputStreamReader(System.in);\n\n bufferedReader = new BufferedReader(inr);\n\n }\n\n public String next() throws IOException {\n\n while(string == null || ! string.hasMoreElements()) {\n\n string = new StringTokenizer(bufferedReader.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 public double nextDouble() throws IOException {\n\n return Double.parseDouble(next());\n\n }\n\n public String nextLine() throws IOException {\n\n return bufferedReader.readLine();\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.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.util.StringTokenizer;\n\npublic class Solution {\n\n static int n;\n\n static int[] a;\n\n static Integer[][][][] memo;\n\n public static void main(String[] args) throws IOException {\n\n Reader input = new Reader();\n\n n = input.nextInt();\n\n a = new int[n];\n\n for(int i = 0; i < n; ++i) {\n\n a[i] = input.nextInt();\n\n }\n\n boolean[] used = new boolean[n+1];\n\n for(int i = 0; i < n; ++i) {\n\n used[a[i]] = true;\n\n }\n\n int evens = 0, odds = 0;\n\n for(int i = 1; i <= n; ++i) {\n\n if(!used[i]) {\n\n if(i%2 == 0) ++evens;\n\n else ++odds;\n\n }\n\n }\n\n memo = new Integer[n][evens+1][odds+1][2];\n\n System.out.println(solve(0, evens, odds, 0));\n\n }\n\n static int solve(int p, int evens, int odds, int prevParty) {\n\n if(p >= n) {\n\n return 0;\n\n }\n\n if(memo[p][evens][odds][prevParty] != null) {\n\n return memo[p][evens][odds][prevParty];\n\n }\n\n int answer = n+1;\n\n if(a[p] != 0) {\n\n answer = p == 0 ? 0 : (a[p]%2 == prevParty ? 0 : 1);\n\n answer += solve(p+1, evens, odds, a[p]%2);\n\n } else {\n\n if(evens > 0) {\n\n int test = p == 0 ? 0 : (prevParty == 0 ? 0 : 1);\n\n test += solve(p+1, evens-1, odds, 0);\n\n answer = Math.min(test, answer);\n\n }\n\n if(odds > 0) {\n\n int test = p == 0 ? 0 : (prevParty == 0 ? 1 : 0);\n\n test += solve(p+1, evens, odds-1, 1);\n\n answer = Math.min(test, answer);\n\n }\n\n }\n\n memo[p][evens][odds][prevParty] = answer;\n\n return answer;\n\n }\n\n static class Reader {\n\n BufferedReader bufferedReader;\n\n StringTokenizer string;\n\n public Reader() {\n\n InputStreamReader inr = new InputStreamReader(System.in);\n\n bufferedReader = new BufferedReader(inr);\n\n }\n\n public String next() throws IOException {\n\n while(string == null || ! string.hasMoreElements()) {\n\n string = new StringTokenizer(bufferedReader.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 public double nextDouble() throws IOException {\n\n return Double.parseDouble(next());\n\n }\n\n public String nextLine() throws IOException {\n\n return bufferedReader.readLine();\n\n }\n\n }\n\n}","language":"java"} +{"contest_id":"1296","problem_id":"E2","statement":"E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1\u2264res\u2264n1\u2264res\u2264n) \u2014 the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1\u2264ci\u2264res1\u2264ci\u2264res and cici means the color of the ii-th character.ExamplesInputCopy9\nabacbecfd\nOutputCopy2\n1 1 2 1 2 1 2 1 2 \nInputCopy8\naaabbcbb\nOutputCopy2\n1 2 1 2 1 2 1 1\nInputCopy7\nabcdedc\nOutputCopy3\n1 1 1 1 1 2 3 \nInputCopy5\nabcde\nOutputCopy1\n1 1 1 1 1 \n","tags":["data structures","dp"],"code":"import java.io.*;\n\nimport java.util.*;\n\npublic class Main {\n\n\tpublic static void main(String[] args) throws IOException \n\n\t{ \n\n\t\tFastScanner f = new FastScanner(); \n\n\t\tint t=1;\n\n\/\/\t\tt=f.nextInt();\n\n\t\tPrintWriter out=new PrintWriter(System.out);\n\n\t\tfor(int tt=0;tt-1;i--) {\n\n\t\t\t\tint cd=1;\n\n\t\t\t\tfor(int j=0; j q = new ArrayList<>();\n\n for (int i: p) q.add( i);\n\n Collections.sort(q);\n\n for (int i = 0; i < p.length; i++) p[i] = q.get(i);\n\n }\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\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\t\t\n\n\t\tint nextInt() {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\t\tint[] readArray(int n) {\n\n\t\t\tint[] a=new int[n];\n\n\t\t\tfor (int i=0; i seen = new HashSet<>();\n\n for(int j = 0; j nums) throws IOException {\n\n for(int i = 0; ikk\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\u2264501\u2264n\u226450) \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":["greedy"],"code":"\timport java.io.*;\n\n\timport java.util.*;\n\n\t \n\n\tpublic class ProblemD {\n\n\t \n\n\t\tpublic static void main(String[] args) throws Exception {\n\n\t\t\tScanner in = new Scanner();\n\n\t\t\tint n = in.readInt();\n\n\t\t\tint a[] = new int[n];\n\n\t\t\tfor(int i = 0;ires = new ArrayList<>();\n\n\t\t\tfor(int i = 0;imp = new HashMap<>();\n\n\t\t\t\t\tArrayListl = new ArrayList<>();\n\n\t\t\t\t\tlong cur = 0;\n\n\t\t\t\t\tint pos = 0;\n\n\t\t\t\t\tmp.put(0l, -1);\n\n\t\t\t\t\tfor(int z=0;zmx){\n\n\t\t\t\t\t\tmx = l.size();\n\n\t\t\t\t\t\tres = new ArrayList<>(l);\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(res.size());\n\n\t\t\tfor(Pair it:res)System.out.println(it.x+\" \"+it.y);\n\n\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\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() { \n\n\t\t @Override public int compare(Pair p1, Pair p2) \n\n\t\t { \n\n\t\t \tif(p1.x!=p2.x) {\n\n\t\t return (int)(p1.x - p2.x); \n\n\t\t \t}\n\n\t\t \telse { \n\n\t\t \t\treturn (int)(p1.y - p2.y);\n\n\t\t \t}\n\n\t\t } \n\n\t\t }); \n\n\t\t \n\n\/\/\t\t for (int i = 0; i < n; i++) { \n\n\/\/\t\t System.out.print(arr[i].x + \" \" + arr[i].y + \" \"); \n\n\/\/\t\t } \n\n\/\/\t\t System.out.println(); \n\n\t\t } \n\n\t\t} \n\n\t \n\n\t static class Scanner {\n\n\t BufferedReader br;\n\n\t StringTokenizer st;\n\n\t \n\n\t public Scanner()\n\n\t {\n\n\t br = new BufferedReader(\n\n\t new InputStreamReader(System.in));\n\n\t }\n\n\t \n\n\t String next()\n\n\t {\n\n\t while (st == null || !st.hasMoreElements()) {\n\n\t try {\n\n\t st = new StringTokenizer(br.readLine());\n\n\t }\n\n\t catch (IOException e) {\n\n\t e.printStackTrace();\n\n\t }\n\n\t }\n\n\t return st.nextToken();\n\n\t }\n\n\t \n\n\t int nextInt() { return Integer.parseInt(next()); }\n\n\t \n\n\t long nextLong() { return Long.parseLong(next()); }\n\n\t \n\n\t double nextDouble()\n\n\t {\n\n\t return Double.parseDouble(next());\n\n\t }\n\n\t \n\n\t String nextLine()\n\n\t {\n\n\t String str = \"\";\n\n\t try {\n\n\t str = br.readLine();\n\n\t }\n\n\t catch (IOException e) {\n\n\t e.printStackTrace();\n\n\t }\n\n\t return str;\n\n\t }\n\n\t }\n\n\t static int max[] = new int[200005];\n\n\t static int ans[] = new int[200005];\n\n\t static void dfs(int src,int par,ArrayList adj[],int a[]) {\n\n\t\t \n\n\t\t max[src] = a[src];\n\n\t\t for(int i : adj[src]) {\n\n\t\t\t \n\n\t\t\t if(i == par) {\n\n\t\t\t\t continue;\n\n\t\t\t }\n\n\t\t\t\t dfs(i,src,adj,a);\n\n\t\t\t\t max[src] += Math.max(0, max[i]);\n\n\t\t\t \n\n\t\t }\n\n\t\t \n\n\t }\n\n\t \n\n\t static void dfs(int src,int par,ArrayList adj[]) {\n\n\t\t \n\n\t\t ans[src] = max[src];\n\n\t\t \n\n\t\t for(int i : adj[src]) {\n\n\t\t\t if(i == par) {\n\n\t\t\t\t continue;\n\n\t\t\t }\n\n\t\t\t \n\n\t\t\t max[src] -= Math.max(0, max[i]);\n\n\t\t\t max[i] += Math.max(0, max[src]);\n\n\t\t\t \n\n\t\t\t dfs(i,src,adj);\n\n\t\t\t \n\n\t\t\t max[i] -= Math.max(0, max[src]);\n\n\t\t\t max[src] += Math.max(0, max[i]);\n\n\t\t }\n\n\t }\n\n\t public static void main(String args[]) throws Exception { \n\n\t\t\n\n\t\t Scanner sc = new Scanner();\n\n\t\t StringBuilder res = new StringBuilder();\n\n\t\t \n\n\t\t int tc = 1;\n\n\t\t \n\n\t\t while(tc-->0) {\n\n\t\t\t \n\n\t\t\t int n = sc.nextInt();\n\n\t\t\t \n\n\t\t\t int a[] = new int[n];\n\n\t\t\t \n\n\t\t\t for(int i=0;i adj[] = new ArrayList[n];\n\n\t\t\t \n\n\t\t\t for(int i=0;i();\n\n\t\t\t }\n\n\t\t\t \n\n\t\t\t for(int i=0;i0){\n\n\t\t\tString firstString = scan.next();\n\n\t\t\tString secondString = scan.next();\n\n\t\t\tString thirdString = scan.next();\n\n\t\t\tboolean flag = false;\n\n\t\t\tfor(int i=0; i 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; 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":"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.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.util.*;\n\npublic class Main {\n static int globalVariable = 123456789;\n static String author = \"pl728 on codeforces\";\n\n public static void main(String[] args) {\n FastReader sc = new FastReader();\n PrintWriter pw = new PrintWriter(System.out);\n MathUtils mathUtils = new MathUtils();\n ArrayUtils arrayUtils = new ArrayUtils();\n\n int tc = sc.ni();\n while (tc-- != 0) {\n String s = sc.ns();\n\n \/\/ separate the string into two parts\n \/\/ if one part is a palindrome, and the other part has no repeating letters\n \/\/ then it's possible\n char[] keyboard = new char[26];\n List alphabet = new ArrayList<>();\n Set alphabetSet = new HashSet<>();\n int n = s.length();\n for (int i = 0; i < 26; i++) {\n alphabet.add((char) (i + 97));\n alphabetSet.add((char) (i + 97));\n }\n if (n == 1) {\n pw.println(\"YES\");\n keyboard[0] = s.charAt(0);\n alphabet.remove(s.charAt(0) - 97);\n for (int i = 0; i < alphabet.size(); i++) {\n keyboard[i + 1] = alphabet.get(i);\n }\n pw.println(keyboard);\n continue;\n }\n boolean ans = true;\n StringBuilder sb = new StringBuilder(s.charAt(0) + \"\" + s.charAt(1));\n int x = 1;\n alphabetSet.remove(s.charAt(0));\n alphabetSet.remove(s.charAt(1));\n\n for(int i = 2; i < n && ans; i++) {\n int m = sb.length();\n if(!alphabetSet.contains(s.charAt(i))) {\n if(x == m - 1) {\n if(sb.charAt(x - 1) == s.charAt(i)) x--;\n else ans = false;\n } else if (x == 0) {\n if(sb.charAt(x + 1) == s.charAt(i)) x++;\n else ans = false;\n } else {\n if(sb.charAt(x + 1) == s.charAt(i)) x++;\n else if(sb.charAt(x - 1) == s.charAt(i)) x--;\n else ans = false;\n }\n } else {\n if(x != m-1 && x != 0) {\n ans = false;\n } else {\n if(x == 0) {\n sb.insert(0, s.charAt(i));\n } else {\n sb.append(s.charAt(i));\n x++;\n }\n alphabetSet.remove(s.charAt(i));\n }\n }\n }\n\n if(ans) {\n pw.println(\"YES\");\n pw.print(sb);\n for(char k : alphabetSet) {\n pw.print(k);\n }\n pw.println();\n } else {\n pw.println(\"NO\");\n }\n\n\n }\n pw.flush();\n }\n\n static class FastReader {\n \/**\n * Uses BufferedReader and StringTokenizer for quick java I\/O\n * get next int, long, double, string\n * get int, long, double, string arrays, both primitive and wrapped object when array contains all elements\n * on one line, and we know the array size (n)\n * next: gets next space separated item\n * nextLine: returns entire line as space\n *\/\n BufferedReader br;\n StringTokenizer st;\n\n public FastReader() {\n this.br = new BufferedReader(new InputStreamReader(System.in));\n }\n\n public 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 \/\/ to parse something else:\n \/\/ T x = T.parseT(fastReader.next());\n public int ni() {\n return Integer.parseInt(next());\n }\n\n public String ns() {\n String str = \"\";\n try {\n str = br.readLine();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return str;\n }\n\n public String[] readStringArrayLine(int n) {\n String line = \"\";\n try {\n line = br.readLine();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return line.split(\" \");\n }\n\n public String[] readStringArrayLines(int n) {\n String[] result = new String[n];\n for (int i = 0; i < n; i++) {\n result[i] = this.next();\n }\n return result;\n }\n\n public int[] readIntArray(int n) {\n int[] result = new int[n];\n for (int i = 0; i < n; i++) {\n result[i] = this.ni();\n }\n return result;\n }\n\n public long[] readLongArray(int n) {\n long[] result = new long[n];\n for (int i = 0; i < n; i++) {\n result[i] = this.nl();\n }\n return result;\n }\n\n public Integer[] readIntArrayObject(int n) {\n Integer[] result = new Integer[n];\n for (int i = 0; i < n; i++) {\n result[i] = this.ni();\n }\n return result;\n }\n\n public long nl() {\n return Long.parseLong(next());\n }\n\n public char[] readCharArray(int n) {\n return this.ns().toCharArray();\n }\n\n }\n\n static class MathUtils {\n public MathUtils() {\n }\n\n public long gcdLong(long a, long b) {\n if (a % b == 0)\n return b;\n else\n return gcdLong(b, a % b);\n }\n\n public long lcmLong(long a, long b) {\n return a * b \/ gcdLong(a, b);\n }\n }\n\n static class ArrayUtils {\n public ArrayUtils() {\n }\n\n public static int[] reverse(int[] a) {\n int n = a.length;\n int[] b = new int[n];\n int j = n;\n for (int i = 0; i < n; i++) {\n b[j - 1] = a[i];\n j = j - 1;\n }\n\n return b;\n }\n\n public int sumIntArrayInt(int[] a) {\n int ans = 0;\n for (int i = 0; i < a.length; i++) {\n ans += a[i];\n }\n\n return ans;\n }\n\n public long sumLongArrayLong(int[] a) {\n long ans = 0;\n for (int i = 0; i < a.length; i++) {\n ans += a[i];\n }\n\n return ans;\n }\n }\n\n public static int lowercaseToIndex(char c) {\n return (int) c - 97;\n }\n}\n","language":"java"} +{"contest_id":"1295","problem_id":"B","statement":"B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss\u2026t=ssss\u2026 For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q\u2212cnt1,qcnt0,q\u2212cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string \"abcd\" has 5 prefixes: empty string, \"a\", \"ab\", \"abc\" and \"abcd\".InputThe first line contains the single integer TT (1\u2264T\u22641001\u2264T\u2264100) \u2014 the number of test cases.Next 2T2T lines contain descriptions of test cases \u2014 two lines per test case. The first line contains two integers nn and xx (1\u2264n\u22641051\u2264n\u2264105, \u2212109\u2264x\u2264109\u2212109\u2264x\u2264109) \u2014 the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si\u2208{0,1}si\u2208{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers \u2014 one per test case. For each test case print the number of prefixes or \u22121\u22121 if there is an infinite number of such prefixes.ExampleInputCopy4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01\nOutputCopy3\n0\n1\n-1\nNoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.","tags":["math","strings"],"code":"import java.util.*;\n\n\n\npublic class infiniteprefixes {\n\n\n\n\tpublic static void main(String[] args) {\n\n\t\tScanner sc = new Scanner(System.in);\n\n\n\n\t\tint t = sc.nextInt();\n\n\n\n\t\twhile (t-- > 0) {\n\n\t\t\tint n = sc.nextInt();\n\n\t\t\tint x = sc.nextInt();\n\n\t\t\tString s = sc.next();\n\n\t\t\tint[] cnt = new int[n];\n\n\t\t\tint c = 0, c0 = 0, c1 = 0, d = 0;\n\n\n\n\t\t\tint ans = 0;\n\n\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tif (s.charAt(i) == '0') {\n\n\t\t\t\t\tc++;\n\n\t\t\t\t\tc0++;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tc--;\n\n\t\t\t\t\tc1++;\n\n\t\t\t\t}\n\n\t\t\t\tcnt[i] = c;\n\n\t\t\t}\n\n\n\n\t\t\td = c0 - c1;\n\n\n\n\t\t\tif (d == 0) {\n\n\t\t\t\tc = 0;\n\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\t\tif (cnt[i] == x)\n\n\t\t\t\t\t\tc++;\n\n\t\t\t\t}\n\n\t\t\t\tif (c != 0)\n\n\t\t\t\t\tans = -1;\n\n\t\t\t\telse\n\n\t\t\t\t\tans = 0;\n\n\t\t\t} else {\n\n\t\t\t\tif (x == 0)\n\n\t\t\t\t\tans++;\n\n\n\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\t\tif ((cnt[i] - x) % d == 0) {\n\n\t\t\t\t\t\tif (d > 0 && cnt[i] <= x)\n\n\t\t\t\t\t\t\tans++;\n\n\t\t\t\t\t\tif (d < 0 && cnt[i] >= x)\n\n\t\t\t\t\t\t\tans++;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\n\t\t\tSystem.out.println(ans);\n\n\t\t}\n\n\t}\n\n}\n\n","language":"java"} +{"contest_id":"1316","problem_id":"B","statement":"B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1\u2264k\u2264n1\u2264k\u2264n). For ii from 11 to n\u2212k+1n\u2212k+1, reverse the substring s[i:i+k\u22121]s[i:i+k\u22121] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a\u2260ba\u2260b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u226450001\u2264t\u22645000). The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u226450001\u2264n\u22645000)\u00a0\u2014 the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s\u2032s\u2032 achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1\u2264k\u2264n1\u2264k\u2264n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6\n4\nabab\n6\nqwerty\n5\naaaaa\n6\nalaska\n9\nlfpbavjsm\n1\np\nOutputCopyabab\n1\nertyqw\n3\naaaaa\n1\naksala\n6\navjsmbpfl\n5\np\n1\nNoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11. ","tags":["brute force","constructive algorithms","implementation","sortings","strings"],"code":"import java.util.*;\n\nimport java.io.*;\n\n \n\npublic class File {\n\n\tpublic static class FastScanner {\n\n\t\tBufferedReader br;\n\n\t\tStringTokenizer st;\n\n\t\t\n\n\t\tpublic FastScanner() {\n\n\t\t\tbr = new BufferedReader(new InputStreamReader(System.in));\n\n\t\t}\n\n\t\t\n\n\t\tString next() {\n\n\t\t\twhile (st == null || !st.hasMoreElements()) {\n\n\t\t\t\ttry {\n\n\t\t\t\t\tst = new StringTokenizer(br.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}\n\n\t\t\t\n\n\t\t\treturn st.nextToken();\n\n\t\t}\n\n\t\t\n\n\t\tint nextInt() {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\t\t\n\n\t\tlong nextLong() {\n\n\t\t\treturn Long.parseLong(next());\n\n\t\t}\n\n\t}\n\n\t\t\n\n\tpublic static void main(String[] args) {\n\n\t\tFastScanner sc = new FastScanner();\n\n\t\tPrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));\n\n\t\tint test=sc.nextInt();\n\n\t\twhile(test>0)\n\n\t\t{\n\n\t\t int n=sc.nextInt();\n\n\t\t String s=sc.next();\n\n\t\t String ans=\"\";\n\n\t\t int a=0;\n\n\t\t for(int i=1;i<=n;i++)\n\n\t\t {\n\n\t\t StringBuilder temp=new StringBuilder();\n\n\t\t temp.append(s.substring(i-1));\n\n\t\t StringBuilder add=new StringBuilder();\n\n\t\t add.append(s.substring(0,i-1));\n\n\t\t if(temp.length()%2!=0)add.reverse();\n\n\t\t temp.append(add);\n\n\t\t if(ans==\"\" || ans.compareTo(temp.toString())>0)\n\n\t\t {\n\n\t\t ans=temp.toString();\n\n\t\t a=i;\n\n\t\t }\n\n\t\t }\n\n\t\t out.println(ans);\n\n\t\t out.println(a);\n\n\t\t test--;\n\n\t\t}\n\n\t\tout.close();\n\n\t}\n\n\t\n\n}","language":"java"} +{"contest_id":"1307","problem_id":"C","statement":"C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1\u2264|s|\u22641051\u2264|s|\u2264105) \u2014 the text that Bessie intercepted.OutputOutput a single integer \u00a0\u2014 the number of occurrences of the secret message.ExamplesInputCopyaaabb\nOutputCopy6\nInputCopyusaco\nOutputCopy1\nInputCopylol\nOutputCopy2\nNoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.","tags":["brute force","dp","math","strings"],"code":"import java.util.*;\n\n\n\npublic class C1307 {\n\n \n\n public static void main(String[] args) {\n\n Scanner scn = new Scanner(System.in);\n\n\n\n String s = scn.next();\n\n\n\n long[] dp1 = new long[26]; \/\/ for 1 length\n\n long[][] dp2 = new long[26][26]; \/\/ for 2 length\n\n\n\n for(int i=0;i[] pfactors, factors;\n\n static int sieve[];\n\n static int count[];\n\n static long ans;\n\n\n\n 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\n\n static long lcm(long a, long b, long g) {\n\n long z = gcd(a, b);\n\n ans = Math.max(ans, ((a * b) \/ z) * g);\n\n if (z == 1)\n\n return 1;\n\n return 0;\n\n }\n\n\n\n static int get(int x) {\n\n int val = 0;\n\n int l = pfactors[x].size();\n\n for (int i = 0; i < (1 << l); i++) {\n\n int p = 1, c = 0;\n\n for (int j = 0; j < l; j++) {\n\n if ((i & (1 << j)) > 0) {\n\n p = p * pfactors[x].get(j);\n\n c++;\n\n }\n\n }\n\n if (c % 2 == 0)\n\n val = val + count[p];\n\n else\n\n val = val - count[p];\n\n }\n\n return val;\n\n }\n\n\n\n static void add(int x, int v) {\n\n for (int z : factors[x]) {\n\n count[z] += v;\n\n }\n\n }\n\n\n\n public static void main(String args[]) throws IOException {\n\n FastReader in = new FastReader(System.in);\n\n int i, j, MN = 100000;\n\n sieve = new int[MN + 1];\n\n pfactors = new ArrayList[MN + 1];\n\n factors = new ArrayList[MN + 1];\n\n for (i = 1; i <= MN; i++) {\n\n pfactors[i] = new ArrayList<>();\n\n factors[i] = new ArrayList<>();\n\n }\n\n sieve[1] = 1;\n\n for (i = 1; i <= MN; i++) {\n\n if (sieve[i] == 0) {\n\n for (j = i; j <= MN; j += i) {\n\n sieve[j] = i;\n\n factors[j].add(i);\n\n }\n\n\n\n } else {\n\n for (j = i; j <= MN; j += i) {\n\n factors[j].add(i);\n\n }\n\n }\n\n }\n\n for (i = 2; i <= MN; i++) {\n\n int temp = i;\n\n while (temp != 1) {\n\n int x = sieve[temp];\n\n pfactors[i].add(x);\n\n while (temp % x == 0)\n\n temp = temp \/ x;\n\n }\n\n }\n\n boolean pre[] = new boolean[MN + 1];\n\n ans = 0;\n\n int n = in.nextInt();\n\n for (i = 0; i < n; i++) {\n\n int x = in.nextInt();\n\n ans = Math.max(ans, x);\n\n pre[x] = true;\n\n }\n\n\n\n count = new int[MN + 1];\n\n for (int gcd = 1; gcd <= MN; gcd++) {\n\n ArrayList list = new ArrayList<>();\n\n for (j = gcd; j <= MN; j += gcd) {\n\n if (pre[j]) {\n\n list.add(j \/ gcd);\n\n }\n\n }\n\n Stack st = new Stack<>();\n\n Collections.sort(list, Collections.reverseOrder());\n\n for (int x : list) {\n\n int z = get(x);\n\n if (z == 0) {\n\n st.add(x);\n\n add(x, 1);\n\n } else {\n\n while (z != 0) {\n\n int y = st.pop();\n\n z -= lcm(x, y, gcd);\n\n add(y, -1);\n\n }\n\n\n\n }\n\n }\n\n while (!st.isEmpty()) {\n\n add(st.pop(), -1);\n\n }\n\n\n\n }\n\n\n\n\n\n System.out.println(ans);\n\n\n\n }\n\n}\n\n\n\nclass FastReader {\n\n\n\n byte[] buf = new byte[2048];\n\n int index, total;\n\n InputStream in;\n\n\n\n FastReader(InputStream is) {\n\n in = is;\n\n }\n\n\n\n int scan() throws IOException {\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 }\n\n return buf[index++];\n\n }\n\n\n\n String next() throws IOException {\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 }\n\n return sb.toString();\n\n }\n\n\n\n int nextInt() throws IOException {\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 }\n\n for (; c >= '0' && c <= '9'; c = scan()) {\n\n val = (val << 3) + (val << 1) + (c & 15);\n\n }\n\n return neg ? -val : val;\n\n }\n\n\n\n long nextLong() throws IOException {\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 }\n\n for (; c >= '0' && c <= '9'; c = scan()) {\n\n val = (val << 3) + (val << 1) + (c & 15);\n\n }\n\n return neg ? -val : val;\n\n }\n\n}\n\n","language":"java"} +{"contest_id":"1325","problem_id":"B","statement":"B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt\u00a0\u2014 the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1\u2264n\u22641051\u2264n\u2264105)\u00a0\u2014 the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, \u2026\u2026, anan (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2\n3\n3 2 1\n6\n3 1 4 1 5 9\nOutputCopy3\n5\nNoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].","tags":["greedy","implementation"],"code":"import java.util.Arrays;\n\nimport java.util.Scanner;\n\n\n\npublic class Test {\n\n\n\n public static void main(String[] args) {\n\n Scanner sc = new Scanner(System.in);\n\n\n\n int t = sc.nextInt();\n\n\n\n while (t-- > 0) {\n\n int n = sc.nextInt();\n\n int[] a = new int[n];\n\n for (int i = 0; i < n; i++) {\n\n a[i] = sc.nextInt();\n\n }\n\n Arrays.sort(a);\n\n int count = 0;\n\n for (int i = 1; i < n; i++) {\n\n if (a[i - 1] == a[i]) {\n\n count++;\n\n }\n\n }\n\n System.out.println(n - count);\n\n } \n\n }\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.*;\nimport java.lang.*;\nimport java.io.*;\n\n\/\/ Created by @thesupremeone on 16\/07\/21\npublic class MindControl {\n int getMin(int[] arr, int m){\n int min = Integer.MAX_VALUE;\n for (int x = 0; x <= m-1; x++) {\n int y = arr.length-(m-1-x)-1;\n min = Math.min(min, Math.max(arr[x], arr[y]));\n }\n return min;\n }\n void solve() throws IOException {\n int ts = getInt();\n for (int t = 1; t <= ts; t++){\n int n = getInt();\n int m = getInt();\n int k = getInt();\n int[] a = new int[n];\n for (int i = 0; i < n; i++){\n a[i] = getInt();\n }\n int max = Integer.MIN_VALUE;\n if(kxkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1\u2264n,m,p\u22642\u22c51051\u2264n,m,p\u22642\u22c5105)\u00a0\u2014 the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1\u2264ai\u22641061\u2264ai\u2264106, 1\u2264cai\u22641091\u2264cai\u2264109)\u00a0\u2014 the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1\u2264bj\u22641061\u2264bj\u2264106, 1\u2264cbj\u22641091\u2264cbj\u2264109)\u00a0\u2014 the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1\u2264xk,yk\u22641061\u2264xk,yk\u2264106, 1\u2264zk\u22641031\u2264zk\u2264103)\u00a0\u2014 defense, attack and the number of coins of the monster kk.OutputPrint a single integer\u00a0\u2014 the maximum profit of the grind.ExampleInputCopy2 3 3\n2 3\n4 7\n2 4\n3 2\n5 11\n1 2 4\n2 1 6\n3 4 6\nOutputCopy1\n","tags":["brute force","data structures","sortings"],"code":"import java.io.*;\n\nimport java.util.*;\n\n\n\n\/*\n\n\u041f\u0440\u043e\u043a\u0440\u0430\u0441\u0442\u0438\u043d\u0438\u0440\u0443\u044e\n\n*\/\n\n\n\npublic class Main {\n\n\n\n static FastReader in;\n\n static PrintWriter out;\n\n static Random rand = new Random();\n\n static final int INF = (int) (1e9 + 10);\n\n static final int MOD = (int) (1e9 + 7);\n\n static final int N = (int) (1e6 + 6);\n\n static final int LOGN = 62;\n\n static int n, m, p;\n\n static int[][] a, b;\n\n\n\n static class Monster {\n\n int x, y, z;\n\n\n\n Monster(int x, int y, int z) {\n\n this.x = x;\n\n this.y = y;\n\n this.z = z;\n\n }\n\n }\n\n\n\n static class SegTree {\n\n int size;\n\n long[] t_max, t_add;\n\n\n\n SegTree(long[] arr) {\n\n size = arr.length;\n\n t_max = new long[size * 4];\n\n t_add = new long[size * 4];\n\n build(arr);\n\n }\n\n\n\n void push(int v) {\n\n if (t_add[v] != 0) {\n\n t_max[v * 2 + 1] += t_add[v];\n\n t_add[v * 2 + 1] += t_add[v];\n\n t_max[v * 2 + 2] += t_add[v];\n\n t_add[v * 2 + 2] += t_add[v];\n\n t_add[v] = 0;\n\n }\n\n }\n\n void pull(int v) {\n\n t_max[v] = Math.max(t_max[v * 2 + 1], t_max[v * 2 + 2]);\n\n }\n\n\n\n void build(int v, int tl, int tr, long[] arr) {\n\n if (tl == tr) {\n\n t_max[v] = arr[tl];\n\n return;\n\n }\n\n int tm = (tl + tr) \/ 2;\n\n build(v * 2 + 1, tl, tm, arr);\n\n build(v * 2 + 2, tm + 1, tr, arr);\n\n pull(v);\n\n }\n\n void build(long[] arr) {\n\n build(0, 0, size - 1, arr);\n\n }\n\n\n\n long maxOn(int v, int tl, int tr, int l, int r) {\n\n if (l > tr || r < tl) return -INF;\n\n if (l <= tl && tr <= r) {\n\n return t_max[v];\n\n }\n\n push(v);\n\n int tm = (tl + tr) \/ 2;\n\n return Math.max(maxOn(v * 2 + 1, tl, tm, l, r),\n\n maxOn(v * 2 + 2, tm + 1, tr, l, r));\n\n }\n\n long maxOn(int l, int r) {\n\n return maxOn(0, 0, size - 1, l, r);\n\n }\n\n\n\n void addOn(int v, int tl, int tr, int l, int r, int val) {\n\n if (l > tr || r < tl)return;\n\n if (l <= tl && tr <= r) {\n\n t_max[v] += val;\n\n t_add[v] += val;\n\n return;\n\n }\n\n push(v);\n\n int tm = (tl + tr) \/ 2;\n\n addOn(v * 2 + 1, tl, tm, l, r, val);\n\n addOn(v * 2 + 2, tm + 1, tr, l, r, val);\n\n pull(v);\n\n }\n\n void addOn(int l, int r, int val) {\n\n addOn(0, 0, size - 1, l, r, val);\n\n }\n\n }\n\n\n\n static int upperBound(int[][] arr, int x) {\n\n int lb = 0, rb = arr.length;\n\n while (lb < rb) {\n\n int mb = (lb + rb) \/ 2;\n\n if (arr[mb][0] <= x) {\n\n lb = mb + 1;\n\n } else {\n\n rb = mb;\n\n }\n\n }\n\n return lb;\n\n }\n\n\n\n static void solve() {\n\n n = in.nextInt();\n\n m = in.nextInt();\n\n p = in.nextInt();\n\n\n\n a = new int[n][2];\n\n for (int i = 0; i < n; i++) {\n\n a[i][0] = in.nextInt();\n\n a[i][1] = in.nextInt();\n\n }\n\n Arrays.sort(a, (a1, a2) -> Integer.compare(a1[0], a2[0]));\n\n\n\n b = new int[m][2];\n\n for (int i = 0; i < m; i++) {\n\n b[i][0] = in.nextInt();\n\n b[i][1] = in.nextInt();\n\n }\n\n Arrays.sort(b, (b1, b2) -> Integer.compare(b1[0], b2[0]));\n\n long[] arr = new long[m];\n\n for (int i = 0; i < m; i++) arr[i] = -b[i][1];\n\n SegTree st = new SegTree(arr);\n\n\n\n Monster[] monsters = new Monster[p];\n\n for (int i = 0; i < p; i++) {\n\n monsters[i] = new Monster(in.nextInt(), in.nextInt(), in.nextInt());\n\n }\n\n Arrays.sort(monsters, (m1, m2) -> Integer.compare(m1.x, m2.x));\n\n\n\n long ans = 10L * -INF;\n\n for (int i = 0, j = 0; i < n; i++) {\n\n while (j < p && monsters[j].x < a[i][0]) {\n\n st.addOn(upperBound(b, monsters[j].y), m - 1, monsters[j].z);\n\n j++;\n\n }\n\n ans = Math.max(ans, st.maxOn(0, m - 1) - a[i][1]);\n\n }\n\n\n\n out.println(ans);\n\n }\n\n\n\n public static void main(String[] args) throws FileNotFoundException {\n\n in = new FastReader(System.in);\n\n\/\/ in = new FastReader(new FileInputStream(\"connect.in\"));\n\n out = new PrintWriter(System.out);\n\n\/\/ out = new PrintWriter(new FileOutputStream(\"connect.out\"));\n\n\n\n\n\n int q = 1;\n\n\/\/ q = in.nextInt();\n\n\n\n while (q-- > 0) {\n\n solve();\n\n }\n\n\n\n out.close();\n\n }\n\n\n\n static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n FastReader(InputStream is) {\n\n br = new BufferedReader(new InputStreamReader(is));\n\n }\n\n\n\n Integer 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 next() {\n\n while (st == null || !st.hasMoreTokens()) {\n\n st = new StringTokenizer(nextLine());\n\n }\n\n return st.nextToken();\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}","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\n\n\nimport java.io.*;\n\nimport java.util.StringTokenizer;\n\n\n\npublic class Problem1288B {\n\n static Scanner scanner = new Scanner(System.in);\n\n public static void main(String[] args) throws IOException {\n\n int tc = scanner.nextInt();\n\n while (tc-->0){\n\n int a = scanner.nextInt();\n\n int b = scanner.nextInt();\n\n\n\n int cnt = 0;\n\n\n\n if (a<9 && b<9) {\n\n System.out.println(0);\n\n continue;\n\n }\n\n boolean flag = allNine(b);\n\n while (b>0){\n\n cnt++;\n\n b\/=10;\n\n }\n\n if (flag){\n\n long val = (long) cnt*a;\n\n System.out.println(val);\n\n continue;\n\n }\n\n long val = (long) a*(cnt-1);\n\n System.out.println(val);\n\n\n\n\n\n }\n\n }\n\n static boolean allNine(int b){\n\n boolean yes = true;\n\n String str = Integer.toString(b);\n\n for (int i =0;i hm = new HashMap<>();\n\n\t\t\t\t\t\tint[][] prev = new int[5][3];\n\n\t\t\t\t\t\tfor(int b = 1; b<5; b++) {\n\n\t\t\t\t\t\t\tprev[b] = p.get(b-1);\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tint start, len;\n\n\t\t\t\t\t\tfor(int b = 4; ; b++) {\n\n\t\t\t\t\t\t\tUtilities.leftShift(prev, 1);\n\n\t\t\t\t\t\t\tprev[4] = p.get(b);\n\n\t\t\t\t\t\t\tFAttackOnRedKingdom.State cur = new FAttackOnRedKingdom.State(prev);\n\n\t\t\t\t\t\t\tif(hm.containsKey(cur)) {\n\n\t\t\t\t\t\t\t\tint val = hm.get(cur);\n\n\t\t\t\t\t\t\t\tstart = val;\n\n\t\t\t\t\t\t\t\tlen = b-4-val;\n\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t}else {\n\n\t\t\t\t\t\t\t\thm.put(cur, b-4);\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\/\/\t\t\t\t\t\tUtilities.Debug.dbg(start, len);\n\n\t\t\t\t\t\tgrundy[i][j][k] = (a, b) -> {\n\n\t\t\t\t\t\t\tif(a=n) {\n\n\t\t\t\t\tint[][] ndp = new int[n*2][3];\n\n\t\t\t\t\tSystem.arraycopy(dp, 0, ndp, 0, n);\n\n\t\t\t\t\tfor(int j = n; j<2*n; j++) {\n\n\t\t\t\t\t\tndp[j][0] = ndp[j][1] = ndp[j][2] = -1;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tdp = ndp;\n\n\t\t\t\t\tn *= 2;\n\n\t\t\t\t}\n\n\t\t\t\tif(dp[left][prev]!=-1) {\n\n\t\t\t\t\treturn dp[left][prev];\n\n\t\t\t\t}\n\n\t\t\t\tBitSet ans = new BitSet();\n\n\t\t\t\tfor(int i = 0; i<3; i++) {\n\n\t\t\t\t\tif(valid(i, prev)) {\n\n\t\t\t\t\t\tans.set(dp(Math.max(0, left-v[i]), i));\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\treturn dp[left][prev] = ans.nextClearBit(0);\n\n\t\t\t}\n\n\n\n\t\t}\n\n\n\n\t\tstatic class State {\n\n\t\t\tint[][] a;\n\n\n\n\t\t\tpublic State(int[][] a) {\n\n\t\t\t\tthis.a = Utilities.deepClone(a);\n\n\t\t\t}\n\n\n\n\t\t\tpublic boolean equals(Object o) {\n\n\t\t\t\tif(this==o) return true;\n\n\t\t\t\tif(o==null||getClass()!=o.getClass()) return false;\n\n\t\t\t\tFAttackOnRedKingdom.State state = (FAttackOnRedKingdom.State) o;\n\n\t\t\t\treturn Arrays.deepEquals(a, state.a);\n\n\t\t\t}\n\n\n\n\t\t\tpublic int hashCode() {\n\n\t\t\t\treturn Arrays.deepHashCode(a);\n\n\t\t\t}\n\n\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(int i) {\n\n\t\t\tprintln(String.valueOf(i));\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 FastReader implements InputReader {\n\n\t\tfinal private int BUFFER_SIZE = 1<<16;\n\n\t\tprivate final DataInputStream din;\n\n\t\tprivate final byte[] buffer;\n\n\t\tprivate int bufferPointer;\n\n\t\tprivate int bytesRead;\n\n\n\n\t\tpublic FastReader(InputStream is) {\n\n\t\t\tdin = new DataInputStream(is);\n\n\t\t\tbuffer = new byte[BUFFER_SIZE];\n\n\t\t\tbufferPointer = bytesRead = 0;\n\n\t\t}\n\n\n\n\t\tpublic int nextInt() {\n\n\t\t\tint ret = 0;\n\n\t\t\tbyte c = skipToDigit();\n\n\t\t\tboolean neg = (c=='-');\n\n\t\t\tif(neg) {\n\n\t\t\t\tc = read();\n\n\t\t\t}\n\n\t\t\tdo {\n\n\t\t\t\tret = ret*10+c-'0';\n\n\t\t\t} while((c = read())>='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\tpublic long nextLong() {\n\n\t\t\tlong ret = 0;\n\n\t\t\tbyte c = skipToDigit();\n\n\t\t\tboolean neg = (c=='-');\n\n\t\t\tif(neg) {\n\n\t\t\t\tc = read();\n\n\t\t\t}\n\n\t\t\tdo {\n\n\t\t\t\tret = ret*10+c-'0';\n\n\t\t\t} while((c = read())>='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 Utilities {\n\n\t\tpublic static void leftShift(T[] arr, int offSet) {\n\n\t\t\tT[] tmp = (T[]) new Object[offSet];\n\n\t\t\tSystem.arraycopy(arr, 0, tmp, 0, offSet);\n\n\t\t\tSystem.arraycopy(arr, offSet, arr, 0, arr.length-offSet);\n\n\t\t\tSystem.arraycopy(tmp, 0, arr, arr.length-offSet, offSet);\n\n\t\t}\n\n\n\n\t\tpublic static int[][] deepClone(int[][] arr) {\n\n\t\t\tint[][] ret = new int[arr.length][];\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; ixkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1\u2264n,m,p\u22642\u22c51051\u2264n,m,p\u22642\u22c5105)\u00a0\u2014 the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1\u2264ai\u22641061\u2264ai\u2264106, 1\u2264cai\u22641091\u2264cai\u2264109)\u00a0\u2014 the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1\u2264bj\u22641061\u2264bj\u2264106, 1\u2264cbj\u22641091\u2264cbj\u2264109)\u00a0\u2014 the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1\u2264xk,yk\u22641061\u2264xk,yk\u2264106, 1\u2264zk\u22641031\u2264zk\u2264103)\u00a0\u2014 defense, attack and the number of coins of the monster kk.OutputPrint a single integer\u00a0\u2014 the maximum profit of the grind.ExampleInputCopy2 3 3\n2 3\n4 7\n2 4\n3 2\n5 11\n1 2 4\n2 1 6\n3 4 6\nOutputCopy1\n","tags":["brute force","data structures","sortings"],"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.List;\nimport java.util.StringTokenizer;\n\npublic class C1320C {\n\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 p = scanner.nextInt();\n var a = new int[n];\n var ca = new int[n];\n var orderA = new Integer[n];\n for (int i = 0; i < n; i++) {\n a[i] = scanner.nextInt();\n ca[i] = scanner.nextInt();\n orderA[i] = i;\n }\n Arrays.sort(orderA, Comparator.comparingInt(i -> a[i]));\n var b = new int[m];\n var cb = new int[m];\n var orderB = new Integer[m];\n for (int i = 0; i < m; i++) {\n b[i] = scanner.nextInt();\n cb[i] = scanner.nextInt();\n orderB[i] = i;\n }\n Arrays.sort(orderB, Comparator.comparingInt(i -> b[i]));\n var x = new int[p];\n var y = new int[p];\n var z = new int[p];\n var orderX = new Integer[p];\n for (int i = 0; i < p; i++) {\n x[i] = scanner.nextInt();\n y[i] = scanner.nextInt();\n z[i] = scanner.nextInt();\n orderX[i] = i;\n }\n Arrays.sort(orderX, Comparator.comparingInt(i -> x[i]));\n\n var acc = new long[4 * m]; \/\/ acc[i,j]\u8868\u793a\u8303\u56f4i\u5230j\u7684\u7d2f\u8ba1\n var max = new long[4 * m]; \/\/ max[i,j]\u8868\u793a\u8303\u56f4i\u5230j\u533a\u95f4\u5185acc\u7684\u6700\u5927\u503c\n Arrays.fill(max, UNTOUCHED);\n for (int ib : orderB) {\n var j = orderB[ib];\n update(acc, max, 0, 0, m - 1, ib, ib, -cb[j]);\n }\n var ix = 0;\n var ans = UNTOUCHED;\n for (var i : orderA) {\n var k = 0;\n while (ix < p && x[(k = orderX[ix])] < a[i]) {\n var startJ = searchFirstGreater(b, orderB, y[k]);\n update(acc, max, 0, 0, m - 1, startJ, m - 1, z[k]);\n ix++;\n }\n ans = Math.max(ans, max[0] - ca[i]);\n }\n writer.println(ans);\n\n scanner.close();\n writer.flush();\n writer.close();\n }\n\n static final long UNTOUCHED = Long.MIN_VALUE;\n\n private static int searchFirstGreater(int[] a, Integer[] order, int key) {\n var low = 0;\n var high = a.length - 1;\n var ans = Integer.MAX_VALUE;\n while (low <= high) {\n var mid = (low + high) >>> 1;\n if (a[order[mid]] <= key) {\n low = mid + 1;\n } else {\n high = mid - 1;\n ans = Math.min(ans, mid);\n }\n }\n return ans;\n }\n\n private static void update(long[] acc, long[] max, int index, int low, int high, int targetLow, int targetHigh,\n int inc) {\n if (targetHigh < low || high < targetLow || targetLow > targetHigh) {\n return;\n }\n if (targetLow <= low && high <= targetHigh) {\n acc[index] += inc;\n if (max[index] == UNTOUCHED) {\n max[index] = 0;\n }\n max[index] += inc;\n return;\n }\n if (low < high) {\n var leftIndex = (index << 1) + 1;\n var rightIndex = leftIndex + 1;\n var mid = (low + high) >>> 1;\n update(acc, max, leftIndex, low, mid, targetLow, targetHigh, inc);\n update(acc, max, rightIndex, mid + 1, high, targetLow, targetHigh, inc);\n max[index] = Math.max(max[index], Math.max(max[leftIndex], max[rightIndex]) + acc[index]);\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}\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":"import java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.IOException;\nimport java.util.InputMismatchException;\nimport java.io.InputStreamReader;\nimport java.io.BufferedOutputStream;\nimport java.util.StringTokenizer;\nimport java.io.Closeable;\nimport java.io.BufferedReader;\nimport java.io.InputStream;\nimport java.io.Flushable;\n\n\/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n *\/\npublic class Main {\n\tstatic class TaskAdapter implements Runnable {\n\t\t@Override\n\t\tpublic void run() {\n\t\t\tInputStream inputStream = System.in;\n\t\t\tOutputStream outputStream = System.out;\n\t\t\tInput in = new Input(inputStream);\n\t\t\tOutput out = new Output(outputStream);\n\t\t\tBIrreducibleAnagrams solver = new BIrreducibleAnagrams();\n\t\t\tsolver.solve(1, in, out);\n\t\t\tout.close();\n\t\t}\n\t}\n\n\tpublic static void main(String[] args) throws Exception {\n\t\tThread thread = new Thread(null, new TaskAdapter(), \"\", 1<<29);\n\t\tthread.start();\n\t\tthread.join();\n\t}\n\tstatic class BIrreducibleAnagrams {\n\t\tpublic BIrreducibleAnagrams() {\n\t\t}\n\n\t\tpublic void solve(int kase, Input in, Output pw) {\n\t\t\tchar[] input = in.next().toCharArray();\n\t\t\tint n = input.length;\n\t\t\tint[][] psum = new int[n+1][26];\n\t\t\tfor(int i = 1; i<=n; i++) {\n\t\t\t\tSystem.arraycopy(psum[i-1], 0, psum[i], 0, 26);\n\t\t\t\tpsum[i][input[i-1]-'a']++;\n\t\t\t}\n\t\t\tint q = in.nextInt();\n\t\t\twhile(q-->0) {\n\t\t\t\tint l = in.nextInt()-1, r = in.nextInt()-1;\n\t\t\t\tif(r-l+1<=1||input[l]!=input[r]) {\n\t\t\t\t\tpw.println(\"Yes\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tint cnt = 0;\n\t\t\t\tfor(int i = 0; i<26; i++) {\n\t\t\t\t\tif(psum[r+1][i]-psum[l][i]>0) {\n\t\t\t\t\t\tcnt++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(cnt>=3) {\n\t\t\t\t\tpw.println(\"Yes\");\n\t\t\t\t}else {\n\t\t\t\t\tpw.println(\"No\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tstatic class Input {\n\t\tBufferedReader br;\n\t\tStringTokenizer st;\n\n\t\tpublic Input(InputStream is) {\n\t\t\tthis(is, 1<<20);\n\t\t}\n\n\t\tpublic Input(InputStream is, int bs) {\n\t\t\tbr = new BufferedReader(new InputStreamReader(is), bs);\n\t\t\tst = null;\n\t\t}\n\n\t\tpublic boolean hasNext() {\n\t\t\ttry {\n\t\t\t\twhile(st==null||!st.hasMoreTokens()) {\n\t\t\t\t\tString s = br.readLine();\n\t\t\t\t\tif(s==null) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tst = new StringTokenizer(s);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}catch(Exception e) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tpublic String next() {\n\t\t\tif(!hasNext()) {\n\t\t\t\tthrow new InputMismatchException();\n\t\t\t}\n\t\t\treturn st.nextToken();\n\t\t}\n\n\t\tpublic int nextInt() {\n\t\t\treturn Integer.parseInt(next());\n\t\t}\n\n\t}\n\n\tstatic class Output implements Closeable, Flushable {\n\t\tpublic StringBuilder sb;\n\t\tpublic OutputStream os;\n\t\tpublic int BUFFER_SIZE;\n\t\tpublic boolean autoFlush;\n\t\tpublic String LineSeparator;\n\n\t\tpublic Output(OutputStream os) {\n\t\t\tthis(os, 1<<16);\n\t\t}\n\n\t\tpublic Output(OutputStream os, int bs) {\n\t\t\tBUFFER_SIZE = bs;\n\t\t\tsb = new StringBuilder(BUFFER_SIZE);\n\t\t\tthis.os = new BufferedOutputStream(os, 1<<17);\n\t\t\tautoFlush = false;\n\t\t\tLineSeparator = System.lineSeparator();\n\t\t}\n\n\t\tpublic void println(String s) {\n\t\t\tsb.append(s);\n\t\t\tprintln();\n\t\t\tif(autoFlush) {\n\t\t\t\tflush();\n\t\t\t}else if(sb.length()>BUFFER_SIZE >> 1) {\n\t\t\t\tflushToBuffer();\n\t\t\t}\n\t\t}\n\n\t\tpublic void println() {\n\t\t\tsb.append(LineSeparator);\n\t\t}\n\n\t\tprivate void flushToBuffer() {\n\t\t\ttry {\n\t\t\t\tos.write(sb.toString().getBytes());\n\t\t\t}catch(IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tsb = new StringBuilder(BUFFER_SIZE);\n\t\t}\n\n\t\tpublic void flush() {\n\t\t\ttry {\n\t\t\t\tflushToBuffer();\n\t\t\t\tos.flush();\n\t\t\t}catch(IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t\tpublic void close() {\n\t\t\tflush();\n\t\t\ttry {\n\t\t\t\tos.close();\n\t\t\t}catch(IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t}\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.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 *\n * @author Manav\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 CRemoveAdjacent solver = new CRemoveAdjacent();\n solver.solve(1, in, out);\n out.close();\n }\n\n static class CRemoveAdjacent {\n public void solve(int testNumber, InputReader in, OutputWriter out) {\n int n = in.nextInt();\n StringBuffer buffer = new StringBuffer(in.next());\n int initialSize = buffer.length();\n boolean isUpdated = true;\n for (int it = 0; it < 110 && isUpdated; it++) {\n int currentSize = buffer.length();\n boolean isBreaked = false;\n for (int i = 25; i >= 1; i += -1) {\n for (int j = 0; j < buffer.length(); j++) {\n int current = buffer.charAt(j) - 'a';\n if (current == i) {\n if (j - 1 >= 0 && buffer.charAt(j - 1) - 'a' == current - 1) {\n buffer.deleteCharAt(j);\n isBreaked = true;\n break;\n }\n if (j + 1 < buffer.length() && buffer.charAt(j + 1) - 'a' == current - 1) {\n buffer.deleteCharAt(j);\n isBreaked = true;\n break;\n }\n\n }\n }\n if (isBreaked) break;\n }\n\n int updatedSize = buffer.length();\n if (currentSize == updatedSize) {\n isUpdated = false;\n }\n }\n out.println(initialSize - buffer.length());\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 String next() {\n return nextString();\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":"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.ArrayList;\n\nimport java.util.Collections;\n\nimport java.util.Scanner;\n\nimport java.io.OutputStreamWriter;\n\nimport java.io.BufferedWriter;\n\nimport java.io.IOException;\n\n\n\npublic class neko {\n\n\n\n\tpublic static void main(String[] args) throws IOException {\n\n\t\tScanner in = new Scanner(System.in);\n\n\t\tBufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); \n\n\t\tint n = in.nextInt();\n\n\t\tint q = in.nextInt();\n\n\t\tint[][] mat = new int[2][n];\n\n\t\tint cnt = 0;\n\n\t\t\n\n\t\tfor(int i = 0; i= 'a'; i--) {\n for (int j = 1; j < sb.length() - 1; j++) {\n if (sb.charAt(j) == i) {\n if (sb.charAt(j - 1) == i - 1 || sb.charAt(j + 1) == i - 1) {\n sb.deleteCharAt(j);\n ok = true;\n break f;\n }\n }\n }\n }\n if (!ok) {\n break;\n }\n }\n out.println(n - (sb.length() - 2));\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 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\n","language":"java"} +{"contest_id":"1312","problem_id":"A","statement":"A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m0){\n\n\t\t\tint m = scan.nextInt();\n\n\t\t\tint n = scan.nextInt();\n\n\t\t\tif(m%n==0){\n\n\t\t\t\tSystem.out.println(\"YES\");\n\n\t\t\t}else{\n\n\t\t\t\tSystem.out.println(\"NO\");\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\n\n}","language":"java"} +{"contest_id":"1296","problem_id":"B","statement":"B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1\u2264x\u2264s1\u2264x\u2264s, buy food that costs exactly xx burles and obtain \u230ax10\u230b\u230ax10\u230b burles as a cashback (in other words, Mishka spends xx burles and obtains \u230ax10\u230b\u230ax10\u230b back). The operation \u230aab\u230b\u230aab\u230b means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1\u2264s\u22641091\u2264s\u2264109) \u2014 the number of burles Mishka initially has.OutputFor each test case print the answer on it \u2014 the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6\n1\n10\n19\n9876\n12345\n1000000000\nOutputCopy1\n11\n21\n10973\n13716\n1111111111\n","tags":["math"],"code":"import java.io.*;\n\nimport java.util.StringTokenizer;\n\n\n\npublic class JavaApplication {\n\n static BufferedReader in;\n\n static BufferedWriter out;\n\n static StringTokenizer st;\n\n static String token;\n\n\n\n public static void main(String[] args) throws IOException {\n\n in = new BufferedReader(new InputStreamReader(System.in));\n\n out=new BufferedWriter(new OutputStreamWriter(System.out));\n\n new JavaApplication().Solve();\n\n out.flush();\n\n }\n\n public String getLine() throws IOException {\n\n return in.readLine();\n\n }\n\n private String getToken() throws IOException {\n\n if (st == null || !st.hasMoreTokens())\n\n st = new StringTokenizer(getLine(), \"\\n \");\n\n return st.nextToken();\n\n }\n\n public int getInt() throws IOException {\n\n return Integer.parseInt(getToken());\n\n }\n\n public long getLong() throws IOException {\n\n return Long.parseLong(getToken());\n\n }\n\n\n\n \/\/ public char getChar() throws IOException {\n\n\/\/\/\/ if (token == null || token.length() == 0)\n\n\/\/\/\/ token = getToken();\n\n\/\/\/\/ char r = token.charAt(0);\n\n\/\/\/\/ token = token.substring(1);\n\n\/\/\/\/ return r;\n\n\/\/ }\n\n public void println() throws IOException {\n\n out.newLine();\n\n }\n\n public void println(Object obj) throws IOException {\n\n if (obj == null)\n\n return;\n\n out.write(String.valueOf(obj));\n\n out.newLine();\n\n }\n\n public void print(Object obj) throws IOException {\n\n if (obj == null)\n\n return;\n\n out.write(String.valueOf(obj));\n\n }\n\n\n\n class Pair{\n\n int a;\n\n int b;\n\n\n\n boolean flag;\n\n public Pair(int a,int b){\n\n this.a=a;\n\n this.b=b;\n\n flag=false;\n\n }\n\n\n\n @Override\n\n public String toString() {\n\n String s=\"\";\n\n s=a+\" \"+b+\", \";\n\n return s;\n\n }\n\n }\n\n\n\n private void Solve() throws IOException {\n\n int t = getInt();\n\n while (t-- > 0) {\n\n int n=getInt();\n\n long spend=0;\n\n while(n>=10){\n\n spend+=10*(n\/10);\n\n n=(n%10)+(n\/10);\n\n }\n\n spend+=n;\n\n println(spend);\n\n }\n\n }\n\n\n\n private int lcm(int n,int m){\n\n return n*m\/gcd(Math.max(n,m),Math.min(n,m));\n\n }\n\n private int gcd(int n,int m){\n\n if(m==0)\n\n return n;\n\n return gcd(m,n%m);\n\n }\n\n}","language":"java"} +{"contest_id":"1300","problem_id":"B","statement":"B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,\u2026,a2k+1][a1,a2,\u2026,a2k+1] of odd number of elements is defined as follows: let [b1,b2,\u2026,b2k+1][b1,b2,\u2026,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u22641041\u2264t\u2264104). The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105)\u00a0\u2014 the number of students halved.The second line of each test case contains 2n2n integers a1,a2,\u2026,a2na1,a2,\u2026,a2n (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3\n1\n1 1\n3\n6 5 4 1 2 3\n5\n13 4 20 13 2 5 8 3 17 16\nOutputCopy0\n1\n5\nNoteIn the first test; there is only one way to partition students\u00a0\u2014 one in each class. The absolute difference of the skill levels will be |1\u22121|=0|1\u22121|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4\u22123|=1|4\u22123|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.","tags":["greedy","implementation","sortings"],"code":"import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.util.Arrays;\nimport java.util.StringTokenizer;\n\npublic class test{\n public static void main(String[] args) throws NumberFormatException, IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n PrintWriter pw = new PrintWriter(System.out);\n\n int t = Integer.parseInt(br.readLine());\n while(t-- > 0){\n int n = Integer.parseInt(br.readLine());\n Integer[] a = new Integer[n*2];\n StringTokenizer tokenizer = new StringTokenizer(br.readLine());\n\n for(int i = 0; i < 2*n; i++){\n a[i] = Integer.parseInt(tokenizer.nextToken());\n }\n\n Arrays.sort(a);\n\n if(n % 2 == 0){\n \/\/ int min = Integer.MAX_VALUE;\n \/\/ for(int i = 2; i < (2*n) - 1; i++){\n \/\/ min = Math.min(min, (int)(a[i] - a[i-1]));\n \/\/ }\n \/\/ pw.println(min);\n pw.println(a[n] - a[n-1]);\n }\n else{\n pw.println(a[n] - a[n-1]);\n }\n }\n\n pw.flush();\n pw.close();\n br.close();\n }\n}","language":"java"} +{"contest_id":"1316","problem_id":"C","statement":"C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+\u22ef+an\u22121xn\u22121f(x)=a0+a1x+\u22ef+an\u22121xn\u22121 and g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1. Let h(x)=f(x)\u22c5g(x)h(x)=f(x)\u22c5g(x). Suppose that h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1\u2264n,m\u2264106,2\u2264p\u22641091\u2264n,m\u2264106,2\u2264p\u2264109), \u00a0\u2014 nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,\u2026,an\u22121a0,a1,\u2026,an\u22121 (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,\u2026,bm\u22121b0,b1,\u2026,bm\u22121 (1\u2264bi\u22641091\u2264bi\u2264109) \u00a0\u2014 bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0\u2264t\u2264n+m\u221220\u2264t\u2264n+m\u22122) \u00a0\u2014 the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2\n1 1 2\n2 1\nOutputCopy1\nInputCopy2 2 999999937\n2 1\n3 1\nOutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.","tags":["constructive algorithms","math","ternary search"],"code":"import java.io.*;\n\nimport java.util.*;\n\n\n\npublic class Main {\n\n \n\n public static void main(String[] args) throws IOException {\n\n Scanner scn = new Scanner(System.in);\n\n OutputWriter out = new OutputWriter(System.out);\n\n \/\/ Always print a trailing \"\\n\" and close the OutputWriter as shown at the end of your output\n\n \n\n \/\/ example:\n\n int n=scn.nextInt();int m=scn.nextInt();int p=scn.nextInt();\n\n int[] a=new int[n];int[] b=new int[m];\n\n int i1=-1;int i2=-1;\n\n for(int i=0;i0)\n\n {\n\n int arr[]=new int[3];\n\n arr[0]=sc.nextInt();\n\n arr[1]=sc.nextInt();\n\n arr[2]=sc.nextInt();\n\n int x=sc.nextInt();\n\n Arrays.sort(arr);\n\n int z=0;\n\n z=(arr[2]-arr[0]) + (arr[2]-arr[1]);\n\n if(z>x)\n\n {\n\n System.out.println(\"No\");\n\n continue;\n\n }\n\n else\n\n {\n\n if((x-z)%3==0)\n\n {\n\n System.out.println(\"Yes\");\n\n }\n\n else System.out.println(\"No\");\n\n }\n\n\n\n }\n\n }\n\n}\n\n","language":"java"} +{"contest_id":"1310","problem_id":"A","statement":"A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A\/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn\u00a0\u2014 the number of news categories (1\u2264n\u22642000001\u2264n\u2264200000).The second line of input consists of nn integers aiai\u00a0\u2014 the number of publications of ii-th category selected by the batch algorithm (1\u2264ai\u22641091\u2264ai\u2264109).The third line of input consists of nn integers titi\u00a0\u2014 time it takes for targeted algorithm to find one new publication of category ii (1\u2264ti\u2264105)1\u2264ti\u2264105).OutputPrint one integer\u00a0\u2014 the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5\n3 7 9 7 8\n5 2 5 7 5\nOutputCopy6\nInputCopy5\n1 2 3 4 5\n1 1 1 1 1\nOutputCopy0\nNoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.","tags":["data structures","greedy","sortings"],"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 cf1310a_2 {\n\n\n\n public static void main(String[] args) throws IOException {\n\n int n = ri(), at[][] = new int[n][2];\n\n r();\n\n for(int i = 0; i < n; ++i) {\n\n at[i][0] = ni();\n\n }\n\n r();\n\n for(int i = 0; i < n; ++i) {\n\n at[i][1] = ni();\n\n }\n\n sort(at, (p, q) -> p[0] - q[0]);\n\n PriorityQueue pq = new PriorityQueue<>((p, q) -> q - p);\n\n int ind = 0, cur = -1;\n\n long sum = 0, ans = 0;\n\n while(ind < n || !pq.isEmpty()) {\n\n if(pq.isEmpty()) {\n\n cur = at[ind][0];\n\n }\n\n while(ind < n && at[ind][0] == cur) {\n\n sum += at[ind][1];\n\n pq.offer(at[ind][1]);\n\n ++ind;\n\n }\n\n sum -= pq.poll();\n\n ans += sum;\n\n ++cur;\n\n }\n\n prln(ans);\n\n close();\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 ~= 2e10\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 randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}\n\n static long hash(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(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 rsort(int[] a) {shuffle(a); sort(a);}\n\n static void rsort(long[] 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 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 static int[] sorted(int[] a) {int[] ans = copy(a); sort(ans); return ans;}\n\n static long[] sorted(long[] a) {long[] ans = copy(a); sort(ans); return ans;}\n\n static int[] rsorted(int[] a) {int[] ans = copy(a); rsort(ans); return ans;}\n\n static long[] rsorted(long[] a) {long[] ans = copy(a); rsort(ans); return ans;}\n\n \/\/ graph util\n\n static List> graph(int n) {List> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}\n\n static List> graph(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;}\n\n static List> graph(int n, int m) throws IOException {return graph(graph(n), m);}\n\n static List> dgraph(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;}\n\n static List> dgraph(List> g, int n, int m) throws IOException {return dgraph(graph(n), m);}\n\n static List> sgraph(int n) {List> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}\n\n static List> sgraph(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;}\n\n static List> sgraph(int n, int m) throws IOException {return sgraph(sgraph(n), m);}\n\n static List> dsgraph(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;}\n\n static List> dsgraph(List> g, int n, int m) throws IOException {return dsgraph(sgraph(n), m);}\n\n static void connect(List> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}\n\n static void connecto(List> g, int u, int v) {g.get(u).add(v);}\n\n static void dconnect(List> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}\n\n static void dconnecto(List> g, int u, int v) {g.get(u).remove(v);}\n\n \/\/ input\n\n static void r() throws IOException {input = new StringTokenizer(__in.readLine());}\n\n static int ri() throws IOException {return Integer.parseInt(__in.readLine());}\n\n static long rl() throws IOException {return Long.parseLong(__in.readLine());}\n\n static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}\n\n static int[] riam1(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()) - 1; return a;}\n\n static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}\n\n static char[] rcha() throws IOException {return __in.readLine().toCharArray();}\n\n static String rline() throws IOException {return __in.readLine();}\n\n static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}\n\n static int ni() {return Integer.parseInt(input.nextToken());}\n\n static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}\n\n static long nl() {return Long.parseLong(input.nextToken());}\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(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\");}\n\n static void flush() {__out.flush();}\n\n static void close() {__out.close();}\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.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 var distinct = Arrays.stream(a).boxed().collect(Collectors.toList());\n Collections.shuffle(distinct);\n var ans = countOps(2, a, n);\n for (int guess = 0; guess < 20 && guess < distinct.size(); guess++) {\n for (int j = -1; j <= 1; j++) {\n var factors = factor(distinct.get(guess) + j);\n for (var factor : factors) {\n var ops = countOps(factor, a, ans);\n ans = Math.min(ans, ops);\n }\n }\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":"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.HashSet;\n\nimport java.util.StringTokenizer;\n\n\n\n\/**\n\n * * @author zhengnaishan\n\n * * @date 2022\/10\/13 9:44\n\n *\/\n\npublic class CF1286 {\n\n\n\n public static void main(String[] args) {\n\n Kattio io = new Kattio();\n\n int n = io.nextInt();\n\n int[] a = new int[n];\n\n int j = (n + 1) \/ 2, o = n \/ 2;\/\/\u8868\u793a\u5947\u6570\u4e2a\u6570\uff0c\u5076\u6570\u4e2a\u6570\n\n for (int i = 0; i < n; i++) {\n\n a[i] = io.nextInt();\n\n if (a[i] != 0) {\n\n if (a[i] % 2 == 0) {\n\n o--;\n\n } else {\n\n j--;\n\n }\n\n }\n\n }\n\n int[][][] f = new int[2][j + 1][o + 1];\/\/\u5f53\u524d\u9762\u7684\u6570\u662f\u5947\u6570\/\u5076\u6570\u65f6\uff0c \u4f7f\u7528j\u4e2a\u5947\u6570\/k\u4e2a\u5076\u6570\u6700\u5c11\u4e0d\u540c\u5bf9\n\n for (int i = 0; i < 2; i++) {\n\n for (int l = 0; l <= j; l++) {\n\n for (int m = 0; m <= o; m++) f[i][l][m] = Integer.MAX_VALUE;\n\n }\n\n }\n\n f[0][0][0] = f[1][0][0] = 0;\n\n for (int i = 0; i < n; i++) {\n\n int ai = a[i];\n\n int[][][] nf = new int[2][j + 1][o + 1];\n\n for (int l = j; l >= 0; l--) {\n\n for (int m = o; m >= 0; m--) {\/\/\u524d\u9762\u7528\u4e86 l\u4e2a\u5947\u6570 m\u4e2a\u5076\u6570\n\n nf[0][l][m] = nf[1][l][m] = Integer.MAX_VALUE;\n\n if (f[0][l][m] != Integer.MAX_VALUE) {\/\/\u524d\u9762\u4e00\u4e2a\u6570\u662f\u5947\u6570\n\n if (a[i] != 0 && a[i] % 2 == 0) {\/\/\u5f53\u524d\u662f\u5076\u6570\n\n nf[1][l][m] = Math.min(nf[1][l][m], f[0][l][m] + 1);\n\n } else if (a[i] != 0 && a[i] % 2 == 1) {\/\/\u5f53\u524d\u6570\u662f\u5947\u6570\n\n nf[0][l][m] = Math.min(nf[0][l][m], f[0][l][m]);\n\n }\n\n if (ai == 0 && l < j) {\/\/\u5f53\u524d\u6570\u7f6e\u4e3a\u5947\u6570\n\n nf[0][l + 1][m] = Math.min(nf[0][l + 1][m], f[0][l][m]);\n\n }\n\n if (ai == 0 && m < o) {\/\/\u5f53\u524d\u6570\u7f6e\u4e3a\u5076\u6570\n\n nf[1][l][m + 1] = Math.min(nf[1][l][m + 1], f[0][l][m] + 1);\n\n }\n\n }\n\n if (f[1][l][m] != Integer.MAX_VALUE) {\/\/\u524d\u9762\u4e00\u4e2a\u6570\u662f\u5076\u6570\n\n if (a[i] != 0 && ai % 2 == 0) {\/\/\u5f53\u524d\u662f\u5076\u6570\n\n nf[1][l][m] = Math.min(nf[1][l][m], f[1][l][m]);\n\n } else if (ai != 0 && ai % 2 == 1) {\/\/\u5f53\u524d\u662f\u5947\u6570\n\n nf[0][l][m] = Math.min(nf[0][l][m], f[1][l][m] + 1);\n\n }\n\n if (ai == 0 && l < j) {\/\/\u5c06\u5f53\u524d\u6570\u7f6e\u4e3a\u5947\u6570\n\n nf[0][l + 1][m] = Math.min(nf[0][l + 1][m], f[1][l][m] + 1);\n\n }\n\n if (ai == 0 && m < o) {\/\/\u5c06\u5f53\u524d\u6570\u7f6e\u4e3a\u5076\u6570\n\n nf[1][l][m + 1] = Math.min(nf[1][l][m + 1], f[1][l][m]);\n\n }\n\n }\n\n }\n\n }\n\n f = nf;\n\n }\n\n int ans = Integer.MAX_VALUE;\n\n for (int i = 0; i <= j; i++) {\n\n for (int l = 0; l <= o; l++) {\n\n ans = Math.min(ans, f[0][i][l]);\n\n ans = Math.min(ans, f[1][i][l]);\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":"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\u2264x0) {\n\n\t\t\tlong a=sc.nextLong(),m=sc.nextLong();\n\n\t\t\tm\/=gcd(a,m);\n\n\t\t\tSystem.out.println(phi(m));\n\n\t\t}\n\n\t\n\n\t\t\n\n\t\t\n\n\t}\n\n\tstatic long phi(long n) {\n\n\t long result = n;\n\n\t for (long i = 2; i * i <= n; i++) {\n\n\t if (n % i == 0) {\n\n\t while (n % i == 0)\n\n\t n \/= i;\n\n\t result -= result \/ i;\n\n\t }\n\n\t }\n\n\t if (n > 1)\n\n\t result -= result \/ n;\n\n\t return result;\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\n\n\t\n\n\tstatic int[] reverseSort(int a[]) {\n\n\t\tArrayList al=new ArrayList<>();\n\n\t\tfor(int i:a)al.add(i);\n\n\t\tCollections.sort(al,Collections.reverseOrder());\n\n\t\tfor(int i=0;i al=new ArrayList<>();\n\n\t\tfor(int i:a)al.add(i);\n\n\t\tCollections.reverse(al);\n\n\t\tfor(int i=0;i al=new ArrayList<>();\n\n\t\tfor(char i:a)al.add(i);\n\n\t\tCollections.reverse(al);\n\n\t\tfor(int i=0;i al=new ArrayList<>();\n\n\t\tfor(int i:a)al.add(i);\n\n\t\tCollections.sort(al);\n\n\t\tfor(int i=0;i mp = new TreeMap<>();\n\n\t\tpublic void solve(int T){\n\n\t\t\twhile(T-->0){\n\n\t\t\t\tn = in.nextInt();\n\n\t\t\t\tm = in.nextInt();\n\n\t\t\t\tvalue = new long[n];\n\n\t\t\t\tfor(int i = 0; i < n; i++) value[i] = in.nextLong();\n\n\t\t\t\tif(n==1){\n\n\t\t\t\t\tin.nextInt();\n\n\t\t\t\t\tin.nextInt();\n\n\t\t\t\t\tcout.print(value[0]);\n\n\t\t\t\t\tcout.write('\\n');\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\t}\n\n\t\t\t\tArrayList[] G = Utils.ListArray(n);\n\n\t\t\t\tfor(int i = 0; i < m; i++){\n\n\t\t\t\t\tint u = in.nextInt() - 1, v = in.nextInt() - 1;\n\n\t\t\t\t\tG[v].add(u);\n\n\t\t\t\t}\n\n\t\t\t\tmp.clear();\n\n\t\t\t\tfor(int i = 0; i < n; i++){\n\n\t\t\t\t\tif(G[i].isEmpty()) continue;\n\n\t\t\t\t\tG[i].sort((x,y)->{ return x-y; });\n\n\t\t\t\t\tint hx = G[i].hashCode();\n\n\t\t\t\t\tif(!mp.containsKey(hx)) mp.put(hx,value[i]);\n\n\t\t\t\t\telse mp.put(hx,mp.get(hx)+value[i]);\n\n\t\t\t\t}\n\n\t\t\t\tLong ans = 0l;\n\n\t\t\t\tfor(long v : mp.values()) ans = gcd(ans,v);\n\n\t\t\t\tcout.write(ans.toString()+'\\n');\n\n\t\t\t}\n\n\t\t}\n\n\t\tprivate long gcd(long A, long B){\n\n\t\t\treturn B!=0 ? gcd(B,A%B) : A;\n\n\t\t}\n\n\t}\n\n\tprivate static class Utils{\n\n\t\tpublic static ArrayList[] ListArray(int _size){\n\n\t\t\tArrayList[] ret = new ArrayList[_size];\n\n\t\t\tfor(int i = 0; i < _size; i++) ret[i] = new ArrayList<>();\n\n\t\t\treturn ret;\n\n\t\t}\n\n\t}\n\n\tpublic static class FastScanner {\n\n\t\tBufferedReader br;\n\n\t\tStringTokenizer st;\n\n\t\tpublic FastScanner(InputStream in) {\n\n\t\t\t\tbr = new BufferedReader(new InputStreamReader(in));\n\n\t\t}\n\n\t\tpublic int nextInt() {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\t\tpublic boolean hasMoreTokens() {\n\n\t\t\twhile (st == null || !st.hasMoreElements()) {\n\n\t\t\t\tString line = null;\n\n\t\t\t\ttry {\n\n\t\t\t\t\tline = br.readLine();\n\n\t\t\t\t} catch (IOException e) {\n\n\t\t\t\t\treturn false;\n\n\t\t\t\t}\n\n\t\t\t\tif (line == null) {\n\n\t\t\t\t\treturn false;\n\n\t\t\t\t}\n\n\t\t\t\tst = new StringTokenizer(line);\n\n\t\t\t}\n\n\t\t\treturn true;\n\n\t\t}\n\n\t\tpublic String next() {\n\n\t\t\twhile (st == null || !st.hasMoreElements()) {\n\n\t\t\t\tString line = null;\n\n\t\t\t\ttry {\n\n\t\t\t\t\tline = br.readLine();\n\n\t\t\t\t} catch (IOException e) {\n\n\t\t\t\t}\n\n\t\t\t\tst = new StringTokenizer(line);\n\n\t\t\t}\n\n\t\t\treturn st.nextToken();\n\n\t\t}\n\n\t\tpublic long nextLong() {\n\n\t\t\treturn Long.parseLong(next());\n\n\t\t}\n\n\t\tpublic double nextDouble() {\n\n\t\t\treturn Double.parseDouble(next());\n\n\t\t}\n\n\t\tpublic int[] nextIntArray(int n) {\n\n\t\t\tint[] ret = new int[n];\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tret[i] = nextInt();\n\n\t\t\t}\n\n\t\t\treturn ret;\n\n\t\t}\n\n\t\tpublic long[] nextLongArray(int n) {\n\n\t\t\tlong[] ret = new long[n];\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tret[i] = nextLong();\n\n\t\t\t}\n\n\t\t\treturn ret;\n\n\t\t}\n\n\t}\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.Scanner;\n\npublic class radio {\n\n public static void main(String[] args){\n\n\n\n Scanner input = new Scanner(System.in);\n\n\n\n byte n = input.nextByte();\n\n int[] robot1 = new int[n];\n\n int[] robot2 = new int[n];\n\n\n\n for(int i=0;i0ai>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.io.*;\n\n\n\npublic class _practise {\n\n\n\n\tpublic static void main(String args[])\n\n\t{\n\n\n\n\t\tFastReader in=new FastReader();\n\n\t\tPrintWriter so = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));\n\n\t\tint t = in.nextInt();\n\n\t\t\/\/int t = 1;\n\n\t\twhile(t-->0)\n\n\t\t{\n\n int n = in.nextInt();\n\n int d = in.nextInt();\n\n int a[] = new int[n];\n\n for(int i=0 ; i al = new ArrayList(); \n\n\t\t\tStringBuilder sb = new StringBuilder();\n\n\t\t\tSet a = new HashSet();\n\n\t\t\tso.println(\"HELLO\");*\/\n\n\t}\n\n\n\n\tstatic class FastReader\n\n\t{ \n\n\t\tBufferedReader br; \n\n\t\tStringTokenizer st; \n\n\n\n\t\tpublic FastReader() \n\n\t\t{ \n\n\t\t\tbr = new BufferedReader(new InputStreamReader(System.in)); \n\n\t\t} \n\n\n\n\t\tString next() \n\n\t\t{ \n\n\t\t\twhile (st == null || !st.hasMoreElements()) \n\n\t\t\t{ \n\n\t\t\t\ttry\n\n\t\t\t\t{ \n\n\t\t\t\t\tst = new StringTokenizer(br.readLine()); \n\n\t\t\t\t} \n\n\t\t\t\tcatch (IOException e) \n\n\t\t\t\t{ \n\n\t\t\t\t\te.printStackTrace(); \n\n\t\t\t\t} \n\n\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{ \n\n\t\t\treturn Integer.parseInt(next()); \n\n\t\t} \n\n\n\n\t\tlong nextLong() \n\n\t\t{ \n\n\t\t\treturn Long.parseLong(next()); \n\n\t\t} \n\n\n\n\t\tdouble nextDouble() \n\n\t\t{ \n\n\t\t\treturn Double.parseDouble(next()); \n\n\t\t} \n\n\n\n\t\tint[] readIntArray(int n)\n\n\t\t{\n\n\t\t\tint a[]=new int[n];\n\n\t\t\tfor(int i=0;i= 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 }\n\n return buf[curChar++];\n\n }\n\n\n\n public int nextInt() {\n\n int c = read();\n\n while (isSpaceChar(c)) {\n\n c = read();\n\n }\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 }\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 boolean isSpaceChar(int c) {\n\n if (filter != null) {\n\n return filter.isSpaceChar(c);\n\n }\n\n return isWhitespace(c);\n\n }\n\n\n\n public static boolean isWhitespace(int c) {\n\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n\n }\n\n\n\n public int[] nextIntArray(int n) {\n\n int[] array = new int[n];\n\n for (int i = 0; i < n; ++i) array[i] = nextInt();\n\n return array;\n\n }\n\n\n\n public interface SpaceCharFilter {\n\n public boolean isSpaceChar(int ch);\n\n\n\n }\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 close() {\n\n writer.close();\n\n }\n\n\n\n public void println(int i) {\n\n writer.println(i);\n\n }\n\n\n\n }\n\n}\n\n\n\n","language":"java"} +{"contest_id":"1313","problem_id":"C2","statement":"C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n\u2264500000n\u2264500000The outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1\u2264ai\u2264mi1\u2264ai\u2264mi). Also there mustn't be integers jj and kk such that jaiai stack=new Stack<>();\n\n for(int i=1;i<=n;i++){\n\n int p=0;\n\n while(!stack.isEmpty()){\n\n int top=stack.peek();\n\n if(a[top]>=a[i]){\n\n stack.pop();\n\n }\n\n else{\n\n p=top;\n\n break;\n\n }\n\n }\n\n stack.push(i);\n\n left[i]=left[p]+1l*(i-p)*a[i];\n\n\/\/ System.out.println(stack.toString());\n\n }\n\n stack=new Stack<>();\n\n for(int i=n;i>=1;i--){\n\n int p=n+1;\n\n while(!stack.isEmpty()){\n\n int top=stack.peek();\n\n if(a[top]>=a[i]){\n\n stack.pop();\n\n }\n\n else{\n\n p=top;\n\n break;\n\n }\n\n }\n\n stack.push(i);\n\n right[i]=right[p]+1l*(p-i)*a[i];\n\n }\n\n int maxIndex=-1;\n\n long max=0;\n\n for(int i=1;i<=n;i++){\n\n if(right[i]+left[i]-a[i]>max){\n\n max=right[i]+left[i]-a[i];\n\n maxIndex=i;\n\n }\n\n\/\/ System.out.println(left[i]+\" \"+right[i]);\n\n }\n\n int ans[]=new int[n+1];\n\n int m=a[maxIndex];\n\n ans[maxIndex]=a[maxIndex];\n\n for(int i=maxIndex-1;i>=1;i--){\n\n if(a[i]>m){\n\n ans[i]=m;\n\n }\n\n else{\n\n ans[i]=a[i];\n\n m=ans[i];\n\n }\n\n }\n\n m=a[maxIndex];\n\n for(int i=maxIndex+1;i<=n;i++){\n\n if(a[i]>m){\n\n ans[i]=m;\n\n }\n\n else{\n\n ans[i]=a[i];\n\n m=ans[i];\n\n }\n\n }\n\n StringBuilder print=new StringBuilder();\n\n for(int i=1;i<=n;i++){\n\n print.append(ans[i]+\" \");\n\n }\n\n System.out.println(print.toString());\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\npublic class CF2111{\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\tscan.nextInt();\n\n\t\t\tStringBuffer stringBuffer = new StringBuffer(scan.next());\n\n\t\t\tSystem.out.println(getReducedString(stringBuffer));\n\n\t\t\ttestCases--;\n\n\t\t}\n\n\t}\n\n\tpublic static String getReducedString(StringBuffer stringBuffer){\n\n\t\twhile(stringBuffer.length()>=1 && (stringBuffer.charAt(stringBuffer.length()-1)-'0')%2==0){\n\n\t\t\tstringBuffer.deleteCharAt(stringBuffer.length()-1);\n\n\t\t}\n\n\t\t\/\/string buffer now contains last character odd.\n\n\t\tint i = stringBuffer.length()-2;\n\n\t\tboolean flag = false;\n\n\t\twhile(i >= 0){\n\n\t\t\tif((stringBuffer.charAt(i)-'0')%2==1){\n\n\t\t\t\tstringBuffer.delete(0, i);\n\n\t\t\t\tflag = true;\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\ti--;\n\n\t\t}\n\n\t\tif(flag\t){\n\n\t\t\treturn stringBuffer.toString();\n\n\t\t}\n\n\t\treturn \"-1\";\n\n\t}\n\n}","language":"java"} +{"contest_id":"1325","problem_id":"C","statement":"C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n\u22122n\u22122 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2\u2264n\u22641052\u2264n\u2264105)\u00a0\u2014 the number of nodes in the tree.Each of the next n\u22121n\u22121 lines contains two space-separated integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n\u22121n\u22121 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3\n1 2\n1 3\nOutputCopy0\n1\nInputCopy6\n1 2\n1 3\n2 4\n2 5\n5 6\nOutputCopy0\n3\n2\n4\n1NoteThe tree from the second sample:","tags":["constructive algorithms","dfs and similar","greedy","trees"],"code":"import java.awt.image.AreaAveragingScaleFilter;\n\nimport java.awt.image.MemoryImageSource;\n\nimport java.io.*;\n\nimport java.sql.Array;\n\nimport java.util.*;\n\nimport java.util.StringTokenizer;\n\n\n\npublic class cf799 {\n\n static class FastReader{\n\n BufferedReader br;\n\n StringTokenizer st;\n\n public FastReader(){\n\n br=new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n String next(){\n\n while(st==null || !st.hasMoreTokens()){\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 int nextInt(){\n\n return Integer.parseInt(next());\n\n }\n\n long nextLong(){\n\n return Long.parseLong(next());\n\n }\n\n double nextDouble(){\n\n return Double.parseDouble(next());\n\n }\n\n String nextLine(){\n\n String str=\"\";\n\n try {\n\n str=br.readLine().trim();\n\n } catch (Exception e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n static class FastWriter {\n\n private final BufferedWriter bw;\n\n\n\n public FastWriter() {\n\n this.bw = new BufferedWriter(new OutputStreamWriter(System.out));\n\n }\n\n\n\n public void print(Object object) throws IOException {\n\n bw.append(\"\" + object);\n\n }\n\n\n\n public void println(Object object) throws IOException {\n\n print(object);\n\n bw.append(\"\\n\");\n\n }\n\n\n\n public void close() throws IOException {\n\n bw.close();\n\n }\n\n }\n\n\n\n\n\n static int [] parent=new int[100001];\n\n static int [] rank=new int[100001];\n\n\n\n public static void makeSet(){\n\n for(int i=0;i {\n\n public int compare(int[] a, int[] b) {\n\n return b[0] - a[0];\n\n }\n\n}\n\n\n\n\n\n public static void main(String[] args) {\n\n try {\n\n FastReader sc = new FastReader();\n\n FastWriter out = new FastWriter();\n\n\n\n\n\n\n\n int n=sc.nextInt();\n\n int []arr=new int[n+1];\n\n ArrayList air=new ArrayList<>();\n\n for(int i=0;i=3 ){\n\n num=air.get(i).a;\n\n break;\n\n }\n\n if(arr[air.get(i).b]>=3 ){\n\n num=air.get(i).b;\n\n break;\n\n }\n\n }\n\n for(int i=0;i0){\n\n ans=((ans%1000000007)*n)%1000000007;\n\nr--;\n\nn--;\n\n }\n\n return ans;\n\n }\n\n\n\n\n\n\n\n public static int lcm(int a,int b){\n\n\n\n return (a\/gcd(a,b))*b;\n\n }\n\n\n\n private static int gcd(int a, int b) {\n\n if(b==0)return a;\n\n return gcd(b,a%b);\n\n }\n\n static class Pair {\n\n int a;\n\n int b;\n\n \/\/ int c;\n\n\n\n\n\n\n\n Pair(int a, int b ) {\n\n this.a = a;\n\n this.b = b;\n\n \/\/ this.c=c;\n\n }\n\n }\n\n static class Pair2 {\n\n String a;\n\n int b;\n\n \/\/ int c;\n\n\n\n\n\n\n\n Pair2(String a, int b ) {\n\n this.a = a;\n\n this.b = b;\n\n \/\/ this.c=c;\n\n }\n\n }\n\n static class ArrayKey {\n\n private int[] array;\n\n\n\n public ArrayKey(int[] array) {\n\n this.array = array;\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 ArrayKey arrayKey = (ArrayKey) o;\n\n return Arrays.equals(array, arrayKey.array);\n\n }\n\n\n\n @Override\n\n public int hashCode() {\n\n return Arrays.hashCode(array);\n\n }\n\n }\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":"import java.io.*;\n\nimport java.util.*;\n\n\n\npublic class Main implements Runnable {\n\n static boolean use_n_tests = false;\n\n static int stack_size = 1 << 27;\n\n static long mod = 1_000_000_007;\n\n\n\n void solve(FastScanner in, PrintWriter out, int testNumber) {\n\n int n, m;\n\n n = in.nextInt();\n\n m = in.nextInt();\n\n List[] graph = new ArrayList[n];\n\n List[] inverseg = new ArrayList[n];\n\n for (int i = 0; i < n; i++) {\n\n graph[i] = new ArrayList<>();\n\n inverseg[i] = new ArrayList<>();\n\n }\n\n for (int i = 0; i < m; i++) {\n\n int v, u;\n\n v = in.nextInt() - 1;\n\n u = in.nextInt() - 1;\n\n graph[v].add(u);\n\n inverseg[u].add(v);\n\n }\n\n int q;\n\n q = in.nextInt();\n\n int[] p = new int[q];\n\n for (int i = 0; i < p.length; i++) {\n\n p[i] = in.nextInt();\n\n }\n\n\n\n int[] distance = new int[n];\n\n Deque deq = new ArrayDeque<>();\n\n deq.addLast(p[q - 1] - 1);\n\n boolean[] mark = new boolean[n];\n\n while (!deq.isEmpty()) {\n\n int v = deq.pollFirst();\n\n mark[v] = true;\n\n for (int x : inverseg[v]) {\n\n if (!mark[x]) {\n\n distance[x] = distance[v] + 1;\n\n deq.addLast(x);\n\n mark[x] = true;\n\n }\n\n }\n\n }\n\n int ansMin = 0;\n\n int ansMax = 0;\n\n\n\n for (int i = 1; i < p.length; i++) {\n\n int v = p[i - 1] - 1;\n\n int u = p[i] - 1;\n\n if (distance[u] > distance[v] - 1) {\n\n ansMin++;\n\n ansMax++;\n\n } else {\n\n for (int j = 0; j < graph[v].size(); j++) {\n\n int w = graph[v].get(j);\n\n if (w != u && distance[w] == distance[v] - 1) {\n\n ansMax++;\n\n break;\n\n }\n\n }\n\n }\n\n }\n\n out.println(ansMin + \" \" + ansMax);\n\n }\n\n\n\n \/\/ ****************************** template code ***********\n\n\n\n static class Range {\n\n int l, r;\n\n int id;\n\n\n\n public int getL() {\n\n return l;\n\n }\n\n\n\n public int getR() {\n\n return r;\n\n }\n\n\n\n public Range(int l, int r, int id) {\n\n this.l = l;\n\n this.r = r;\n\n this.id = id;\n\n }\n\n }\n\n\n\n static class Array {\n\n static Range[] readRanges(int n, FastScanner in) {\n\n Range[] result = new Range[n];\n\n for (int i = 0; i < n; i++) {\n\n result[i] = new Range(in.nextInt(), in.nextInt(), i);\n\n }\n\n return result;\n\n }\n\n\n\n static public Integer[] read(int n, FastScanner in) {\n\n Integer[] out = new Integer[n];\n\n for (int i = 0; i < out.length; i++) {\n\n out[i] = in.nextInt();\n\n }\n\n return out;\n\n }\n\n\n\n static public int[] readint(int n, FastScanner in) {\n\n int[] out = new int[n];\n\n for (int i = 0; i < out.length; i++) {\n\n out[i] = in.nextInt();\n\n }\n\n return out;\n\n }\n\n }\n\n\n\n class Graph {\n\n List> create(int n) {\n\n List> graph = new ArrayList<>();\n\n for (int i = 0; i < n; i++) {\n\n graph.add(new ArrayList<>());\n\n }\n\n return graph;\n\n }\n\n }\n\n\n\n class FastScanner {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public FastScanner(InputStream io) {\n\n br = new BufferedReader(new InputStreamReader(io));\n\n }\n\n\n\n public 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 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\n\n void run_t_tests() {\n\n int t = in.nextInt();\n\n int i = 0;\n\n while (t-- > 0) {\n\n solve(in, out, i++);\n\n }\n\n }\n\n\n\n void run_one() {\n\n solve(in, out, -1);\n\n }\n\n\n\n @Override\n\n public void run() {\n\n in = new FastScanner(System.in);\n\n out = new PrintWriter(System.out);\n\n if (use_n_tests) {\n\n run_t_tests();\n\n } else {\n\n run_one();\n\n }\n\n out.close();\n\n }\n\n\n\n static FastScanner in;\n\n static PrintWriter out;\n\n\n\n public static void main(String[] args) throws InterruptedException {\n\n Thread thread = new Thread(null, new Main(), \"\", stack_size);\n\n thread.start();\n\n thread.join();\n\n }\n\n}","language":"java"} +{"contest_id":"1316","problem_id":"B","statement":"B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1\u2264k\u2264n1\u2264k\u2264n). For ii from 11 to n\u2212k+1n\u2212k+1, reverse the substring s[i:i+k\u22121]s[i:i+k\u22121] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a\u2260ba\u2260b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u226450001\u2264t\u22645000). The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u226450001\u2264n\u22645000)\u00a0\u2014 the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s\u2032s\u2032 achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1\u2264k\u2264n1\u2264k\u2264n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6\n4\nabab\n6\nqwerty\n5\naaaaa\n6\nalaska\n9\nlfpbavjsm\n1\np\nOutputCopyabab\n1\nertyqw\n3\naaaaa\n1\naksala\n6\navjsmbpfl\n5\np\n1\nNoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11. ","tags":["brute force","constructive algorithms","implementation","sortings","strings"],"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\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 = fastReader.nextInt();\n while(tt-- > 0) {\n int n = fastReader.nextInt();\n char c[] =fastReader.nextLine().toCharArray();\n char ans[] = c;\n int k = 1;\n for(int i = 1; i < n; i++){\n char cur [] = new char[n];\n int index = 0;\n for(int j = i ;j < n; j++,index++) cur[index] = c[j];\n if((n-(i+1)+1)%2 == 1){\n for(int j = i-1; j>=0 ; j-- , index++) cur[index] = c[j];\n }else{\n for(int j = 0; j < i ; j++ , index++) cur[index] = c[j];\n }\n if(isSmall(ans,cur)){\n ans = cur;\n k = (i+1);\n }\n }\n out.println(String.valueOf(ans));\n out.println(k);\n\n }\n out.close();\n }\n\n private static boolean isSmall(char[] ans, char[] cur) {\n int n = ans.length;\n for(int i = 0; i < n;i++){\n if(cur[i] < ans[i]) return true;\n if(cur[i] > ans[i]) return false;\n }\n return false;\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":"1310","problem_id":"B","statement":"B. Double Eliminationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe biggest event of the year \u2013 Cota 2 world championship \"The Innernational\" is right around the corner. 2n2n teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from 11 to 2n2n and will play games one-on-one. All teams start in the upper bracket.All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.Lower bracket starts with 2n\u221212n\u22121 teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round 2k2k teams play a game with each other (teams are split into games by team numbers). 2k\u221212k\u22121 loosing teams are eliminated from the championship, 2k\u221212k\u22121 winning teams are playing 2k\u221212k\u22121 teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have 2k\u221212k\u22121 teams remaining. See example notes for better understanding.Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.You are a fan of teams with numbers a1,a2,...,aka1,a2,...,ak. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?InputFirst input line has two integers n,kn,k\u00a0\u2014 2n2n teams are competing in the championship. You are a fan of kk teams (2\u2264n\u226417;0\u2264k\u22642n2\u2264n\u226417;0\u2264k\u22642n).Second input line has kk distinct integers a1,\u2026,aka1,\u2026,ak\u00a0\u2014 numbers of teams you're a fan of (1\u2264ai\u22642n1\u2264ai\u22642n).OutputOutput single integer\u00a0\u2014 maximal possible number of championship games that include teams you're fan of.ExamplesInputCopy3 1\n6\nOutputCopy6\nInputCopy3 3\n1 7 8\nOutputCopy11\nInputCopy3 4\n1 3 5 7\nOutputCopy14\nNoteOn the image; each game of the championship is denoted with an English letter (aa to nn). Winner of game ii is denoted as WiWi, loser is denoted as LiLi. Teams you're a fan of are highlighted with red background.In the first example, team 66 will play in 6 games if it looses the first upper bracket game (game cc) and wins all lower bracket games (games h,j,l,mh,j,l,m). In the second example, teams 77 and 88 have to play with each other in the first game of upper bracket (game dd). Team 88 can win all remaining games in upper bracket, when teams 11 and 77 will compete in the lower bracket. In the third example, your favourite teams can play in all games of the championship. ","tags":["dp","implementation"],"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.io.Writer;\n\nimport java.io.OutputStreamWriter;\n\nimport java.util.InputMismatchException;\n\nimport java.io.IOException;\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 TaskB solver = new TaskB();\n\n solver.solve(1, in, out);\n\n out.close();\n\n }\n\n\n\n static class TaskB {\n\n\n\n static final int inf = 1000 * 1000 * 1000;\n\n int[] A;\n\n int[][] d;\n\n\n\n public void solve(int testNumber, InputReader in, OutputWriter out) {\n\n int n = in.nextInt();\n\n int k = in.nextInt();\n\n A = new int[(1 << (n + 1))];\n\n for (int i = 0; i < k; ++i) {\n\n A[(1 << n) + in.nextInt() - 1] = 1;\n\n }\n\n if (k == 0) {\n\n out.printLine(0);\n\n return;\n\n }\n\n for (int i = A.length - 1; i > 0; --i) {\n\n A[i \/ 2] += A[i];\n\n }\n\n d = new int[4][A.length];\n\n for (int i = 0; i < d.length; ++i) {\n\n Arrays.fill(d[i], -inf - 1);\n\n }\n\n int res = Math.max(calc(1, 1), Math.max(calc(1, 2), calc(1, 3)));\n\n if (res < 0) {\n\n res = 0;\n\n }\n\n ++res;\n\n out.printLine(res);\n\n }\n\n\n\n int calc(int v, int s) {\n\n if (s == 0) {\n\n return 0;\n\n }\n\n if (A[v] == 0) {\n\n return -inf;\n\n }\n\n if (s == 3 && A[v] < 2) {\n\n return -inf;\n\n }\n\n if (v * 4 >= A.length) {\n\n return 1;\n\n }\n\n if (d[s][v] != -inf - 1) {\n\n return d[s][v];\n\n }\n\n int res = -inf;\n\n for (int s1 = 0; s1 <= 3; ++s1) {\n\n for (int s2 = 0; s2 <= 3; ++s2) {\n\n int val1 = calc(v * 2, s1);\n\n int val2 = calc(v * 2 + 1, s2);\n\n for (int mask = 0; mask < 8; ++mask) {\n\n int cur = val1 + val2;\n\n int w1 = mask % 2 == 0 ? s1 % 2 : s2 % 2;\n\n int l1 = mask % 2 == 0 ? s2 % 2 : s1 % 2;\n\n if (w1 + l1 > 0) {\n\n ++cur;\n\n }\n\n\n\n int w2 = (mask >> 1) % 2 == 0 ? (s1 >> 1) % 2 : (s2 >> 1) % 2;\n\n int l2 = (mask >> 1) % 2 == 0 ? (s2 >> 1) % 2 : (s1 >> 1) % 2;\n\n if (w2 + l2 > 0) {\n\n ++cur;\n\n }\n\n\n\n int w3 = (mask >> 2) % 2 == 0 ? l1 : w2;\n\n if (l1 + w2 > 0) {\n\n ++cur;\n\n }\n\n if (w3 * 2 + w1 != s) {\n\n continue;\n\n }\n\n if (cur > res) {\n\n res = cur;\n\n }\n\n }\n\n }\n\n }\n\n \/\/System.err.println(s + \" \" + v + \": \" + res);\n\n d[s][v] = res;\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 }\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 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":"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\u2264r0){\n\n String s=sc.next();\n\n boolean z=false;\n\n int first=s.length();\n\n for(int i=0;i=0;i--){\n\n if(s.charAt(i)=='1'){\n\n last=i;\n\n break;\n\n }\n\n }\n\n int total=0;\n\n for(int i=first;i<=last;i++){\n\n if(s.charAt(i)=='0')total++;\n\n }\n\n System.out.println(total);\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":"import java.util.Scanner;\npublic class template {\n static Scanner sc = new Scanner(System.in);\n public static void main(String[] args) {\n int t = sc.nextInt();\n for (int i = 0; i < t; i++) {\n solve();\n }\n }\n public static void solve() {\n int n = sc.nextInt();\n int[] input = new int[n];\n for (int i = 0; i < n; i++) {\n input[i] = sc.nextInt();\n }\n int even = input[0] % 2;\n for (int i = 0; i < n; i++) {\n if (input[i] % 2 != even) {\n System.out.println(\"NO\");\n return;\n }\n }\n System.out.println(\"YES\");\n return;\n }\n}\n","language":"java"} +{"contest_id":"13","problem_id":"B","statement":"B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1\u2009\/\u20094 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1\u2009\/\u20094). InputThe first line contains one integer t (1\u2009\u2264\u2009t\u2009\u2264\u200910000) \u2014 the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers \u2014 coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print \u00abYES\u00bb (without quotes), if the segments form the letter A and \u00abNO\u00bb otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES","tags":["geometry","implementation"],"code":"import java.io.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.util.StringTokenizer;\n\n \n\npublic class AnotA {\n\n \n\n\tlong x1,x2;\n\n\tlong y1,y2;\n\n\t\n\n\tAnotA(String s){\n\n\t\tStringTokenizer st = new StringTokenizer(s);\n\n\t\tthis.x1 =Integer.parseInt(st.nextToken());\n\n\t\tthis.y1 =Integer.parseInt(st.nextToken());\n\n\t\tthis.x2 =Integer.parseInt(st.nextToken());\n\n\t\tthis.y2 =Integer.parseInt(st.nextToken());\n\n\t}\n\n\tpublic static void main(String[] args) throws IOException {\n\n\t\tBufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n\t\tint n = Integer.parseInt(br.readLine());\n\n\t\tfor(int i=0; iMath.max(a.x1, a.x2)||yMath.max(a.y1, a.y2))\n\n\t\t\treturn false;\n\n\t\t\/\/check ratio between parts\n\n\t\tint xpart = (int) Math.abs(a.x1-a.x2);\n\n\t\tint ypart = (int) Math.abs(a.y1-a.y2);\n\n\t\tint xmin = (int) Math.min(Math.abs(a.x1-x), Math.abs(a.x2-x));\n\n\t\tint ymin = (int) Math.min(Math.abs(a.y1-y), Math.abs(a.y2-y));\n\n\t\t\n\n\t\treturn xpart<=5*xmin&&ypart<=5*ymin&& (long) (x-a.x2)*(a.y1-a.y2)==(long)(y-a.y2)*(a.x1-a.x2);\n\n\t}\n\n\tpublic static boolean checkConstraints(AnotA a, AnotA b, AnotA c) {\n\n\t\tif(a.x1==b.x1&&a.y1==b.y1) {\n\n\t\t\t\n\n\t\t\treturn getAngle(a.x2,a.y2,b.x2,b.y2,a.x1,a.y1);\n\n\t\t}\n\n\t\telse if(a.x2==b.x1&&a.y2==b.y1) {\n\n\t\t\t\n\n\t\t\treturn getAngle(a.x1, a.y1, b.x2, b.y2, a.x2, a.y2);\n\n\t\t}\n\n\t\telse if(a.x1==b.x2&&a.y1==b.y2) {\n\n\t\t\t\n\n\t\t\treturn getAngle(a.x2, a.y2, b.x1, b.y1, a.x1, a.y1);\n\n\t\t}\n\n\t\telse if(a.x2==b.x2&&a.y2==b.y2) {\n\n\t\t\t\n\n\t\t\treturn getAngle(a.x1, a.y1, b.x1, b.y1, a.x2, a.y2);\n\n\t\t}\n\n\t\treturn false;\n\n\t\t\n\n\t}\n\n\t\n\n\tpublic static boolean getAngle(long x1, long y1, long x2, long y2, long x3, long y3) {\n\n\t\tboolean collinear =areCollinear( x1, y1, x2, y2, x3, y3);\n\n\t\t\/\/check angle <= 90\n\n\t\tlong a13 = (long) (x1-x3) * (x1-x3) + (long) (y1-y3) *(y1-y3); \n\n\t\tlong a23 = (long) (x2-x3) * (x2-x3) + (long) (y2-y3) *(y2-y3);\n\n\t\tlong a12 = (long) (x1-x2) * (x1-x2) + (long) (y1-y2) *(y1-y2); \n\n\t\treturn !collinear&&a13+a23>=a12;\n\n\t}\n\n\t\n\n\tprivate static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) {\n\n\t\tlong area = (long) (x1-x3)*(y2-y3) - (long) (x2-x3)*(y1-y3);\n\n\t\treturn area==0?true:false;\n\n\t\t\n\n\t}\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.IOException;\n\nimport java.io.InputStream;\n\nimport java.io.PrintWriter;\n\nimport java.math.BigDecimal;\n\nimport java.math.RoundingMode;\n\nimport java.util.*;\n\nimport java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;\n\nimport java.beans.Visibility;\n\nimport java.io.File;\n\nimport java.io.FileDescriptor;\n\nimport java.io.FileOutputStream;\n\nimport java.io.OutputStream;\n\nimport java.io.UncheckedIOException;\n\nimport java.lang.Thread.State;\n\nimport java.lang.reflect.Field;\n\nimport java.nio.CharBuffer;\n\nimport java.nio.charset.CharacterCodingException;\n\nimport java.nio.charset.CharsetEncoder;\n\nimport java.nio.charset.StandardCharsets;\n\n\n\npublic class Main {\n\n\tstatic final long MOD1=1000000007;\n\n\tstatic final long MOD=998244353;\n\n\tstatic long ans=0;\n\n\tpublic static void main(String[] args){\n\n\t\tPrintWriter out = new PrintWriter(System.out);\n\n\t\tInputReader sc=new InputReader(System.in);\n\n\t\tint n = sc.nextInt();\n\n\t\tint m = sc.nextInt();\n\n\t\tint[] a = sc.nextIntArray(m);\n\n\t\tint[] min = new int[n];\n\n\t\tint[] max = new int[n];\n\n\t\tArrays.setAll(min, k->k+1);\n\n\t\tArrays.setAll(max, k->k+1);\n\n\t\tint[] last = new int[n];\n\n\t\tArrays.fill(last, -1);\n\n\t\tSegTree seg1 = new SegTree(n, (x,y)->x+y, 0);\n\n\t\tSegTree seg2 = new SegTree(m, (x,y)->x+y, 0);\n\n\t\tfor (int i = 0; i < m; i++) {\n\n\t\t\tint id = a[i]-1;\n\n\t\t\tmin[id] = 1;\n\n\t\t\tif (last[id]==-1) {\n\n\t\t\t\tmax[id] += seg1.prod(a[i], n);\n\n\t\t\t\tseg1.set(id, 1);\n\n\t\t\t\tseg2.set(i, 1);\n\n\t\t\t}else {\n\n\t\t\t\tseg2.set(last[id], 0);\n\n\t\t\t\tseg2.set(i, 1);\n\n\t\t\t\tmax[id] = Math.max(max[id], seg2.prod(last[id], i)+1);\n\n\t\t\t}\n\n\t\t\tlast[id] = i;\n\n\t\t}\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tif (last[i]==-1) {\n\n\t\t\t\tmax[i] += seg1.prod(i, n);\n\n\t\t\t}else {\n\n\t\t\t\tmax[i] = Math.max(max[i], seg2.prod(last[i], m));\n\n\t\t\t}\n\n\t\t}\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tout.println(min[i]+\" \"+max[i]);\n\n\t\t}\n\n\t\tout.flush();\n\n\t} \n\n\tstatic class SegTree {\n\n\t final int MAX;\n\n\n\n\t final int N;\n\n\t final java.util.function.BinaryOperator op;\n\n\t final S E;\n\n\n\n\t final S[] data;\n\n\n\n\t @SuppressWarnings(\"unchecked\")\n\n\t public SegTree(int n, java.util.function.BinaryOperator op, S e) {\n\n\t this.MAX = n;\n\n\t int k = 1;\n\n\t while (k < n) k <<= 1;\n\n\t this.N = k;\n\n\t this.E = e;\n\n\t this.op = op;\n\n\t this.data = (S[]) new Object[N << 1];\n\n\t java.util.Arrays.fill(data, E);\n\n\t }\n\n\n\n\t public SegTree(S[] dat, java.util.function.BinaryOperator op, S e) {\n\n\t this(dat.length, op, e);\n\n\t build(dat);\n\n\t }\n\n\n\n\t private void build(S[] dat) {\n\n\t int l = dat.length;\n\n\t System.arraycopy(dat, 0, data, N, l);\n\n\t for (int i = N - 1; i > 0; i--) {\n\n\t data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]);\n\n\t }\n\n\t }\n\n\n\n\t public void set(int p, S x) {\n\n\t exclusiveRangeCheck(p);\n\n\t data[p += N] = x;\n\n\t p >>= 1;\n\n\t while (p > 0) {\n\n\t data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]);\n\n\t p >>= 1;\n\n\t }\n\n\t }\n\n\n\n\t public S get(int p) {\n\n\t exclusiveRangeCheck(p);\n\n\t return data[p + N];\n\n\t }\n\n\n\n\t public S prod(int l, int r) {\n\n\t if (l > r) {\n\n\t throw new IllegalArgumentException(\n\n\t String.format(\"Invalid range: [%d, %d)\", l, r)\n\n\t );\n\n\t }\n\n\t inclusiveRangeCheck(l);\n\n\t inclusiveRangeCheck(r);\n\n\t S sumLeft = E;\n\n\t S sumRight = E;\n\n\t l += N; r += N;\n\n\t while (l < r) {\n\n\t if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]);\n\n\t if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight);\n\n\t l >>= 1; r >>= 1;\n\n\t }\n\n\t return op.apply(sumLeft, sumRight);\n\n\t }\n\n\n\n\t public S allProd() {\n\n\t return data[1];\n\n\t }\n\n\n\n\t public int maxRight(int l, java.util.function.Predicate f) {\n\n\t inclusiveRangeCheck(l);\n\n\t if (!f.test(E)) {\n\n\t throw new IllegalArgumentException(\"Identity element must satisfy the condition.\");\n\n\t }\n\n\t if (l == MAX) return MAX;\n\n\t l += N;\n\n\t S sum = E;\n\n\t do {\n\n\t l >>= Integer.numberOfTrailingZeros(l);\n\n\t if (!f.test(op.apply(sum, data[l]))) {\n\n\t while (l < N) {\n\n\t l = l << 1;\n\n\t if (f.test(op.apply(sum, data[l]))) {\n\n\t sum = op.apply(sum, data[l]);\n\n\t l++;\n\n\t }\n\n\t }\n\n\t return l - N;\n\n\t }\n\n\t sum = op.apply(sum, data[l]);\n\n\t l++;\n\n\t } while ((l & -l) != l);\n\n\t return MAX;\n\n\t }\n\n\n\n\t public int minLeft(int r, java.util.function.Predicate f) {\n\n\t inclusiveRangeCheck(r);\n\n\t if (!f.test(E)) {\n\n\t throw new IllegalArgumentException(\"Identity element must satisfy the condition.\");\n\n\t }\n\n\t if (r == 0) return 0;\n\n\t r += N;\n\n\t S sum = E;\n\n\t do {\n\n\t r--;\n\n\t while (r > 1 && (r & 1) == 1) r >>= 1;\n\n\t if (!f.test(op.apply(data[r], sum))) {\n\n\t while (r < N) {\n\n\t r = r << 1 | 1;\n\n\t if (f.test(op.apply(data[r], sum))) {\n\n\t sum = op.apply(data[r], sum);\n\n\t r--;\n\n\t }\n\n\t }\n\n\t return r + 1 - N;\n\n\t }\n\n\t sum = op.apply(data[r], sum);\n\n\t } while ((r & -r) != r);\n\n\t return 0;\n\n\t }\n\n\n\n\t private void exclusiveRangeCheck(int p) {\n\n\t if (p < 0 || p >= MAX) {\n\n\t throw new IndexOutOfBoundsException(\n\n\t String.format(\"Index %d out of bounds for the range [%d, %d).\", p, 0, MAX)\n\n\t );\n\n\t }\n\n\t }\n\n\n\n\t private void inclusiveRangeCheck(int p) {\n\n\t if (p < 0 || p > MAX) {\n\n\t throw new IndexOutOfBoundsException(\n\n\t String.format(\"Index %d out of bounds for the range [%d, %d].\", p, 0, MAX)\n\n\t );\n\n\t }\n\n\t }\n\n\t}\n\n\tstatic class InputReader {\n\n\t\tprivate InputStream in;\n\n\t\tprivate byte[] buffer = new byte[1024];\n\n\t\tprivate int curbuf;\n\n\t\tprivate int lenbuf;\n\n\t\tpublic InputReader(InputStream in) {\n\n\t\t\tthis.in = in;\n\n\t\t\tthis.curbuf = this.lenbuf = 0;\n\n\t\t}\n\n\t\tpublic boolean hasNextByte() {\n\n\t\t\tif (curbuf >= lenbuf) {\n\n\t\t\t\tcurbuf = 0;\n\n\t\t\t\ttry {\n\n\t\t\t\t\tlenbuf = in.read(buffer);\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 (lenbuf <= 0)\n\n\t\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t\treturn true;\n\n\t\t}\n\n\n\n\t\tprivate int readByte() {\n\n\t\t\tif (hasNextByte())\n\n\t\t\t\treturn buffer[curbuf++];\n\n\t\t\telse\n\n\t\t\t\treturn -1;\n\n\t\t}\n\n\n\n\t\tprivate boolean isSpaceChar(int c) {\n\n\t\t\treturn !(c >= 33 && c <= 126);\n\n\t\t}\n\n\n\n\t\tprivate void skip() {\n\n\t\t\twhile (hasNextByte() && isSpaceChar(buffer[curbuf]))\n\n\t\t\t\tcurbuf++;\n\n\t\t}\n\n\n\n\t\tpublic boolean hasNext() {\n\n\t\t\tskip();\n\n\t\t\treturn hasNextByte();\n\n\t\t}\n\n\n\n\t\tpublic String next() {\n\n\t\t\tif (!hasNext())\n\n\t\t\t\tthrow new NoSuchElementException();\n\n\t\t\tStringBuilder sb = new StringBuilder();\n\n\t\t\tint b = readByte();\n\n\t\t\twhile (!isSpaceChar(b)) {\n\n\t\t\t\tsb.appendCodePoint(b);\n\n\t\t\t\tb = readByte();\n\n\t\t\t}\n\n\t\t\treturn sb.toString();\n\n\t\t}\n\n\n\n\t\tpublic int nextInt() {\n\n\t\t\tif (!hasNext())\n\n\t\t\t\tthrow new NoSuchElementException();\n\n\t\t\tint c = readByte();\n\n\t\t\twhile (isSpaceChar(c))\n\n\t\t\t\tc = readByte();\n\n\t\t\tboolean minus = false;\n\n\t\t\tif (c == '-') {\n\n\t\t\t\tminus = true;\n\n\t\t\t\tc = readByte();\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 = res * 10 + c - '0';\n\n\t\t\t\tc = readByte();\n\n\t\t\t} while (!isSpaceChar(c));\n\n\t\t\treturn (minus) ? -res : res;\n\n\t\t}\n\n\n\n\t\tpublic long nextLong() {\n\n\t\t\tif (!hasNext())\n\n\t\t\t\tthrow new NoSuchElementException();\n\n\t\t\tint c = readByte();\n\n\t\t\twhile (isSpaceChar(c))\n\n\t\t\t\tc = readByte();\n\n\t\t\tboolean minus = false;\n\n\t\t\tif (c == '-') {\n\n\t\t\t\tminus = true;\n\n\t\t\t\tc = readByte();\n\n\t\t\t}\n\n\t\t\tlong 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 = res * 10 + c - '0';\n\n\t\t\t\tc = readByte();\n\n\t\t\t} while (!isSpaceChar(c));\n\n\t\t\treturn (minus) ? -res : res;\n\n\t\t}\n\n\n\n\t\tpublic double nextDouble() {\n\n\t\t\treturn Double.parseDouble(next());\n\n\t\t}\n\n\n\n\t\tpublic int[] nextIntArray(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\t\tpublic double[] nextDoubleArray(int n) {\n\n\t\t\tdouble[] a = new double[n];\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t\ta[i] = nextDouble();\n\n\t\t\treturn a;\n\n\t\t}\n\n\t\tpublic long[] nextLongArray(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\tpublic char[][] nextCharMap(int n, int m) {\n\n\t\t\tchar[][] map = new char[n][m];\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t\tmap[i] = next().toCharArray();\n\n\t\t\treturn map;\n\n\t\t}\n\n\t}\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 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 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\tpublic static void main(String[] args) \n\n\t{\n\n\t\tFastReader sc = new FastReader();\n\n\t PrintWriter out = new PrintWriter(System.out);\n\n\/\/ int t=sc.nextInt();\n\n\/\/ while(t-->0)\n\n\/\/ {\n\n\/\/ \t\n\n\/\/ }\n\n\t String s=sc.next();\n\n\t int n=s.length();\n\n\t int l=s.indexOf('(');\n\n\t int r=s.lastIndexOf(')');\n\n\t int c1=1,c2=1;\n\n\t ArrayList x1=new ArrayList();\n\n\t ArrayList x2=new ArrayList();\n\n\t if(lc2)\n\n\t \t{\n\n\t \t\twhile(s.charAt(r)!=')' && l<=r)\n\n\t \t\t{\n\n\t \t\t\tr--;\n\n\t \t\t}\n\n\t \t\tx2.add(r);\n\n\t \t\tr--;\n\n\t \t\tc2++;\n\n\t \t}\n\n\t \telse if(c2>c1)\n\n\t \t{\n\n\t \t\twhile(s.charAt(l)!='(' && l<=r)\n\n\t \t\t{\n\n\t \t\t\tl++;\n\n\t \t\t}\n\n\t \t\tx1.add(l);\n\n\t \t\tl++;\n\n\t \t\tc1++;\n\n\t \t}\n\n\t \telse\n\n\t \t{\n\n\t \t\twhile(l<=r && c1==c2)\n\n\t \t\t{\n\n\t \t\t\tif(s.charAt(l)=='(' && l<=r)\n\n\t \t\t\t{\n\n\t \t\t\t\tc1++;\n\n\t \t\t\t\tx1.add(l);\n\n\t \t\t\t\tl++;\n\n\t \t\t\t}\n\n\t \t\t\telse if(s.charAt(r)==')' && l<=r)\n\n\t \t\t\t{\n\n\t \t\t\t\tc2++;\n\n\t \t\t\t\tx2.add(r);\n\n\t \t\t\t\tr--;\n\n\t \t\t\t}\n\n\t \t\t\telse\n\n\t \t\t\t{\n\n\t \t\t\t\tl++;\n\n\t \t\t\t\tr--;\n\n\t \t\t\t}\n\n\t \t\t}\n\n\t \t}\n\n\t }\n\n\t if(!x1.isEmpty() && !x2.isEmpty())\n\n\t {\n\n\t\t Collections.sort(x1);\n\n\t\t \tCollections.sort(x2);\n\n\t\t while((long)x1.get(x1.size()-1)>(long)x2.get(0))\n\n\t\t {\n\n\t\t \tx1.remove(x1.size()-1);\n\n\t\t \tx2.remove(0);\n\n\t\t }\n\n\t\t while(x1.get(0)<0)\n\n\t\t {\n\n\t\t \tx1.remove(0);\n\n\t\t }\n\n\t \twhile(x1.size()>=1 && x2.size()>=1 &&(long)x1.get(x1.size()-1)==(long)x2.get(0))\n\n\t \t{\n\n\t \t\tx1.remove(x1.size()-1);\n\n\t \t\tx2.remove(0);\n\n\t \t}\n\n\t\t \tint k1=x1.size(),k2=x2.size();\n\n\t\t \twhile(x1.size()>Math.min(k1,k2))\n\n\t\t \t{\n\n\t\t \t\tx1.remove(x1.size()-1);\n\n\t\t \t}\n\n\t \twhile(x2.size()>Math.min(k1,k2))\n\n\t \t{\n\n\t \t\tx2.remove(0);\n\n\t\t }\n\n\t }\n\n\t if(x1.isEmpty() || x2.isEmpty())\n\n\t {\n\n\t \tout.println(0);\n\n\t }\n\n\t else\n\n\t {\n\n\t\t \tout.println(1);\n\n\t\t \tout.println(x1.size()+x2.size());\n\n\t\t \tfor(int i=0;i graph[];\n\n static q qs[];\n\n\n\n static void dfs(int s, int id, int p, int di){\n\n d[s][id] = p;\n\n for(int i : graph[id]){\n\n if(i == p) continue;\n\n dfs(s, i, id, di+1);\n\n }\n\n }\n\n\n\n public static void main(String args[]) throws IOException{\n\n BufferedReader eat = new BufferedReader(new InputStreamReader(System.in));\n\n PrintWriter moo = new PrintWriter(System.out);\n\n N = Integer.parseInt(eat.readLine());\n\n graph = new ArrayList[N];\n\n for(int i = 0; i < N; i++) graph[i] = new ArrayList();\n\n u = new int[N-1];\n\n v = new int[N-1];\n\n for(int i = 0; i < N-1; i++){\n\n StringTokenizer st = new StringTokenizer(eat.readLine());\n\n int x = Integer.parseInt(st.nextToken()) - 1, y = Integer.parseInt(st.nextToken()) - 1;\n\n u[i] = x;\n\n v[i] = y;\n\n graph[x].add(y);\n\n graph[y].add(x);\n\n }\n\n d = new int[N][N];\n\n for(int i = 0; i < N; i++){\n\n dfs(i, i, -1, 0);\n\n }\n\n M = Integer.parseInt(eat.readLine());\n\n qs = new q[M];\n\n for(int i = 0; i < M; i++){\n\n StringTokenizer st = new StringTokenizer(eat.readLine());\n\n int a = Integer.parseInt(st.nextToken()) - 1, b = Integer.parseInt(st.nextToken()) - 1, g = Integer.parseInt(st.nextToken());\n\n qs[i] = new q(a, b, g);\n\n }\n\n Arrays.sort(qs);\n\n be = new int[N][N];\n\n boolean f = false;\n\n for(int i = 0; i < M; i++){\n\n int a = qs[i].a, b = qs[i].b, g = qs[i].g;\n\n f = false;\n\n while(a != b){\n\n int nxt = d[b][a];\n\n if(be[a][nxt] <= g){\n\n f = true;\n\n be[a][nxt] = be[nxt][a] = g;\n\n }\n\n a = nxt;\n\n }\n\n if(!f){\n\n break;\n\n }\n\n }\n\n if(f){\n\n for(int i = 0; i < N-1; i++){\n\n int x = be[u[i]][v[i]];\n\n moo.print((x == 0 ? 1 : x) + \" \");\n\n }\n\n moo.println();\n\n }else{\n\n moo.println(-1);\n\n }\n\n eat.close(); moo.close();\n\n }\n\n\n\n static class q implements Comparable{\n\n int a, b, g;\n\n q(int a, int b, int g){\n\n this.a = a;\n\n this.b = b;\n\n this.g = g;\n\n }\n\n public int compareTo(q x){\n\n return x.g - this.g;\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":"import java.util.*;\n\nimport java.io.*;\n\n\n\n\/\/ -------------------------Main class-------------------------\n\n\n\npublic class Main\n\n{\n\n\n\n \/\/ private final int V;\n\n \/\/ private final List> adj;\n\n \/\/ public Main(int V)\n\n \/\/ {\n\n \/\/ this.V=V;\n\n \/\/ adj=new ArrayList<>(V);\n\n \/\/ for(int i=0;i());\n\n \/\/ }\n\n\n\n \/\/ private void addEdge(int src, int dest)\n\n \/\/ {\n\n \/\/ adj.get(src).add(dest);\n\n \/\/ }\n\n\n\n \/\/ private boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack)\n\n \/\/ {\n\n \/\/ if(recStack[i])\n\n \/\/ return true;\n\n \/\/ if(visited[i])\n\n \/\/ return false;\n\n \/\/ visited[i]=true;\n\n \/\/ recStack[i]=true;\n\n \/\/ List children=adj.get(i);\n\n \/\/ for(Integer c: children)\n\n \/\/ {\n\n \/\/ if(isCyclicUtil(c,visited,recStack))\n\n \/\/ return true;\n\n \/\/ }\n\n \/\/ recStack[i]=false;\n\n \/\/ return false;\n\n \/\/ }\n\n\n\n \/\/ private boolean isCyclic()\n\n \/\/ {\n\n \/\/ boolean[] visited=new boolean[V];\n\n \/\/ boolean[] recStack=new boolean[V];\n\n \/\/ for(int i=0;i 0) {\n\n\n\n\t\t\t\/\/ If y is odd, multiply x\n\n\t\t\t\/\/ with result\n\n\t\t\tif (y % 2 == 1)\n\n\t\t\t\tres = (res * x) % p;\n\n\n\n\t\t\t\/\/ y must be even now\n\n\t\t\ty = y >> 1; \/\/ y = y\/2\n\n\t\t\tx = (x * x) % p;\n\n\t\t}\n\n\n\n\t\treturn res;\n\n\t}\n\n\n\n\t\/\/ Returns n^(-1) mod p\n\n\tstatic long modInverse(long n, long p)\n\n\t{\n\n\t\treturn power(n, p - 2, p);\n\n\t}\n\n\n\n\t\/\/ Returns nCr % p using Fermat's\n\n\t\/\/ little theorem.\n\n\tstatic long nCrModPFermat(long n, long r,\n\n\t\t\t\t\t\t\tlong p,long[] fac)\n\n\t{\n\n\n\n\t\tif (n factors=getFactors(x);\n\n factors.add(0,1L);\n\n factors.add(x);\n\n long ans1=1;\n\n long ans2=x;\n\n for(int j=0;j0)\n\n {\n\n if(n%2==1)\n\n res=(res%mod*pow2%mod)%mod;\n\n pow2=(pow2%mod*pow2%mod)%mod;\n\n n>>=1;\n\n }\n\n return res;\n\n }\n\n\n\n \/\/ Time Complexity : n*r\n\n static long nCrModpDP(long n, long r, long p)\n\n {\n\n long c[]=new long[(int)r+1];\n\n c[0]=1;\n\n for(long j=1;j<=n;j++)\n\n {\n\n for(long k=Math.min(j,r);k>0;k--)\n\n c[(int)k]=(c[(int)k]%p+c[(int)k-1]%p)%p;\n\n }\n\n return c[(int)r];\n\n }\n\n\n\n \/\/ Time Complexity : log(n)\n\n static long nCrModpLucas(long n, long r, long p)\n\n {\n\n if(r==0)\n\n return 1;\n\n long ni=n%p;\n\n long ri=r%p;\n\n return (nCrModpLucas(n\/p, r\/p, p)%p*nCrModpDP(ni, ri, p)%p)%p;\n\n }\n\n\n\n \/\/ Time Complexity : log(mod)\n\n static long inverseMOD(long x, long mod) {\n\n if(mod==0)\n\n return 1;\n\n if(mod%2==1)\n\n return(x*inverseMOD(x, mod - 1))%MOD;\n\n else\n\n return inverseMOD((x * x) % MOD, mod\/2);\n\n }\n\n\n\n \/\/ Time Complexity : log(max(a,b))\n\n static long bitwiseAND(long a, long b)\n\n {\n\n long shiftcount=0;\n\n while(a!=b&&a>0)\n\n {\n\n shiftcount++;\n\n a=a>>1;\n\n b=b>>1;\n\n }\n\n return (long)(a<> al, boolean[] visited)\n\n {\n\n visited[j]=true;\n\n for(int x=0;x al=new ArrayList<>();\n\n while(n>1)\n\n {\n\n if(n%x==0)\n\n {\n\n \/\/ if(!al.contains(x))\n\n \/\/ al.add(x);\n\n count++;\n\n n\/=x;\n\n }\n\n else\n\n x++;\n\n }\n\n return count;\n\n }\n\n\n\n \/\/ Time Complexity : log(n)\n\n static ArrayList primeFactorization(int x, int[] spf)\n\n {\n\n HashMap map=new HashMap<>();\n\n ArrayList al=new ArrayList<>();\n\n while(x!=1)\n\n {\n\n if(!al.contains(spf[x]))\n\n al.add(spf[x]);\n\n map.put(spf[x],map.getOrDefault(spf[x],0)+1);\n\n x\/=spf[x];\n\n }\n\n return al;\n\n \/\/ return map;\n\n }\n\n\n\n \/\/ Time Complexity : n*10\n\n static int[][] getBitMap(int[] a)\n\n {\n\n int n=a.length;\n\n int[][] bit_map=new int[n][32];\n\n for(int j=0;j sieveOfEratosthenes(int n)\n\n {\n\n boolean prime[]=new boolean[n+1];\n\n for(int j=0;j<=n;j++)\n\n prime[j]=true;\n\n for(long p=2;p*p<=n;p++)\n\n {\n\n if(prime[(int)p])\n\n {\n\n for(long j=p*p;j<=n;j+=p)\n\n prime[(int)j]=false;\n\n }\n\n }\n\n ArrayList al=new ArrayList<>();\n\n for(long j=2;j<=n;j++)\n\n {\n\n if(prime[(int)j])\n\n al.add((int)j);\n\n }\n\n return al;\n\n }\n\n\n\n \/\/ Time Complexity : n\n\n static boolean sortedIncreasing(int[] a)\n\n {\n\n int f=0;\n\n for(int j=1;ja[j-1])\n\n f=1;\n\n }\n\n return f==0?true:false;\n\n }\n\n\n\n \/\/ Time Complexity : sqrt(n)\n\n static ArrayList getFactors(long n)\n\n {\n\n ArrayList al=new ArrayList<>();\n\n \/\/ int count=0;\n\n for(long i=1;i*i<=n;i++)\n\n {\n\n if(n%i==0)\n\n {\n\n al.add(i);\n\n \/\/ count++;\n\n if(n\/i!=i)\n\n {\n\n al.add(n\/i);\n\n \/\/ count++;\n\n }\n\n }\n\n }\n\n return al;\n\n \/\/ return count;\n\n }\n\n\n\n \/\/ Time Complexity : n*log(n)\n\n static void sort(int[] a)\n\n {\n\n\t\tArrayList l=new ArrayList<>();\n\n\t\tfor (int i:a)\n\n 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)\n\n l.add(i);\n\n\t\tCollections.sort(l);\n\n\t\tfor(int i=0;i0&&curr<=x)\n\n {\n\n ans=mid;\n\n l=mid+1;\n\n }\n\n else\n\n r=mid-1;\n\n }\n\n return ans;\n\n }\n\n\n\n \/\/ Time Complexity : log(n*logn)\n\n static long getRemainderSum(long[] a, long totalsum, int x)\n\n {\n\n long k=0;\n\n outer :\n\n for(int mul=x;;mul+=x)\n\n {\n\n int l=0;\n\n int r=a.length-1;\n\n int index=-1;\n\n while(l<=r)\n\n {\n\n int mid=l+(r-l)\/2;\n\n if(a[mid]>=mul)\n\n {\n\n index=mid;\n\n r=mid-1;\n\n }\n\n else\n\n l=mid+1;\n\n }\n\n if(index==-1)\n\n break outer;\n\n else\n\n k+=a.length-index;\n\n }\n\n return (totalsum-k*x);\n\n }\n\n\n\n \/\/ -------------------------Input class-------------------------\n\n\n\n static class FastReader\n\n {\n\n BufferedReader br; \n\n StringTokenizer st;\n\n public FastReader()\n\n {\n\n br=new BufferedReader(new InputStreamReader(System.in)); \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 int nextInt()\n\n {\n\n return Integer.parseInt(next());\n\n }\n\n long nextLong()\n\n {\n\n return Long.parseLong(next());\n\n }\n\n double nextDouble()\n\n {\n\n return Double.parseDouble(next());\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\n\n}\n\n\n\n\/\/ -------------------------Other classes-------------------------\n\n\n\nclass Pair\n\n{\n\n int first=0;\n\n int second=0;\n\n char ch='a';\n\n int index=-1;\n\n Pair(int x, int y)\n\n {\n\n first=x;\n\n second=y;\n\n }\n\n Pair(char x, int y)\n\n {\n\n ch=x;\n\n index=y;\n\n }\n\n}\n\n\n\nclass NewComparator implements Comparator\n\n{\n\n public int compare(Pair p1, Pair p2)\n\n {\n\n return Long.compare(p2.second, p1.second);\n\n }\n\n}","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":"import java.io.*;\n\nimport java.util.StringTokenizer;\n\n\n\nimport static java.lang.Double.parseDouble;\n\nimport static java.lang.Integer.parseInt;\n\nimport static java.lang.Long.parseLong;\n\nimport static java.lang.System.in;\n\nimport static java.lang.System.out;\n\n\n\npublic class National_Project {\n\n public static void main(String[] args) {\n\n try {\n\n FastReader in = new FastReader();\n\n FastWriter out = new FastWriter();\n\n int test = in.nextInt();\n\n while (test > 0) {\n\n \/\/Your Code Here\n\n int length = in.nextInt();\n\n int good = in.nextInt();\n\n int bad = in.nextInt();\n\n calc(length, good, bad);\n\n test--;\n\n }\n\n out.close();\n\n } catch (Exception e) {\n\n return;\n\n }\n\n\n\n }\n\n\n\n private static void calc(int length, int good_duration, int bad_duration) {\n\n long required = (length + 1) \/ 2;\n\n long good = good_duration;\n\n long ans = 0;\n\n \/\/long good_count=0;\n\n if (length < good_duration) {\n\n ans = length;\n\n } else {\n\n ans += (required\/good_duration)*(good_duration+bad_duration);\n\n if(required%good_duration==0)\n\n {\n\n ans-=bad_duration;\n\n }\n\n else\n\n {\n\n ans+=(required%good_duration);\n\n }\n\n\n\n\n\n }\n\n out.println(Math.max(ans,length));\n\n }\n\n\n\n private static long gcd(long a, long b) {\n\n if (a == 0) {\n\n return b;\n\n } else {\n\n return (gcd(b % a, a));\n\n }\n\n }\n\n\n\n static class FastWriter {\n\n private final BufferedWriter bw;\n\n\n\n public FastWriter() {\n\n this.bw = new BufferedWriter(new OutputStreamWriter(out));\n\n }\n\n\n\n public void print(Object object) throws IOException {\n\n bw.append(\"\" + object);\n\n }\n\n\n\n public void println(Object object) throws IOException {\n\n print(object);\n\n bw.append(\"\\n\");\n\n }\n\n\n\n public void close() throws IOException {\n\n bw.close();\n\n }\n\n }\n\n\n\n public static class FastReader {\n\n BufferedReader br;\n\n StringTokenizer st;\n\n\n\n public FastReader() {\n\n br = new BufferedReader(new InputStreamReader(in));\n\n }\n\n\n\n String next() {\n\n while (st == null || !st.hasMoreTokens()) {\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 parseInt(next());\n\n }\n\n\n\n long nextLong() {\n\n return parseLong(next());\n\n }\n\n\n\n double nextDouble() {\n\n return parseDouble(next());\n\n }\n\n\n\n String nextLine() {\n\n String str = \"\";\n\n try {\n\n str = br.readLine().trim();\n\n } catch (Exception e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n}\n\n","language":"java"} +{"contest_id":"1291","problem_id":"B","statement":"B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,\u2026,ana1,\u2026,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1\u2264k\u2264n1\u2264k\u2264n such that a1ak+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.math.BigInteger;\n\nimport java.util.*;\n\nimport static java.lang.Math.*;\n\n\n\n\n\npublic class Main{\n\n public static void main(String args[]){\n\n Scanner sc=new Scanner(System.in);\n\n int testcase=sc.nextInt();\n\n for(int tc=1;tc<=testcase;tc++){\n\n \/\/System.out.print(\"Case #\"+tc+\": \");\n\n int n = sc.nextInt();\n\n int a[] = new int[n];\n\n for(int i=0;i=k;i--){\n\n if(a[i] < n-1-i){\n\n flag = false;\n\n break;\n\n }\n\n }\n\n if(flag)\n\n System.out.println(\"Yes\");\n\n else\n\n System.out.println(\"No\");\n\n }\n\n sc.close();\n\n }\n\n static long fact(long n)\n\n {\n\n \n\n \/\/ single line to find factorial\n\n return (n == 1 || n == 0) ? 1 : n * fact(n - 1);\n\n \n\n }\n\n static boolean isSorted(int a[]){\n\n for(int i=1;i= 0)\n\n return Arrays.binarySearch(arr, key);\n\n int mid, N = arr.length;\n\n \n\n \/\/ Initialise starting index and\n\n \/\/ ending index\n\n int low = 0;\n\n int high = i;\n\n \n\n \/\/ Till low is less than high\n\n while (low < high && low != N) {\n\n \/\/ Find the index of the middle element\n\n mid = low + (high - low) \/ 2;\n\n \n\n \/\/ If key is greater than or equal\n\n \/\/ to arr[mid], then find in\n\n \/\/ right subarray\n\n if (key >= arr[mid]) {\n\n low = mid + 1;\n\n }\n\n \n\n \/\/ If key is less than arr[mid]\n\n \/\/ then find in left subarray\n\n else {\n\n high = mid;\n\n }\n\n }\n\n \n\n return low;\n\n }\n\n static int lower_bound(int[] arr, int key, int i)\n\n {\n\n if(Arrays.binarySearch(arr, key) >= 0)\n\n return Arrays.binarySearch(arr, key);\n\n \/\/ Initialize starting index and\n\n \/\/ ending index\n\n int low = 0, high = i;\n\n int mid;\n\n \n\n \/\/ Till high does not crosses low\n\n while (low < high) {\n\n \n\n \/\/ Find the index of the middle element\n\n mid = low + (high - low) \/ 2;\n\n \n\n \/\/ If key is less than or equal\n\n \/\/ to array[mid], then find in\n\n \/\/ left subarray\n\n if (key <= arr[mid]) {\n\n high = mid;\n\n }\n\n \n\n \/\/ If key is greater than array[mid],\n\n \/\/ then find in right subarray\n\n else {\n\n \n\n low = mid + 1;\n\n }\n\n }\n\n return low;\n\n }\n\n static boolean palin(int arr[], int i, int j){\n\n while(i < j){\n\n if(arr[i] != arr[j])\n\n return false;\n\n i++;\n\n j--;\n\n }\n\n return true;\n\n }\n\n static boolean palin(String s){\n\n int i=0,j=s.length()-1;\n\n while(ia[i+1]){\n\n return i;\n\n }\n\n }\n\n return n;\n\n }\n\n static void rev(int a[], int i, int j){\n\n while(i 0)\n\n {\n\n \n\n \/\/ If y is odd, multiply x with result\n\n if ((y & 1) != 0)\n\n res = (res * x) % p;\n\n \n\n \/\/ y must be even now\n\n y = y >> 1; \/\/ y = y\/2\n\n x = (x * x) % p;\n\n }\n\n return res;\n\n }\n\n}","language":"java"} +{"contest_id":"1311","problem_id":"D","statement":"D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a\u2264b\u2264ca\u2264b\u2264c.In one move, you can add +1+1 or \u22121\u22121 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A\u2264B\u2264CA\u2264B\u2264C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1\u2264a\u2264b\u2264c\u22641041\u2264a\u2264b\u2264c\u2264104).OutputFor each test case, print the answer. In the first line print resres \u2014 the minimum number of operations you have to perform to obtain three integers A\u2264B\u2264CA\u2264B\u2264C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8\n1 2 3\n123 321 456\n5 10 15\n15 18 21\n100 100 101\n1 22 29\n3 19 38\n6 30 46\nOutputCopy1\n1 1 3\n102\n114 228 456\n4\n4 8 16\n6\n18 18 18\n1\n100 100 100\n7\n1 22 22\n2\n1 19 38\n8\n6 24 48\n","tags":["brute force","math"],"code":"import java.io.*;\n\nimport java.util.*;\n\n\n\npublic class Main {\n\n public static void main(String[] args) throws IOException {\n\n \/\/BufferedReader f = new BufferedReader(new FileReader(\"uva.in\"));\n\n BufferedReader f = new BufferedReader(new InputStreamReader(System.in));\n\n PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));\n\n int t = Integer.parseInt(f.readLine());\n\n while(t-- > 0) {\n\n StringTokenizer st = new StringTokenizer(f.readLine());\n\n int a = Integer.parseInt(st.nextToken());\n\n int b = Integer.parseInt(st.nextToken());\n\n int c = Integer.parseInt(st.nextToken());\n\n int ans = 30000;\n\n int resA = 0;\n\n int resB = 0;\n\n int resC = 0;\n\n for(int A = 1; A <= 10000; A++) {\n\n for(int B = A; B <= 20000; B += A) {\n\n int C1 = c\/B*B;\n\n int C2 = (c+B-1)\/B*B;\n\n int temp = Math.abs(A-a)+Math.abs(B-b)+Math.abs(C2-c);\n\n if(temp < ans) {\n\n ans = temp;\n\n resA = A;\n\n resB = B;\n\n resC = C2;\n\n }\n\n if(C1 > 0) {\n\n temp = Math.abs(A-a)+Math.abs(B-b)+Math.abs(C1-c);\n\n if(temp < ans) {\n\n ans = temp;\n\n resA = A;\n\n resB = B;\n\n resC = C1;\n\n }\n\n }\n\n }\n\n }\n\n out.println(ans);\n\n out.println(resA + \" \" + resB + \" \" + resC);\n\n }\n\n f.close();\n\n out.close();\n\n }\n\n}\n\n","language":"java"} +{"contest_id":"1315","problem_id":"B","statement":"B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,\u2026,j\u22121i,i+1,\u2026,j\u22121 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i\u2264t 0) {\n\t\t\tint a = fastReader.nextInt();\n\t\t\tint b = fastReader.nextInt();\n\t\t\tint q = fastReader.nextInt();\n\t\t\tchar c[] = fastReader.nextLine().toCharArray();\n\t\t\tint n = c.length;\n\t\t\tint index = n - 1;\n\t\t\tfor (int i = n - 2; i >= 0; i--) {\n\t\t\t\tif (c[i] == 'B') {\n\t\t\t\t\tq -= b;\n\t\t\t\t} else {\n\t\t\t\t\tq -= a;\n\t\t\t\t}\n\t\t\t\tint cur_indx = i - 1;\n\t\t\t\twhile (cur_indx >= 0 && c[cur_indx] == c[i])\n\t\t\t\t\tcur_indx--;\n\t\t\t\tif (q >= 0) {\n\t\t\t\t\tindex = (cur_indx + 1);\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ti = cur_indx + 1;\n\t\t\t}\n\t\t\tout.println((index + 1));\n\t\t}\n\t\tout.close();\n\t}\n\n\t\/\/ constants\n\tstatic final int IBIG = 1000000007;\n\tstatic final int IMAX = 2147483647;\n\tstatic final long LMAX = 9223372036854775807L;\n\tstatic Random __r = new Random();\n\n\t\/\/ math util\n\tstatic int minof(int a, int b, int c) {\n\t\treturn min(a, min(b, c));\n\t}\n\n\tstatic int minof(int... x) {\n\t\tif (x.length == 1)\n\t\t\treturn x[0];\n\t\tif (x.length == 2)\n\t\t\treturn min(x[0], x[1]);\n\t\tif (x.length == 3)\n\t\t\treturn min(x[0], min(x[1], x[2]));\n\t\tint min = x[0];\n\t\tfor (int i = 1; i < x.length; ++i)\n\t\t\tif (x[i] < min)\n\t\t\t\tmin = x[i];\n\t\treturn min;\n\t}\n\n\tstatic long minof(long a, long b, long c) {\n\t\treturn min(a, min(b, c));\n\t}\n\n\tstatic long minof(long... x) {\n\t\tif (x.length == 1)\n\t\t\treturn x[0];\n\t\tif (x.length == 2)\n\t\t\treturn min(x[0], x[1]);\n\t\tif (x.length == 3)\n\t\t\treturn min(x[0], min(x[1], x[2]));\n\t\tlong min = x[0];\n\t\tfor (int i = 1; i < x.length; ++i)\n\t\t\tif (x[i] < min)\n\t\t\t\tmin = x[i];\n\t\treturn min;\n\t}\n\n\tstatic int maxof(int a, int b, int c) {\n\t\treturn max(a, max(b, c));\n\t}\n\n\tstatic int maxof(int... x) {\n\t\tif (x.length == 1)\n\t\t\treturn x[0];\n\t\tif (x.length == 2)\n\t\t\treturn max(x[0], x[1]);\n\t\tif (x.length == 3)\n\t\t\treturn max(x[0], max(x[1], x[2]));\n\t\tint max = x[0];\n\t\tfor (int i = 1; i < x.length; ++i)\n\t\t\tif (x[i] > max)\n\t\t\t\tmax = x[i];\n\t\treturn max;\n\t}\n\n\tstatic long maxof(long a, long b, long c) {\n\t\treturn max(a, max(b, c));\n\t}\n\n\tstatic long maxof(long... x) {\n\t\tif (x.length == 1)\n\t\t\treturn x[0];\n\t\tif (x.length == 2)\n\t\t\treturn max(x[0], x[1]);\n\t\tif (x.length == 3)\n\t\t\treturn max(x[0], max(x[1], x[2]));\n\t\tlong max = x[0];\n\t\tfor (int i = 1; i < x.length; ++i)\n\t\t\tif (x[i] > max)\n\t\t\t\tmax = x[i];\n\t\treturn max;\n\t}\n\n\tstatic int powi(int a, int b) {\n\t\tif (a == 0)\n\t\t\treturn 0;\n\t\tint ans = 1;\n\t\twhile (b > 0) {\n\t\t\tif ((b & 1) > 0)\n\t\t\t\tans *= a;\n\t\t\ta *= a;\n\t\t\tb >>= 1;\n\t\t}\n\t\treturn ans;\n\t}\n\n\tstatic long powl(long a, int b) {\n\t\tif (a == 0)\n\t\t\treturn 0;\n\t\tlong ans = 1;\n\t\twhile (b > 0) {\n\t\t\tif ((b & 1) > 0)\n\t\t\t\tans *= a;\n\t\t\ta *= a;\n\t\t\tb >>= 1;\n\t\t}\n\t\treturn ans;\n\t}\n\n\tstatic int fli(double d) {\n\t\treturn (int) d;\n\t}\n\n\tstatic int cei(double d) {\n\t\treturn (int) ceil(d);\n\t}\n\n\tstatic long fll(double d) {\n\t\treturn (long) d;\n\t}\n\n\tstatic long cel(double d) {\n\t\treturn (long) ceil(d);\n\t}\n\n\tstatic int gcd(int a, int b) {\n\t\treturn b == 0 ? a : gcd(b, a % b);\n\t}\n\n\tstatic int lcm(int a, int b) {\n\t\treturn (a \/ gcd(a, b)) * b;\n\t}\n\n\tstatic long gcd(long a, long b) {\n\t\treturn b == 0 ? a : gcd(b, a % b);\n\t}\n\n\tstatic long lcm(long a, long b) {\n\t\treturn (a \/ gcd(a, b)) * b;\n\t}\n\n\tstatic int[] exgcd(int a, int b) {\n\t\tif (b == 0)\n\t\t\treturn new int[] { 1, 0 };\n\t\tint[] y = exgcd(b, a % b);\n\t\treturn new int[] { y[1], y[0] - y[1] * (a \/ b) };\n\t}\n\n\tstatic long[] exgcd(long a, long b) {\n\t\tif (b == 0)\n\t\t\treturn new long[] { 1, 0 };\n\t\tlong[] y = exgcd(b, a % b);\n\t\treturn new long[] { y[1], y[0] - y[1] * (a \/ b) };\n\t}\n\n\tstatic int randInt(int min, int max) {\n\t\treturn __r.nextInt(max - min + 1) + min;\n\t}\n\n\tstatic long mix(long x) {\n\t\tx += 0x9e3779b97f4a7c15L;\n\t\tx = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;\n\t\tx = (x ^ (x >> 27)) * 0x94d049bb133111ebL;\n\t\treturn x ^ (x >> 31);\n\t}\n\n\tpublic static boolean[] findPrimes(int limit) {\n\t\tassert limit >= 2;\n\n\t\tfinal boolean[] nonPrimes = new boolean[limit];\n\t\tnonPrimes[0] = true;\n\t\tnonPrimes[1] = true;\n\n\t\tint sqrt = (int) Math.sqrt(limit);\n\t\tfor (int i = 2; i <= sqrt; i++) {\n\t\t\tif (nonPrimes[i])\n\t\t\t\tcontinue;\n\t\t\tfor (int j = i; j < limit; j += i) {\n\t\t\t\tif (!nonPrimes[j] && i != j)\n\t\t\t\t\tnonPrimes[j] = true;\n\t\t\t}\n\t\t}\n\n\t\treturn nonPrimes;\n\t}\n\n\t\/\/ array util\n\tstatic void reverse(int[] a) {\n\t\tfor (int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {\n\t\t\tint swap = a[i];\n\t\t\ta[i] = a[n - i - 1];\n\t\t\ta[n - i - 1] = swap;\n\t\t}\n\t}\n\n\tstatic void reverse(long[] a) {\n\t\tfor (int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {\n\t\t\tlong swap = a[i];\n\t\t\ta[i] = a[n - i - 1];\n\t\t\ta[n - i - 1] = swap;\n\t\t}\n\t}\n\n\tstatic void reverse(double[] a) {\n\t\tfor (int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {\n\t\t\tdouble swap = a[i];\n\t\t\ta[i] = a[n - i - 1];\n\t\t\ta[n - i - 1] = swap;\n\t\t}\n\t}\n\n\tstatic void reverse(char[] a) {\n\t\tfor (int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {\n\t\t\tchar swap = a[i];\n\t\t\ta[i] = a[n - i - 1];\n\t\t\ta[n - i - 1] = swap;\n\t\t}\n\t}\n\n\tstatic void shuffle(int[] a) {\n\t\tint n = a.length - 1;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint ind = randInt(i, n);\n\t\t\tint swap = a[i];\n\t\t\ta[i] = a[ind];\n\t\t\ta[ind] = swap;\n\t\t}\n\t}\n\n\tstatic void shuffle(long[] a) {\n\t\tint n = a.length - 1;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint ind = randInt(i, n);\n\t\t\tlong swap = a[i];\n\t\t\ta[i] = a[ind];\n\t\t\ta[ind] = swap;\n\t\t}\n\t}\n\n\tstatic void shuffle(double[] a) {\n\t\tint n = a.length - 1;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint ind = randInt(i, n);\n\t\t\tdouble swap = a[i];\n\t\t\ta[i] = a[ind];\n\t\t\ta[ind] = swap;\n\t\t}\n\t}\n\n\tstatic void rsort(int[] a) {\n\t\tshuffle(a);\n\t\tsort(a);\n\t}\n\n\tstatic void rsort(long[] a) {\n\t\tshuffle(a);\n\t\tsort(a);\n\t}\n\n\tstatic void rsort(double[] a) {\n\t\tshuffle(a);\n\t\tsort(a);\n\t}\n\n\tstatic int[] copy(int[] a) {\n\t\tint[] ans = new int[a.length];\n\t\tfor (int i = 0; i < a.length; ++i)\n\t\t\tans[i] = a[i];\n\t\treturn ans;\n\t}\n\n\tstatic long[] copy(long[] a) {\n\t\tlong[] ans = new long[a.length];\n\t\tfor (int i = 0; i < a.length; ++i)\n\t\t\tans[i] = a[i];\n\t\treturn ans;\n\t}\n\n\tstatic double[] copy(double[] a) {\n\t\tdouble[] ans = new double[a.length];\n\t\tfor (int i = 0; i < a.length; ++i)\n\t\t\tans[i] = a[i];\n\t\treturn ans;\n\t}\n\n\tstatic char[] copy(char[] a) {\n\t\tchar[] ans = new char[a.length];\n\t\tfor (int i = 0; i < a.length; ++i)\n\t\t\tans[i] = a[i];\n\t\treturn ans;\n\t}\n\n\tstatic class FastReader {\n\n\t\tBufferedReader br;\n\t\tStringTokenizer st;\n\n\t\tpublic FastReader() {\n\t\t\tbr = new BufferedReader(\n\t\t\t\t\tnew InputStreamReader(System.in));\n\t\t}\n\n\t\tString next() {\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\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn st.nextToken();\n\t\t}\n\n\t\tint nextInt() {\n\t\t\treturn Integer.parseInt(next());\n\t\t}\n\n\t\tint[] ria(int n) {\n\t\t\tint[] a = new int[n];\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\ta[i] = Integer.parseInt(next());\n\t\t\treturn a;\n\t\t}\n\n\t\tlong nextLong() {\n\t\t\treturn Long.parseLong(next());\n\t\t}\n\n\t\tlong[] rla(int n) {\n\t\t\tlong[] a = new long[n];\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\ta[i] = Long.parseLong(next());\n\t\t\treturn a;\n\t\t}\n\n\t\tdouble nextDouble() {\n\t\t\treturn Double.parseDouble(next());\n\t\t}\n\n\t\tString nextLine() {\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\te.printStackTrace();\n\t\t\t}\n\t\t\treturn str;\n\t\t}\n\t}\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\n\n\nimport java.util.*;\n\nimport java.io.*;\n\n\n\n\n\npublic class Main{\n\n static class pair{\n\n long x ;long y ;\n\n pair(long x ,long y )\n\n {\n\n this.x=x;\n\n this.y =y;\n\n }\n\n\n\n }\n\n static class FastReader{\n\n BufferedReader br;\n\n StringTokenizer st;\n\n public FastReader(){\n\n br=new BufferedReader(new InputStreamReader(System.in));\n\n }\n\n String next(){\n\n while(st==null || !st.hasMoreTokens()){\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 int nextInt(){\n\n return Integer.parseInt(next());\n\n }\n\n long nextLong(){\n\n return Long.parseLong(next());\n\n }\n\n double nextDouble(){\n\n return Double.parseDouble(next());\n\n }\n\n String nextLine(){\n\n String str=\"\";\n\n try {\n\n str=br.readLine().trim();\n\n } catch (Exception e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n static class FastWriter {\n\n private final BufferedWriter bw;\n\n\n\n public FastWriter() {\n\n this.bw = new BufferedWriter(new OutputStreamWriter(System.out));\n\n }\n\n\n\n public void prlong(Object object) throws IOException {\n\n\n\n bw.append(\"\" + object);\n\n }\n\n\n\n public void prlongln(Object object) throws IOException {\n\n prlong(object);\n\n bw.append(\"\\n\");\n\n }\n\n\n\n public void close() throws IOException {\n\n bw.close();\n\n }\n\n }\n\n public static long gcd(long a, long b)\n\n {\n\n if (a == 0)\n\n return b;\n\n return gcd(b % a, a);\n\n }\n\n\n\n \/\/dsu\n\n static int[] parent,rank;\n\n public static void dsu(int n){\n\n parent = new int[n]; rank = new int[n];\n\n for(int i =0;i=rank[j]){\n\n rank[i]+=rank[j];\n\n parent[j]=i;\n\n }\n\n else {\n\n rank[j]+=rank[i];\n\n parent[i]=j;\n\n }\n\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n public static int help(boolean[] v){\n\n HashSet s = new HashSet<>();\n\n for(int e=1;e 0) {\n\n\n\nlong n =in.nextLong();\n\nlong arr[]=new long[(int) n];\n\nlong sum =0;\n\nfor(int i =0;i 0) {\n\n int n = rni(), m = ni();\n\n par = new int[n];\n\n for(int i = 0; i < n; ++i) {\n\n par[i] = i;\n\n }\n\n long c[] = rla(n);\n\n List> g = sgraph(2 * n);\n\n for(int i = 0; i < m; ++i) {\n\n int u = rni() - 1, v = ni() + n - 1;\n\n connect(g, u, v);\n\n }\n\n if(m == 0) {\n\n prln(0);\n\n } else {\n\n Map sum = new HashMap<>();\n\n for(int i = 0; i < n; ++i) {\n\n long hash = 0;\n\n for(int j : g.get(n + i)) {\n\n hash ^= hash(j);\n\n }\n\n sum.put(hash, sum.getOrDefault(hash, 0L) + c[i]);\n\n }\n\n long ans = 0;\n\n for(long k : sum.keySet()) {\n\n if(k != 0) {\n\n if(ans == 0) {\n\n ans = sum.get(k);\n\n } else {\n\n ans = gcf(ans, sum.get(k));\n\n }\n\n }\n\n }\n\n prln(ans);\n\n }\n\n if(t > 0) {\n\n rline();\n\n }\n\n }\n\n close();\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 ~= 2e10\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 randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}\n\n static long hash(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(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 rsort(int[] a) {shuffle(a); sort(a);}\n\n static void rsort(long[] 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 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 static int[] sorted(int[] a) {int[] ans = copy(a); sort(ans); return ans;}\n\n static long[] sorted(long[] a) {long[] ans = copy(a); sort(ans); return ans;}\n\n static int[] rsorted(int[] a) {int[] ans = copy(a); rsort(ans); return ans;}\n\n static long[] rsorted(long[] a) {long[] ans = copy(a); rsort(ans); return ans;}\n\n \/\/ graph util\n\n static List> graph(int n) {List> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}\n\n static List> graph(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;}\n\n static List> graph(int n, int m) throws IOException {return graph(graph(n), m);}\n\n static List> dgraph(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;}\n\n static List> dgraph(List> g, int n, int m) throws IOException {return dgraph(graph(n), m);}\n\n static List> sgraph(int n) {List> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}\n\n static List> sgraph(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;}\n\n static List> sgraph(int n, int m) throws IOException {return sgraph(sgraph(n), m);}\n\n static List> dsgraph(List> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;}\n\n static List> dsgraph(List> g, int n, int m) throws IOException {return dsgraph(sgraph(n), m);}\n\n static void connect(List> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}\n\n static void connecto(List> g, int u, int v) {g.get(u).add(v);}\n\n static void dconnect(List> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}\n\n static void dconnecto(List> g, int u, int v) {g.get(u).remove(v);}\n\n \/\/ input\n\n static void r() throws IOException {input = new StringTokenizer(__in.readLine());}\n\n static int ri() throws IOException {return Integer.parseInt(__in.readLine());}\n\n static long rl() throws IOException {return Long.parseLong(__in.readLine());}\n\n static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}\n\n static int[] riam1(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()) - 1; return a;}\n\n static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}\n\n static char[] rcha() throws IOException {return __in.readLine().toCharArray();}\n\n static String rline() throws IOException {return __in.readLine();}\n\n static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}\n\n static int ni() {return Integer.parseInt(input.nextToken());}\n\n static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}\n\n static long nl() {return Long.parseLong(input.nextToken());}\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(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\");}\n\n static void flush() {__out.flush();}\n\n static void close() {__out.close();}\n\n}","language":"java"} +{"contest_id":"1313","problem_id":"D","statement":"D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1\u2264n\u2264100000,1\u2264m\u2264109,1\u2264k\u226481\u2264n\u2264100000,1\u2264m\u2264109,1\u2264k\u22648)\u00a0\u2014 the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1\u2264Li\u2264Ri\u2264m1\u2264Li\u2264Ri\u2264m)\u00a0\u2014 the parameters of the ii spell.OutputPrint a single integer\u00a0\u2014 the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.","tags":["bitmasks","dp","implementation"],"code":"\/\/package com.example.practice.codeforces.sc2500;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.Map;\nimport java.util.StringTokenizer;\n\/\/D. Happy New Year\npublic class Solution1 {\n public static void main (String [] args) throws IOException {\n \/\/ Use BufferedReader rather than RandomAccessFile; it's much faster\n final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));\n \/\/ input file name goes above\n \/\/PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(\"inflate.out\")));\n\n StringTokenizer st = new StringTokenizer(input.readLine());\n int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken());\n int[][] ns = new int[n][2];\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":"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":"\n\nimport java.io.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.io.PrintWriter;\n\nimport java.util.ArrayList;\n\nimport java.util.Arrays;\n\nimport java.util.Collections;\n\nimport java.util.HashMap;\n\nimport java.util.InputMismatchException;\n\nimport java.util.LinkedHashMap;\n\nimport java.util.Map;\n\nimport java.util.Scanner;\n\nimport java.util.StringTokenizer;\n\nimport java.util.stream.Collectors;\n\npublic class cf {\n\n\n\n\tstatic class FastReader {\n\n\t\tBufferedReader br;\n\n\t\tStringTokenizer st;\n\n \n\n\t\tpublic FastReader() {\n\n\t\t\tbr = new BufferedReader(new InputStreamReader(System.in));\n\n\t\t}\n\n \n\n\t\tString next() {\n\n\t\t\twhile(st == null || !st.hasMoreElements()) {\n\n\t\t\t\ttry {\n\n\t\t\t\t\tString str = br.readLine();\n\n \n\n\t\t\t\t\tif(str == null)\n\n\t\t\t\t\t\tthrow new InputMismatchException();\n\n \n\n\t\t\t\t\tst = new StringTokenizer(str);\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\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\tlong nextLong() {\n\n\t\t\treturn Long.parseLong(next());\n\n\t\t}\n\n \n\n\t\tdouble nextDouble() {\n\n\t\t\treturn Double.parseDouble(next());\n\n\t\t}\n\n \n\n\t\tString nextLine() {\n\n\t\t\tString str = \"\";\n\n \n\n\t\t\ttry {\n\n\t\t\t\tstr = br.readLine();\n\n\t\t\t} catch(IOException e) {\n\n\t\t\t\te.printStackTrace();\n\n\t\t\t}\n\n \n\n\t\t\tif(str == null) \n\n\t\t\t\tthrow new InputMismatchException();\n\n\t\t\treturn str;\n\n\t\t}\n\n\t}\n\n static boolean pal(String s)\n\n {\n\n \tStringBuilder sb=new StringBuilder();\n\n \tsb.append(s);\n\n \tsb.reverse();\n\n \tString s1=sb.toString();\n\n \tif(s1.contentEquals(s))\n\n \t{\n\n \t\treturn true;\n\n \t}\n\n \telse\n\n \t{\n\n \t\treturn false;\n\n \t}\n\n }\n\n \n\n static boolean isPrime(long arr)\n\n{\n\n \/\/ Corner cases\n\n if (arr <= 1)\n\n return false;\n\n if (arr <= 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 (arr % 2 == 0 || arr % 3 == 0)\n\n return false;\n\n \n\n for (int i = 5; i * i <= arr; i = i + 6)\n\n if (arr % i == 0 || arr % (i + 2) == 0)\n\n return false;\n\n \n\n return true;\n\n}\n\n public static int reverseBits(int n)\n\n {\n\n int rev = 0;\n\n \n\n \/\/ traversing bits of 'n'\n\n \/\/ from the right\n\n while (n > 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 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\tpublic static void main(String[] args) \n\n\t{\n\n\t\tFastReader sc = new FastReader();\n\n\t PrintWriter out = new PrintWriter(System.out);\n\n int t=sc.nextInt();\n\n while(t-->0)\n\n {\n\n \tlong n=sc.nextLong();\n\n\t\t\tlong s=sc.nextLong();\n\n\t\t\tlong k=sc.nextLong();\n\n\t\t\tlong arr[]=new long[(int) k];\n\n\t\t\tHashMap x=new HashMap();\n\n\t\t\tfor(int i=0;i=1)\n\n\t\t\t\t{\n\n\t\t\t\t\tout.println(Math.abs(s1-s2));\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t\ts++;\n\n\t\t\t\ts1--;\n\n\t\t\t}\n\n }\n\n\t out.close();\n\n\t}\n\n}","language":"java"} +{"contest_id":"1325","problem_id":"A","statement":"A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1\u2264t\u2264100)(1\u2264t\u2264100) \u00a0\u2014 the number of testcases.Each testcase consists of one line containing a single integer, xx (2\u2264x\u2264109)(2\u2264x\u2264109).OutputFor each testcase, output a pair of positive integers aa and bb (1\u2264a,b\u2264109)1\u2264a,b\u2264109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2\n2\n14\nOutputCopy1 1\n6 4\nNoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.","tags":["constructive algorithms","greedy","number theory"],"code":"import java.io.* ;\n\npublic class Main\n\n{\n\n public static void main( String[] args) throws Exception\n\n {\n\n BufferedReader br = new BufferedReader ( new InputStreamReader( System.in ) );\n\n PrintWriter out = new PrintWriter ( System.out );\n\n \n\n int t = Integer.parseInt( br.readLine() ) ;\n\n \n\n int[] arr = new int [ t ] ;\n\n \n\n for( int i = 0 ; i != t ; ++i )\n\n arr[ i ] =Integer.parseInt( br.readLine() ) ;\n\n \n\n for( int item : arr )\n\n out.println( \"1 \" + ( item-1 ) );\n\n out.flush(); \n\n \n\n return ;\n\n \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\/\/System.out.println(\"Hello World\");\n\n\t\tScanner sc=new Scanner(System.in);\n\n\t\tint t=sc.nextInt();\n\n\t\t\n\n\t\tfor(int i=0;ib)\n\n\t\t {\n\n\t\t if((a-b)%2==0)\n\n\t\t System.out.println(\"1\");\n\n\t\t else\n\n\t\t System.out.println(\"2\");\n\n\t\t }\n\n\t\t else\n\n\t\t {\n\n\t\t if((b-a)%2!=0)\n\n\t\t System.out.println(\"1\");\n\n\t\t else\n\n\t\t System.out.println(\"2\");\n\n\t\t }\n\n\t\t\n\n\t\t}\n\n\t}\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.*;\n\nimport java.util.*;\n\n\n\npublic class Main {\n\n private static final InputReader in = new InputReader(System.in);\n\n private static final PrintWriter pw = new PrintWriter(System.out);\n\n\n\n public static void main(String[] args) {\n\n int n = in.nextInt();\n\n Integer[] d = new Integer[n];\n\n for (int i = 0; i < n; i++) {\n\n d[i] = in.nextInt();\n\n }\n\n for (int i = 0; i < n; i++) {\n\n d[i] -= in.nextInt();\n\n }\n\n\n\n Arrays.sort(d);\n\n\n\n long ans = 0;\n\n for (int i = 0; i < n - 1; i++) {\n\n int l = i + 1, r = n - 1, x = n;\n\n while (l <= r) {\n\n int mid = l + (r - l) \/ 2;\n\n if (d[mid] > -d[i]) {\n\n r = mid - 1;\n\n x = mid;\n\n }\n\n else l = mid + 1;\n\n }\n\n ans += n - x;\n\n }\n\n pw.println(ans);\n\n pw.close();\n\n }\n\n\n\n private static class Pair {\n\n private int first, second;\n\n\n\n public Pair(int first, int second) {\n\n this.first = first;\n\n this.second = second;\n\n }\n\n }\n\n\n\n private static class InputReader {\n\n public BufferedReader reader;\n\n public 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 boolean ready() throws IOException {\n\n return reader.ready();\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 = null;\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 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}","language":"java"} +{"contest_id":"1322","problem_id":"C","statement":"C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1\u2264t\u22645000001\u2264t\u2264500000)\u00a0\u2014 the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1\u00a0\u2264\u00a0n,\u00a0m\u00a0\u2264\u00a05000001\u00a0\u2264\u00a0n,\u00a0m\u00a0\u2264\u00a0500000)\u00a0\u2014 the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1\u2264ci\u226410121\u2264ci\u22641012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1\u2264ui,vi\u2264n1\u2264ui,vi\u2264n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer\u00a0\u2014 the required greatest common divisor.ExampleInputCopy3\n2 4\n1 1\n1 1\n1 2\n2 1\n2 2\n\n3 4\n1 1 1\n1 1\n1 2\n2 2\n2 3\n\n4 7\n36 31 96 29\n1 2\n1 3\n1 4\n2 2\n2 4\n3 1\n4 3\nOutputCopy2\n1\n12\nNoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.","tags":["graphs","hashing","math","number theory"],"code":"import java.io.*;\n\nimport java.util.*;\n\nimport java.math.*;\n\npublic class Main{\n\n\tprivate static Scanner cin = new Scanner(new BufferedInputStream(System.in));\n\n\tprivate static PrintWriter cout = new PrintWriter(System.out,true);\n\n\tprivate static InputStream inputstream = System.in;\n\n\tprivate static FastScanner in = new FastScanner(inputstream);\n\n\tpublic static void main(String[] args){\n\n\t\tTask solver = new Task();\n\n\t\tint TaskCase = in.nextInt();\n\n\t\tsolver.solve(TaskCase);\n\n\t\tcout.flush();\n\n\t}\n\n\tprivate static class Task{\n\n\t\tlong value[];\n\n\t\tint n,m;\n\n\t\tTreeMap mp = new TreeMap<>();\n\n\t\tpublic void solve(int T){\n\n\t\t\twhile(T-->0){\n\n\t\t\t\tn = in.nextInt();\n\n\t\t\t\tm = in.nextInt();\n\n\t\t\t\tvalue = new long[n];\n\n\t\t\t\tfor(int i = 0; i < n; i++) value[i] = in.nextLong();\n\n\t\t\t\tif(n==1){\n\n\t\t\t\t\tin.nextInt();\n\n\t\t\t\t\tin.nextInt();\n\n\t\t\t\t\tcout.print(value[0]);\n\n\t\t\t\t\tcout.write('\\n');\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\t}\n\n\t\t\t\tArrayList[] G = Utils.ListArray(n);\n\n\t\t\t\tfor(int i = 0; i < m; i++){\n\n\t\t\t\t\tint u = in.nextInt() - 1, v = in.nextInt() - 1;\n\n\t\t\t\t\tG[v].add(u);\n\n\t\t\t\t}\n\n\t\t\t\tmp.clear();\n\n\t\t\t\tfor(int i = 0; i < n; i++){\n\n\t\t\t\t\tif(G[i].isEmpty()) continue;\n\n\t\t\t\t\tG[i].sort((x,y)->{ return x-y; });\n\n\t\t\t\t\tint hx = G[i].hashCode();\n\n\t\t\t\t\tif(!mp.containsKey(hx)) mp.put(hx,value[i]);\n\n\t\t\t\t\telse mp.put(hx,mp.get(hx)+value[i]);\n\n\t\t\t\t}\n\n\t\t\t\tLong ans = 0l;\n\n\t\t\t\tfor(long v : mp.values()) ans = gcd(ans,v);\n\n\t\t\t\tcout.write(ans.toString()+'\\n');\n\n\t\t\t}\n\n\t\t}\n\n\t\tprivate long gcd(long A, long B){\n\n\t\t\treturn B!=0 ? gcd(B,A%B) : A;\n\n\t\t}\n\n\t}\n\n\tprivate static class Utils{\n\n\t\tpublic static ArrayList[] ListArray(int _size){\n\n\t\t\tArrayList[] ret = new ArrayList[_size];\n\n\t\t\tfor(int i = 0; i < _size; i++) ret[i] = new ArrayList<>();\n\n\t\t\treturn ret;\n\n\t\t}\n\n\t}\n\n\tpublic static class FastScanner {\n\n\t\tBufferedReader br;\n\n\t\tStringTokenizer st;\n\n\t\tpublic FastScanner(InputStream in) {\n\n\t\t\t\tbr = new BufferedReader(new InputStreamReader(in));\n\n\t\t}\n\n\t\tpublic int nextInt() {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\t\tpublic boolean hasMoreTokens() {\n\n\t\t\twhile (st == null || !st.hasMoreElements()) {\n\n\t\t\t\tString line = null;\n\n\t\t\t\ttry {\n\n\t\t\t\t\tline = br.readLine();\n\n\t\t\t\t} catch (IOException e) {\n\n\t\t\t\t\treturn false;\n\n\t\t\t\t}\n\n\t\t\t\tif (line == null) {\n\n\t\t\t\t\treturn false;\n\n\t\t\t\t}\n\n\t\t\t\tst = new StringTokenizer(line);\n\n\t\t\t}\n\n\t\t\treturn true;\n\n\t\t}\n\n\t\tpublic String next() {\n\n\t\t\twhile (st == null || !st.hasMoreElements()) {\n\n\t\t\t\tString line = null;\n\n\t\t\t\ttry {\n\n\t\t\t\t\tline = br.readLine();\n\n\t\t\t\t} catch (IOException e) {\n\n\t\t\t\t}\n\n\t\t\t\tst = new StringTokenizer(line);\n\n\t\t\t}\n\n\t\t\treturn st.nextToken();\n\n\t\t}\n\n\t\tpublic long nextLong() {\n\n\t\t\treturn Long.parseLong(next());\n\n\t\t}\n\n\t\tpublic double nextDouble() {\n\n\t\t\treturn Double.parseDouble(next());\n\n\t\t}\n\n\t\tpublic int[] nextIntArray(int n) {\n\n\t\t\tint[] ret = new int[n];\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tret[i] = nextInt();\n\n\t\t\t}\n\n\t\t\treturn ret;\n\n\t\t}\n\n\t\tpublic long[] nextLongArray(int n) {\n\n\t\t\tlong[] ret = new long[n];\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tret[i] = nextLong();\n\n\t\t\t}\n\n\t\t\treturn ret;\n\n\t\t}\n\n\t}\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.*;\n\nimport java.util.Arrays;\n\nimport java.util.StringJoiner;\n\nimport java.util.StringTokenizer;\n\n\n\npublic class MainE {\n\n\n\n static int N;\n\n static int[] A;\n\n\n\n public static void main(String[] args) {\n\n var sc = new FastScanner(System.in);\n\n N = sc.nextInt();\n\n A = sc.nextIntArray(N);\n\n\n\n System.out.println(solve());\n\n }\n\n\n\n private static int solve() {\n\n \/\/ [L, R)\n\n var merged = new int[N][N+1];\n\n for (int i = 0; i < N; i++) {\n\n merged[i][i+1] = A[i];\n\n }\n\n for (int w = 2; w <= N; w++) {\n\n for (int l = 0; l < N-w+1; l++) {\n\n int r = l+w;\n\n int lr = -1;\n\n for (int m = l+1; m < r; m++) {\n\n if( merged[l][m] != -1 && merged[l][m] == merged[m][r] ) {\n\n lr = merged[l][m]+1;\n\n }\n\n }\n\n merged[l][r] = lr;\n\n }\n\n }\n\n\n\n var len = new int[N][N+1];\n\n for (int i = 0; i < N; i++) {\n\n len[i][i+1] = 1;\n\n }\n\n for (int w = 2; w <= N; w++) {\n\n for (int l = 0; l < N-w+1; l++) {\n\n\n\n int r = l+w;\n\n int lr = Integer.MAX_VALUE;\n\n if( merged[l][r] != -1 ) {\n\n len[l][r] = 1;\n\n continue;\n\n }\n\n for (int m = l+1; m < r; m++) {\n\n lr = Math.min(lr, len[l][m] + len[m][r]);\n\n }\n\n len[l][r] = lr;\n\n }\n\n }\n\n\n\n return len[0][N];\n\n }\n\n\n\n @SuppressWarnings(\"unused\")\n\n static class FastScanner {\n\n private final BufferedReader reader;\n\n private StringTokenizer tokenizer;\n\n\n\n FastScanner(InputStream in) {\n\n reader = new BufferedReader(new InputStreamReader(in));\n\n tokenizer = null;\n\n }\n\n\n\n String next() {\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 RuntimeException(e);\n\n }\n\n }\n\n return tokenizer.nextToken();\n\n }\n\n\n\n String nextLine() {\n\n if (tokenizer == null || !tokenizer.hasMoreTokens()) {\n\n try {\n\n return 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\n long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n\n\n int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n int[] nextIntArray(int n) {\n\n var a = new int[n];\n\n for (int i = 0; i < n; i++) a[i] = nextInt();\n\n return a;\n\n }\n\n\n\n int[] nextIntArray(int n, int delta) {\n\n var a = new int[n];\n\n for (int i = 0; i < n; i++) a[i] = nextInt() + delta;\n\n return a;\n\n }\n\n\n\n long[] nextLongArray(int n) {\n\n var a = new long[n];\n\n for (int i = 0; i < n; i++) a[i] = nextLong();\n\n return a;\n\n }\n\n }\n\n\n\n static void writeLines(int[] as) {\n\n var pw = new PrintWriter(System.out);\n\n for (var a : as) pw.println(a);\n\n pw.flush();\n\n }\n\n\n\n static void writeLines(long[] as) {\n\n var pw = new PrintWriter(System.out);\n\n for (var a : as) pw.println(a);\n\n pw.flush();\n\n }\n\n\n\n static void writeSingleLine(int[] as) {\n\n var pw = new PrintWriter(System.out);\n\n for (var i = 0; i < as.length; i++) {\n\n if (i != 0) pw.print(\" \");\n\n pw.print(as[i]);\n\n }\n\n pw.println();\n\n pw.flush();\n\n }\n\n\n\n static void debug(Object... args) {\n\n var j = new StringJoiner(\" \");\n\n for (var arg : args) {\n\n if (arg == null) j.add(\"null\");\n\n else if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg));\n\n else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg));\n\n else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg));\n\n else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg));\n\n else j.add(arg.toString());\n\n }\n\n System.err.println(j.toString());\n\n }\n\n}\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.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;i0)\n\n\t {\n\n\t int n=sc.nextInt();\n\n\t int k=sc.nextInt();\n\n\t int max=0,i,flag=0;\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}\n\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.*;\n\nimport java.util.*;\n\n\n\npublic class Main{\n\n\tstatic LinkedList[]adj;\n\n\tstatic int k,dep[],par[];\n\n\tstatic boolean[]take,v;\n\n\tstatic LinkedListcycle;\n\n\tstatic void dfs(int i,boolean leaf) {\n\n\t\tv[i]=true;\n\n\t\tboolean isLeaf=true;\n\n\t\tboolean adjc=false;\n\n\t\tfor(int j:adj[i]) {\n\n\t\t\tif(!v[j]) {\n\n\t\t\t\tisLeaf=false;\n\n\t\t\t\tdfs(j,leaf);\n\n\t\t\t}\n\n\t\t\tadjc|=take[j];\n\n\t\t}\n\n\t\tif(isLeaf) {\n\n\t\t\ttake[i]=leaf;\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tif(!adjc) {\n\n\t\t\ttake[i]=true;\n\n\t\t}\n\n\t}\n\n\tstatic void dfs2(int i,int depth) {\n\n\/\/\t\tSystem.out.println(i);\n\n\t\tdep[i]=depth;\n\n\t\tv[i]=true;\n\n\t\tfor(int j:adj[i]) {\n\n\t\t\tif(j==par[i])continue;\n\n\t\t\tif(!v[j]) {\n\n\t\t\t\tpar[j]=i;\n\n\t\t\t\tdfs2(j,depth+1);\n\n\t\t\t}\n\n\t\t\telse {\n\n\t\t\t\tif(dep[i]<=dep[j])continue;\n\n\t\t\t\tint cnt=dep[i]-dep[j]+1;\n\n\t\t\t\tif(cnt>=k && cycle==null) {\n\n\/\/\t\t\t\t\tSystem.out.println(i+\" \"+j);\n\n\t\t\t\t\tcycle=new LinkedList<>();\n\n\t\t\t\t\tint cur=i;\n\n\t\t\t\t\twhile(cur!=j) {\n\n\t\t\t\t\t\tcycle.add(cur);\n\n\t\t\t\t\t\tcur=par[cur];\n\n\t\t\t\t\t}\n\n\t\t\t\t\tcycle.add(j);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tstatic void main() throws Exception{\n\n\t\tint n=sc.nextInt(),m=sc.nextInt();\n\n\t\tk=1;\n\n\t\twhile(k*k();\n\n\t\tfor(int j=0;j0)\n\n\t\t\tmain();\n\n\t\tpw.flush();\n\n\t}\n\n\tstatic PrintWriter pw;\n\n\tstatic MScanner sc;\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[] intArr(int n) throws IOException {\n\n\t int[]in=new int[n];for(int i=0;i[] tree;\n\n\tstatic void dfs(int curr,int p) {\n\n\t\ttable[curr][0]=p; \n\n\t\tfor (int i=1;i<18;i++) { \n\n table[curr][i]=table[table[curr][i-1]][i-1];\n\n }\n\n\t\tfor(int child:tree[curr]) {\n\n\t\t\tif(child!=p) {\n\n\t\t\t\tdepth[child]=1+depth[curr];\n\n\t\t\t\tdfs(child,curr);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t\n\n\tstatic int lca(int u, int v) \n\n { \n\n if(depth[u]-1;i--) { \n\n if ((depth[u]-(int)Math.pow(2, i))>=depth[v]) { \n\n u=table[u][i]; \n\n }\n\n } \n\n if (u==v) { \n\n return u; \n\n }\n\n for(int i=17;i>-1;i--) { \n\n if (table[u][i]!=table[v][i]) { \n\n u=table[u][i]; \n\n v=table[v][i]; \n\n } \n\n } \n\n return table[u][0]; \n\n } \n\n\tstatic int dist(int a, int b) {\n\n\t\t int c = lca(a, b);\n\n\t\t int ans = depth[a] + depth[b] - 2*depth[c];\n\n\t\t return ans;\n\n\t}\n\n\tpublic static void main(String[] args) throws IOException \n\n\t{ \n\n\t\tFastScanner f = new FastScanner(); \n\n\t\tint ttt=1;\n\n\/\/\t\tttt=f.nextInt();\n\n\t\tPrintWriter out=new PrintWriter(System.out);\n\n\t\tfor(int tt=0;tt();\n\n\t\t\tfor(int i=0;i q = new ArrayList<>();\n\n for (int i: p) q.add( i);\n\n Collections.sort(q);\n\n for (int i = 0; i < p.length; i++) p[i] = q.get(i);\n\n }\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\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\t\t\n\n\t\tint nextInt() {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\t\tint[] readArray(int n) {\n\n\t\t\tint[] a=new int[n];\n\n\t\t\tfor (int i=0; i list=new ArrayList<>();\n\n int a=reader.nextInt();\n\n int b=reader.nextInt();\n\n int c=reader.nextInt();\n\n int n=reader.nextInt();\n\n list.add(a);\n\n list.add(b);\n\n list.add(c);\n\n Collections.sort(list);\n\n int max=Collections.max(list);\n\n int rem=0;\n\n int coins=0;\n\n for (int x=0;xn){\n\n System.out.println(\"NO\");\n\n }\n\n else {\n\n if ((n-rem)%3==0){\n\n System.out.println(\"YES\");\n\n }\n\n else {\n\n System.out.println(\"NO\");\n\n }\n\n\n\n }\n\n\n\n\n\n }\n\n\n\n }\n\n}\n\n","language":"java"} +{"contest_id":"1287","problem_id":"A","statement":"A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters \"A\" and \"P\": \"A\" corresponds to an angry student \"P\" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt\u00a0\u2014 the number of groups of students (1\u2264t\u22641001\u2264t\u2264100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1\u2264ki\u22641001\u2264ki\u2264100)\u00a0\u2014 the number of students in the group, followed by a string sisi, consisting of kiki letters \"A\" and \"P\", which describes the ii-th group of students.OutputFor every group output single integer\u00a0\u2014 the last moment a student becomes angry.ExamplesInputCopy1\n4\nPPAP\nOutputCopy1\nInputCopy3\n12\nAPPAPPPAPPPP\n3\nAAP\n3\nPPA\nOutputCopy4\n1\n0\nNoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute\u00a0\u2014 AAPAAPPAAPPP after 22 minutes\u00a0\u2014 AAAAAAPAAAPP after 33 minutes\u00a0\u2014 AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.","tags":["greedy","implementation"],"code":"import java.util.*;\npublic class JavaApplication51 {\nstatic Scanner z = new Scanner(System.in);\n public static void main(String[] args) {\n int d=z.nextInt();\n \n \n while(d-->0){\n int s=z.nextInt();\n String c=z.next();\n StringBuffer k = new StringBuffer(c);\n int count=0;\n while(true){\n boolean h=false;\n String l=k.toString();\n StringBuffer r=new StringBuffer(\"\") ;\n for (int i = 1; i < s; i++) {\n if(k.charAt(i-1)=='A'&&k.charAt(i)=='P'){\n k.setCharAt(i, 'A');\n h=true;\n i++;\n } \n }\n r=k;\n if(h){\n count++; \n }\n if(l.equals(r.toString())){\n break;\n }\n }\n System.out.println(count);\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":"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.*;\n\nimport java.util.*;\n\n\n\npublic class D {\n\n\n\n\tstatic void query(int l, int r) {\n\n\t\tSystem.out.printf(\"? %d %d\\n\", l, r);\n\n\t}\n\n\n\n\tpublic static void main(String[] args) throws IOException {\n\n\t\tScanner sc = new Scanner();\n\n\t\tint n = sc.nextInt();\n\n\t\tquery(1, n);\n\n\t\tchar[] ans = new char[n];\n\n\t\tif (n == 1) {\n\n\t\t\tans = sc.next().toCharArray();\n\n\t\t} else {\n\n\t\t\tHashMap map = new HashMap();\n\n\t\t\tfor (int i = n * (n + 1) \/ 2; i > 0; i--) {\n\n\t\t\t\tString s = sc.get();\n\n\t\t\t\tmap.put(s, map.getOrDefault(s, 0) + 1);\n\n\n\n\t\t\t}\n\n\n\n\t\t\tquery(2, n);\n\n\t\t\tfor (int i = n * (n - 1) \/ 2; i > 0; i--) {\n\n\t\t\t\tString s = sc.get();\n\n\t\t\t\tmap.put(s, map.get(s) - 1);\n\n\t\t\t}\n\n\t\t\tArrayList a = new ArrayList();\n\n\t\t\tfor (String x : map.keySet()) {\n\n\t\t\t\tif (map.get(x) > 0)\n\n\t\t\t\t\ta.add(x);\n\n\t\t\t}\n\n\t\t\tCollections.sort(a, (x, y) -> x.length() - y.length());\n\n\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tString curr = a.get(i);\n\n\t\t\t\tint[] f = new int[26];\n\n\t\t\t\tfor (char c : curr.toCharArray())\n\n\t\t\t\t\tf[c - 'a']++;\n\n\t\t\t\tfor (int j = 0; j < i; j++)\n\n\t\t\t\t\tf[ans[j] - 'a']--;\n\n\t\t\t\tfor (int c = 0; c < 26; c++)\n\n\t\t\t\t\tif (f[c] > 0)\n\n\t\t\t\t\t\tans[i] = (char) (c + 'a');\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tSystem.out.printf(\"! %s\\n\", new String(ans));\n\n\t}\n\n\n\n\tstatic class Scanner {\n\n\t\tBufferedReader br;\n\n\t\tStringTokenizer st;\n\n\n\n\t\tScanner() {\n\n\t\t\tbr = new BufferedReader(new InputStreamReader(System.in));\n\n\t\t}\n\n\n\n\t\tString get() throws IOException {\n\n\t\t\tString ans = next();\n\n\t\t\tchar[] s = ans.toCharArray();\n\n\t\t\tArrays.sort(s);\n\n\t\t\treturn new String(s);\n\n\t\t}\n\n\n\n\t\tScanner(String fileName) throws FileNotFoundException {\n\n\t\t\tbr = new BufferedReader(new FileReader(fileName));\n\n\t\t}\n\n\n\n\t\tString 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\n\n\t\tString nextLine() throws IOException {\n\n\t\t\treturn br.readLine();\n\n\t\t}\n\n\n\n\t\tint nextInt() throws IOException {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\n\n\t\tlong nextLong() throws NumberFormatException, IOException {\n\n\t\t\treturn Long.parseLong(next());\n\n\t\t}\n\n\n\n\t\tdouble nextDouble() throws NumberFormatException, IOException {\n\n\t\t\treturn Double.parseDouble(next());\n\n\t\t}\n\n\n\n\t\tboolean ready() throws IOException {\n\n\t\t\treturn br.ready();\n\n\t\t}\n\n\n\n\t}\n\n\n\n\tstatic void sort(int[] a) {\n\n\t\tshuffle(a);\n\n\t\tArrays.sort(a);\n\n\t}\n\n\n\n\tstatic void shuffle(int[] a) {\n\n\t\tint n = a.length;\n\n\t\tRandom rand = new Random();\n\n\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\tint tmpIdx = rand.nextInt(n);\n\n\t\t\tint tmp = a[i];\n\n\t\t\ta[i] = a[tmpIdx];\n\n\t\t\ta[tmpIdx] = tmp;\n\n\t\t}\n\n\t}\n\n\n\n}","language":"java"} +{"contest_id":"1313","problem_id":"C2","statement":"C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n\u2264500000n\u2264500000The outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1\u2264ai\u2264mi1\u2264ai\u2264mi). Also there mustn't be integers jj and kk such that jaiai= aa[i])\n\t\t\t\tcnt--;\n\t\t\tqu[cnt++] = i;\n\t\t\tpp[i] = p;\n\t\t\tdp[i] = dp[p] + (long) (i - p) * aa[i];\n\t\t}\n\t\tcnt = 0;\n\t\tqu[cnt++] = n + 1;\n\t\tfor (int q, i = n; i >= 1; i--) {\n\t\t\twhile (aa[q = qu[cnt - 1]] >= aa[i])\n\t\t\t\tcnt--;\n\t\t\tqu[cnt++] = i;\n\t\t\tqq[i] = q;\n\t\t\tdq[i] = dq[q] + (long) (q - i) * aa[i];\n\t\t}\n\t\tint h = 0;\n\t\tfor (int i = 1; i <= n; i++)\n\t\t\tif (h == 0 || dp[h] + dq[h] - aa[h] < dp[i] + dq[i] - aa[i])\n\t\t\t\th = i;\n\t\tfor (int i = h; i >= 1; ) {\n\t\t\tint a = aa[i];\n\t\t\tint p = pp[i];\n\t\t\twhile (i != p) {\n\t\t\t\taa[i] = a;\n\t\t\t\ti--;\n\t\t\t}\n\t\t}\n\t\tfor (int i = h; i <= n; ) {\n\t\t\tint a = aa[i];\n\t\t\tint q = qq[i];\n\t\t\twhile (i != q) {\n\t\t\t\taa[i] = a;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\tfor (int i = 1; i <= n; i++)\n\t\t\tprint(aa[i] + \" \");\n\t\tprintln();\n\t}\n}\n","language":"java"} +{"contest_id":"1141","problem_id":"D","statement":"D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1\u2264n\u22641500001\u2264n\u2264150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk \u2014 the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1\u2264aj,bj\u2264n1\u2264aj,bj\u2264n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10\ncodeforces\ndodivthree\nOutputCopy5\n7 8\n4 9\n2 2\n9 10\n3 1\nInputCopy7\nabaca?b\nzabbbcc\nOutputCopy5\n6 5\n2 3\n4 6\n7 4\n1 2\nInputCopy9\nbambarbia\nhellocode\nOutputCopy0\nInputCopy10\ncode??????\n??????test\nOutputCopy10\n6 2\n1 6\n7 3\n3 5\n4 8\n9 7\n5 1\n2 4\n10 9\n8 10\n","tags":["greedy","implementation"],"code":"import java.io.*;\nimport java.util.*;\n\npublic class EvenorOdd {\n\tpublic static void main(String[] args) throws IOException {\n\t\tBufferedReader f = new BufferedReader(new InputStreamReader(System.in));\n\t\tPrintWriter out = new PrintWriter(System.out);\n\t\tint n=Integer.parseInt(f.readLine());\n\t\tString s=f.readLine();\n\t\tString s2=f.readLine();\n\t\tTreeSet[] arr=new TreeSet[27];\n\t\tTreeSet[] barr=new TreeSet[27];\n\t\tfor(int i=0;i<27;i++) {\n\t\t\tarr[i]=new TreeSet();\n\t\t\tbarr[i]=new TreeSet();\n\t\t}\n\t\tfor(int i=0;i= 0) {\n\n\t\t\tx += ft[i];\n\n\t\t\ti &= i + 1; i--;\n\n\t\t}\n\n\t\treturn x;\n\n\t} \n\n\tpublic static void r(int arr[],int l,int m,int r) {\n\n\t\tint n1=m-l+1;\n\n\t\tint n2=r-m;\n\n\t\tint L[]=new int[n1];\n\n\t\tint R[]=new int[n2];\n\n\t\tfor(int i=0;i= 0; h--)\n\n\t\t\thh[ii[h]] = h;\n\n\t\tft = new int[m];\n\n\t\tfor (int i = n - 1; i >= 0; i--) {\n\n\t\t\timax[i] += query(hh[i] - 1);\n\n\t\t\tupdate(hh[i], m, 1);\n\n\t\t}\n\n\t\tArrays.fill(ft, 0);\n\n\t\tArrays.fill(hh, m);\n\n\t\tfor (int h = m - 1; h >= 0; h--) {\n\n\t\t\tint i = ii[h];\n\n\t\t\timax[i] = Math.max(imax[i], query(hh[i] - 1));\n\n\t\t\tupdate(hh[i], m, -1);\n\n\t\t\thh[i] = h;\n\n\t\t\tupdate(hh[i], m, 1);\n\n\t\t}\n\n\t\tfor (int i = 0; i < n; i++)\n\n\t\t\tSystem.out.println((imin[i] + 1) + \" \" + (imax[i] + 1));\n\n\t}\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.Arrays;\n\nimport java.util.Scanner;\n\n\n\npublic class CR622A {\n\n\tpublic static int parts(int a, int b, int c) {\n\n\t\tint count = 0;\n\n\t\tif (a!=0) {\n\n\t\t\tcount++;a--;\n\n\t\t}\n\n\t\tif (c!=0) {\n\n\t\t\tcount++;c--;\n\n\t\t}\n\n\t\tif (b!=0) {\n\n\t\t\tcount++;b--;\n\n\t\t}\n\n\t\tif (a!=0 && b!=0) {\n\n\t\t\tcount++;\n\n\t\t\ta--;b--;\n\n\t\t}\n\n\t\tif (a!=0 && c!=0) {\n\n\t\t\tcount++;\n\n\t\t\ta--;c--;\n\n\t\t}\n\n\t\tif (c!=0 && b!=0) {\n\n\t\t\tcount++;\n\n\t\t\tc--;b--;\n\n\t\t}\n\n\t\t\n\n\t\tif (a!=0 && b!=0 && c!=0) {\n\n\t\t\tcount++;\n\n\t\t}\n\n\t\treturn count;\n\n\t}\n\n\t\n\n\tpublic static void main (String[] args) {\n\n\t\tScanner m = new Scanner(System.in);\n\n\t\tint n = m.nextInt();\n\n\t\tint[] arr = new int[3];\n\n\t\tfor (int i=0; i arrayList = new ArrayList<>();\n\n int count = 0;\n\n int counter = 0;\n\n\n\n\n\n for (int i = 0; i < t; i++) {\n\n arrayList.add(sc.nextInt());\n\n }\n\n\n\n for (int i = 0; i < t * 2; i++) {\n\n if (arrayList.get(i % t) == 1) {\n\n counter++;\n\n count = Math.max(count, counter);\n\n } else {\n\n counter = 0;\n\n }\n\n\n\n }\n\n System.out.println(count);\n\n }\n\n}","language":"java"} +{"contest_id":"1294","problem_id":"A","statement":"A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1\u2264a,b,c,n\u22641081\u2264a,b,c,n\u2264108) \u2014 the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print \"YES\" if Polycarp can distribute all nn coins between his sisters and \"NO\" otherwise.ExampleInputCopy5\n5 3 2 8\n100 101 102 105\n3 2 1 100000000\n10 20 15 14\n101 101 101 3\nOutputCopyYES\nYES\nNO\nNO\nYES\n","tags":["math"],"code":"import java.util.Scanner;\n\n\n\npublic class zas {\n\n public static void main(String[] args) {\n\n Scanner input = new Scanner(System.in);\n\n int t = input.nextInt();\n\n for (int i = 0; i < t; i++) {\n\n int a, b, c, n;\n\n a = input.nextInt();\n\n b = input.nextInt();\n\n c = input.nextInt();\n\n n = input.nextInt();\n\n if ((a + b + c + n) % 3 == 0 && n >= Math.max(Math.max(a, b), c) * 3 - (a + b + c)) {\n\n System.out.println(\"YES\");\n\n } else {\n\n System.out.println(\"NO\");\n\n }\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":"\/\/package assignment;\n\n\n\nimport java.io.PrintWriter;\n\nimport java.util.*;\n\n\n\npublic class TreapMap, V> implements Treap {\n\n TreapNode head;\n\n @Override\n\n public V lookup(K key) {\n\n TreapNode tr = lookupH(key);\n\n if(tr == null) return null;\n\n else return tr.getValue();\n\n }\n\n private TreapNode lookupH(K key) {\n\n TreapNode curr = head;\n\n while (true) {\n\n if(curr == null) return null;\n\n int compareVal = curr.getKey().compareTo(key);\n\n if (compareVal > 0) curr = curr.getLeft();\n\n else if (compareVal < 0) curr = curr.getRight();\n\n else return curr;\n\n }\n\n }\n\n public void insert(K key, V value, int prio) {\n\n TreapNode curr = head;\n\n TreapNode toInsert = new TreapNode<>(key, value, prio);\n\n ArrayList> path = new ArrayList<>();\n\n if(head == null) {\n\n head = toInsert;\n\n return;\n\n }\n\n while (true) {\n\n path.add(curr);\n\n int compareVal = curr.getKey().compareTo(key);\n\n if (compareVal > 0) {\n\n if(curr.getLeft() == null) {\n\n curr.setLeft(toInsert);\n\n break;\n\n }\n\n curr = curr.getLeft();\n\n }\n\n else if(compareVal == 0 && prio != Treap.MAX_PRIORITY) { \/\/ override if we're not adding a split node\n\n curr.setValue(value);\n\n return;\n\n }\n\n else {\n\n if(curr.getRight() == null) {\n\n curr.setRight(toInsert);\n\n break;\n\n }\n\n curr = curr.getRight();\n\n }\n\n }\n\n curr = toInsert;\n\n for(int i = path.size() - 1; i >= 1; i--) {\n\n if(path.get(i).getPrio() < curr.getPrio()) {\n\n if(path.get(i - 1).getLeft() == path.get(i) && path.get(i).getLeft() == curr) {\n\n rotateLL(path.get(i - 1));\n\n }\n\n else if(path.get(i - 1).getLeft() == path.get(i) && path.get(i).getRight() == curr) {\n\n rotateLR(path.get(i - 1));\n\n }\n\n else if(path.get(i - 1).getRight() == path.get(i) && path.get(i).getLeft() == curr) {\n\n rotateRL(path.get(i - 1));\n\n }\n\n else if(path.get(i - 1).getRight() == path.get(i) && path.get(i).getRight() == curr) {\n\n rotateRR(path.get(i - 1));\n\n }\n\n else {\n\n System.out.println(\"insert is BROKEN LOL\");\n\n }\n\n }\n\n else break;\n\n }\n\n if(head.getPrio() < curr.getPrio()) {\n\n if(head.getLeft() == curr) {\n\n head.setLeft(curr.getRight());\n\n curr.setRight(head);\n\n }\n\n else {\n\n head.setRight(curr.getLeft());\n\n curr.setLeft(head);\n\n }\n\n head = curr;\n\n }\n\n }\n\n @Override\n\n public void insert(K key, V value) {\n\n Random r = new Random();\n\n insert(key, value, r.nextInt(Treap.MAX_PRIORITY));\n\n }\n\n\n\n @Override\n\n public V remove(K key) {\n\n TreapNode par = null;\n\n TreapNode curr = head;\n\n while (true) {\n\n if(curr == null) return null;\n\n if(curr.getKey() == null) break; \/\/ join case\n\n int compareVal = curr.getKey().compareTo(key);\n\n if (compareVal > 0) {\n\n par = curr;\n\n curr = curr.getLeft();\n\n }\n\n else if (compareVal < 0) {\n\n par = curr;\n\n curr = curr.getRight();\n\n\n\n }\n\n else break;\n\n }\n\n while(curr.getLeft() != null || curr.getRight() != null) {\n\n int lPrio = -1;\n\n if(curr.getLeft() != null) lPrio = curr.getLeft().getPrio();\n\n int rPrio = -1;\n\n if(curr.getRight() != null) rPrio = curr.getRight().getPrio();\n\n if(rPrio > lPrio) { \/\/ swap with right then\n\n if(par == null) { \/\/ curr = head\n\n TreapNode temp = curr.getRight();\n\n assert temp != null;\n\n curr.setRight(temp.getLeft());\n\n temp.setLeft(curr);\n\n head = temp;\n\n par = temp;\n\n }\n\n else {\n\n TreapNode temp = curr.getRight();\n\n if(par.getLeft() == curr) {\n\n par.setLeft(temp);\n\n }\n\n else {\n\n par.setRight(temp);\n\n }\n\n curr.setRight(temp.getLeft());\n\n temp.setLeft(curr);\n\n par = temp;\n\n }\n\n } else {\n\n if(par == null) { \/\/ curr = head\n\n TreapNode temp = curr.getLeft();\n\n assert temp != null;\n\n curr.setLeft(temp.getRight());\n\n temp.setRight(curr);\n\n head = temp;\n\n par = temp;\n\n }\n\n else {\n\n TreapNode temp = curr.getLeft();\n\n if(par.getLeft() == curr) {\n\n par.setLeft(temp);\n\n }\n\n else {\n\n par.setRight(temp);\n\n }\n\n curr.setLeft(temp.getRight());\n\n temp.setRight(curr);\n\n par = temp;\n\n }\n\n }\n\n }\n\n if(par == null) head = null; \/\/ head = node\n\n else if(par.getLeft() == curr) par.setLeft(null);\n\n else if(par.getRight() == curr) par.setRight(null);\n\n return curr.getValue();\n\n }\n\n\n\n @Override\n\n public Treap[] split(K key) {\n\n Treap[] ans = new TreapMap[2];\n\n this.insert(key, null, Treap.MAX_PRIORITY);\n\n TreapMap t1 = new TreapMap<>();\n\n t1.head = head.getLeft();\n\n TreapMap t2 = new TreapMap<>();\n\n t2.head = head.getRight();\n\n ans[0] = t1;\n\n ans[1] = t2;\n\n return ans;\n\n }\n\n\n\n @Override\n\n public void join(Treap t) {\n\n if(!(t instanceof TreapMap)) throw new IllegalArgumentException();\n\n TreapMap tTr = (TreapMap) t;\n\n TreapNode joiner = new TreapNode<>(null, null, Treap.MAX_PRIORITY);\n\n if(tTr.head.getKey().compareTo(this.head.getKey()) < 0) {\n\n joiner.setLeft(tTr.head);\n\n joiner.setRight(this.head);\n\n }\n\n else {\n\n joiner.setRight(tTr.head);\n\n joiner.setLeft(this.head);\n\n }\n\n head = joiner;\n\n remove(null);\n\n }\n\n\n\n @Override\n\n public void meld(Treap t) throws UnsupportedOperationException {\n\n if(!(t instanceof TreapMap)) return;\n\n meldRec(((TreapMap) t).head);\n\n }\n\n private void meldRec(TreapNode curr) {\n\n if(curr == null) return;\n\n TreapNode oldHead = head;\n\n this.insert(curr.getKey(), curr.getValue(), curr.getPrio());\n\n head = this.lookupH(curr.getKey());\n\n meldRec(curr.getLeft());\n\n meldRec(curr.getRight());\n\n head = oldHead;\n\n }\n\n @Override\n\n public void difference(Treap t) throws UnsupportedOperationException {\n\n if(!(t instanceof TreapMap)) return;\n\n diffRec(((TreapMap) t).head);\n\n }\n\n private void diffRec(TreapNode curr) {\n\n if(curr == null) return;\n\n TreapNode oldHead = head;\n\n TreapNode tr = this.lookupH(curr.getKey());\n\n if(tr != null) {\n\n this.remove(curr.getKey());\n\n this.head = tr;\n\n }\n\n meldRec(curr.getLeft());\n\n meldRec(curr.getRight());\n\n head = oldHead;\n\n }\n\n @Override\n\n public Iterator iterator() {\n\n ArrayList arr = new ArrayList<>();\n\n dfs2(arr, head);\n\n return arr.iterator();\n\n }\n\n\n\n private void dfs2(ArrayList trav, TreapNode curr) {\n\n if(curr == null) return;\n\n dfs2(trav, curr.getLeft());\n\n trav.add(curr.getKey());\n\n dfs2(trav, curr.getRight());\n\n }\n\n @Override\n\n public double balanceFactor() throws UnsupportedOperationException {\n\n return 0;\n\n }\n\n\n\n private void rotateLL(TreapNode p) {\n\n TreapNode c1 = p.getLeft();\n\n TreapNode c2 = c1.getLeft();\n\n TreapNode temp = c2.getRight();\n\n p.setLeft(c2);\n\n c2.setRight(c1);\n\n c1.setLeft(temp);\n\n }\n\n\n\n private void rotateLR(TreapNode p) {\n\n TreapNode c1 = p.getLeft();\n\n TreapNode c2 = c1.getRight();\n\n TreapNode temp = c2.getLeft();\n\n p.setLeft(c2);\n\n c2.setLeft(c1);\n\n c1.setRight(temp);\n\n }\n\n\n\n private void rotateRL(TreapNode p) {\n\n TreapNode c1 = p.getRight();\n\n TreapNode c2 = c1.getLeft();\n\n TreapNode temp = c2.getRight();\n\n p.setRight(c2);\n\n c2.setRight(c1);\n\n c1.setLeft(temp);\n\n }\n\n\n\n private void rotateRR(TreapNode p) {\n\n TreapNode c1 = p.getRight();\n\n TreapNode c2 = c1.getRight();\n\n p.setRight(c2);\n\n TreapNode temp = c2.getLeft();\n\n c2.setLeft(c1);\n\n c1.setRight(temp);\n\n }\n\n private void dfs(ArrayList trav, TreapNode curr) {\n\n if(curr == null) return;\n\n trav.add(String.format(\"[%d] <%s, %s>%n\", curr.getPrio(), curr.getKey().toString(), curr.getValue().toString()));\n\n dfs(trav, curr.getLeft());\n\n dfs(trav, curr.getRight());\n\n }\n\n public String toString() {\n\n StringBuilder sb = new StringBuilder();\n\n ArrayList trav = new ArrayList<>();\n\n dfs(trav, head);\n\n for(String str : trav) sb.append(str);\n\n return sb.toString();\n\n }\n\n\n\n \/\/ testing- proof by ac\n\n \/\/ https:\/\/codeforces.com\/contest\/1278\/problem\/C\n\n public static void main(String[] args) {\n\n Scanner sc = new Scanner(System.in);\n\n PrintWriter pw = new PrintWriter(System.out);\n\n int t = sc.nextInt();\n\n loop:\n\n while(t-- > 0) {\n\n int x = sc.nextInt();\n\n TreapMap hs = new TreapMap<>();\n\n for(int i=1;i<=2*x;i++){\n\n hs.insert(i, 0);\n\n }\n\n int[] arr = new int[2*x];\n\n for(int i=0;i<2*x;i+=2){\n\n arr[i]=sc.nextInt();\n\n hs.remove(arr[i]);\n\n }\n\n \/\/pw.println(hs);\n\n for(int i=1;i<2*x;i+=2){\n\n if(hs.lookup(arr[i-1]+1) != null){\n\n arr[i]=arr[i-1]+1;\n\n hs.remove(arr[i]);\n\n }\n\n else{\n\n for(int j=arr[i-1];j<=2*x;j++){\n\n if(hs.lookup(j) != null){\n\n arr[i]=j;\n\n hs.remove(j);\n\n break;\n\n }\n\n if(j==2*x){\n\n pw.println(-1);\n\n continue loop;\n\n }\n\n }\n\n }\n\n }\n\n for(int trr : arr){\n\n pw.print(trr+\" \");\n\n }\n\n pw.println();\n\n }\n\n pw.close();\n\n }\n\n}\n\nclass TreapNode {\n\n private int prio;\n\n private K key;\n\n private V value;\n\n private TreapNode left;\n\n private TreapNode right;\n\n\n\n public int getPrio() {\n\n return prio;\n\n }\n\n\n\n public V getValue() {\n\n return value;\n\n }\n\n\n\n public K getKey() {\n\n return key;\n\n }\n\n\n\n public TreapNode getLeft() {\n\n return left;\n\n }\n\n\n\n public TreapNode getRight() {\n\n return right;\n\n }\n\n\n\n public void setLeft(TreapNode left) {\n\n this.left = left;\n\n }\n\n\n\n public void setValue(V value) {\n\n this.value = value;\n\n }\n\n\n\n public void setRight(TreapNode right) {\n\n this.right = right;\n\n }\n\n\n\n public TreapNode(K key, V value, int prio) {\n\n this.key = key;\n\n this.value = value;\n\n this.prio = prio;\n\n }\n\n public String toString() {\n\n return String.format(\"{%s, %d}\", this.key.toString(), prio);\n\n }\n\n}\n\ninterface Treap, V> extends Iterable {\n\n\n\n \/**\n\n * The maximum priority that a node can have.\n\n *\/\n\n public static final int MAX_PRIORITY = 65535;\n\n\n\n \/**\n\n * Retrieves the value associated with a key in this dictionary.\n\n * If the key is null or the key is not present in this\n\n * dictionary, this method returns null.\n\n *\n\n * @param key the key whose associated value\n\n * should be retrieved\n\n * @return the value associated with the key, or\n\n * null if the key is null or the key is not in\n\n * this treap\n\n *\/\n\n V lookup(K key);\n\n\n\n \/**\n\n * Adds a key-value pair to this dictionary. Any old value\n\n * associated with the key is lost. If the key or the value is\n\n * null, the pair is not added to the dictionary.\n\n *\n\n * @param key the key to add to this dictionary\n\n * @param value the value to associate with the key\n\n *\/\n\n void insert(K key, V value);\n\n\n\n \/**\n\n * Removes a key from this dictionary. If the key is not present\n\n * in this dictionary, this method does nothing. Returns the\n\n * value associated with the removed key, or null if the key\n\n * is not present.\n\n *\n\n * @param key the key to remove\n\n * @return the associated with the removed key, or null\n\n *\/\n\n V remove(K key);\n\n\n\n \/**\n\n * Splits this treap into two treaps. The left treap should contain\n\n * values less than the key, while the right treap should contain\n\n * values greater than or equal to the key.\n\n *\n\n * @param key the key to split the treap with\n\n * @return the left treap in index 0, the right in index 1\n\n *\/\n\n Treap [] split(K key);\n\n\n\n \/**\n\n * Joins this treap with another treap. If the other treap is not\n\n * an instance of the implementing class, both treaps are unmodified.\n\n * At the end of the join, this treap will contain the result.\n\n * This method may destructively modify both treaps.\n\n *\n\n * @param t the treap to join with\n\n *\/\n\n void join(Treap t);\n\n\n\n \/**\n\n * Melds this treap with another treap. If the other treap is not\n\n * an instance of the implementing class, both treaps are unmodified.\n\n * At the end of the meld, this treap will contain the result. This\n\n * method may destructively modify both treaps.\n\n *\n\n * If you don't implement this method, just throw an\n\n * UnsupportedOperationException.\n\n *\n\n * @param t the treap to meld with. t may be modified.\n\n *\/\n\n void meld(Treap t) throws UnsupportedOperationException;\n\n\n\n \/**\n\n * Removes elements from another treap from this treap. If the\n\n * other treap is not an instance of the implementing class,\n\n * both treaps are unmodified. At the end of the difference,\n\n * this treap will contain no keys that were in the other\n\n * treap. This method may destructively modify both treaps.\n\n *\n\n * If you don't implement this method, just throw an\n\n * UnsupportedOperationException.\n\n *\n\n * @param t a treap containing elements to remove from this\n\n * treap. t may be destructively modified.\n\n *\/\n\n void difference(Treap t) throws UnsupportedOperationException;\n\n\n\n\n\n \/**\n\n * Build a human-readable version of the treap.\n\n * Each node in the treap will be represented as\n\n *\n\n * [priority] \\n\n\n *\n\n * Subtreaps are indented one tab over from their parent for\n\n * printing. This method prints out the string representations\n\n * of key and value using the object's toString(). Treaps should\n\n * be printed in pre-order traversal fashion.\n\n *\/\n\n String toString();\n\n\n\n\n\n \/**\n\n * @return a fresh iterator that points to the first element in\n\n * this assignment.Treap and iterates in sorted order.\n\n *\/\n\n Iterator iterator();\n\n\n\n \/**\n\n * Returns the balance factor of the treap. The balance factor\n\n * is the height of the treap divided by the minimum possible\n\n * height of a treap of this size. A perfectly balanced treap\n\n * has a balance factor of 1.0. If this treap does not support\n\n * balance statistics, throw an exception.\n\n *\n\n * If you don't implement this method, just throw an\n\n * UnsupportedOperationException.\n\n *\/\n\n double balanceFactor() throws UnsupportedOperationException;\n\n}","language":"java"} +{"contest_id":"1300","problem_id":"B","statement":"B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,\u2026,a2k+1][a1,a2,\u2026,a2k+1] of odd number of elements is defined as follows: let [b1,b2,\u2026,b2k+1][b1,b2,\u2026,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u22641041\u2264t\u2264104). The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105)\u00a0\u2014 the number of students halved.The second line of each test case contains 2n2n integers a1,a2,\u2026,a2na1,a2,\u2026,a2n (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3\n1\n1 1\n3\n6 5 4 1 2 3\n5\n13 4 20 13 2 5 8 3 17 16\nOutputCopy0\n1\n5\nNoteIn the first test; there is only one way to partition students\u00a0\u2014 one in each class. The absolute difference of the skill levels will be |1\u22121|=0|1\u22121|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4\u22123|=1|4\u22123|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.","tags":["greedy","implementation","sortings"],"code":"import java.util.*;\n\npublic class Solution\n\n{\n\n public static void main(String[] args)\n\n {\n\n Scanner sc = new Scanner(System.in);\n\n int testCases = sc.nextInt();\n\n \n\n while(testCases != 0)\n\n {\n\n int n = sc.nextInt() * 2;\n\n int[] arr = new int[n];\n\n for(int i = 0; i < n; i++)\n\n {\n\n arr[i] = sc.nextInt();\n\n }\n\n \n\n Arrays.sort(arr);\n\n int mid = arr.length \/ 2;\n\n System.out.println(Math.abs(arr[mid] - arr[mid - 1]));\n\n \n\n testCases -= 1;\n\n }\n\n \n\n return;\n\n }\n\n \n\n private static int getPartition(int[] arr)\n\n {\n\n Arrays.sort(arr);\n\n ArrayList left = new ArrayList<>();\n\n ArrayList right = new ArrayList<>();\n\n \n\n \n\n for(int i = 0; i < arr.length; i++)\n\n {\n\n if(i % 2 == 0)\n\n {\n\n left.add(arr[i]);\n\n }\n\n else\n\n {\n\n right.add(arr[i]);\n\n }\n\n }\n\n \n\n int mid = left.size() \/ 2;\n\n return Math.abs(left.get(mid) - right.get(mid));\n\n \n\n }\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":"import java.util.Scanner;\n\n\n\npublic class Main {\n\n\n\n public static void main(String[] args) {\n\n\n\n Scanner sc = new Scanner(System.in);\n\n long t = sc.nextInt();\n\n\n\n while (t-- > 0) {\n\n int n = sc.nextInt();\n\n int arr[] = new int[n];\n\n long total = 0;\n\n for (int i = 0; i < n; i++) {\n\n arr[i] = sc.nextInt();\n\n total += arr[i];\n\n }\n\n long sum = 0;\n\n long maxi = Long.MIN_VALUE;\n\n ;\n\n for (int i = 0; i < n - 1; i++) {\n\n sum += arr[i];\n\n if (sum > maxi) {\n\n maxi = sum;\n\n }\n\n if (sum < 0) {\n\n sum = 0;\n\n }\n\n }\n\n\n\n sum = 0L;\n\n long maxi2 = Long.MIN_VALUE;\n\n for (int i = 1; i < n; i++) {\n\n sum += arr[i];\n\n if (sum > maxi2) {\n\n maxi2 = sum;\n\n }\n\n if (sum < 0) {\n\n sum = 0;\n\n }\n\n }\n\n\n\n if (total > Math.max(maxi, maxi2)) {\n\n System.out.println(\"YES\");\n\n } else {\n\n System.out.println(\"NO\");\n\n }\n\n }\n\n }\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.io.*;\n\nimport java.util.*;\n\npublic class Codeforces {\n\n public static void solve() {\n\n FastReader input = new FastReader();\n\n int testcases=input.nextInt();\n\n while(testcases-->0){\n\n\t\t\tString str=input.next();\n\n\t\t\tint first=0,last=0;\n\n\t\t\tint count1=0,count0=0;\n\n\t\t\tfor(int i=0;i=0;i--){\n\n\t\t\t\tif(str.charAt(i)=='1'){\n\n\t\t\t\t\tlast=i;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tint count=0;\n\n\t\t\tfor(int i=first;i<=last;i++){\n\n\t\t\t\tif(str.charAt(i)=='0'){\n\n\t\t\t\t\tcount++;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tSystem.out.println(count);\n\n\t\t}\n\n\t\t}\n\n }\n\n public static void input_output() {\n\n try {\n\n System.setIn(new FileInputStream(\"input.txt\"));\n\n \/\/System.setOut(new PrintStream(\"output.txt\"));\n\n } catch (Exception e) {\n\n \/\/System.out.println(\"Error\");\n\n }\n\n }\n\n public static void main(String[] args)throws java.lang.Exception {\n\n if (System.getProperty(\"ONLINE_JUDGE\") == null) {\n\n input_output();\n\n solve();\n\n } \n\n else {\n\n solve();\n\n }\n\n }\n\n public 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() { return Integer.parseInt(next()); }\n\n\n\n long nextLong() { return Long.parseLong(next()); }\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}\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 set = new TreeSet<>();\n\n for(int i = 0; i < n; ++i) {\n\n g[i] = new Node();\n\n set.add(i + 1);\n\n }\n\n for(int i = 0; i < n; ++i) {\n\n int p = rni() - 1, c = ni();\n\n if(p == -1) {\n\n root = g[i];\n\n } else {\n\n g[p].chd.add(g[i]);\n\n }\n\n g[i].c = c + 1;\n\n }\n\n boolean yes = root.dfs(set);\n\n prYN(yes);\n\n if(yes) {\n\n for(int i = 0; i < n; ++i) {\n\n if(i > 0) {\n\n pr(' ');\n\n }\n\n pr(g[i].a);\n\n }\n\n prln();\n\n }\n\n close();\n\n }\n\n\n\n static class Node {\n\n List chd = new ArrayList<>();\n\n int a, c;\n\n\n\n boolean dfs(TreeSet set) {\n\n Iterator iter = set.iterator();\n\n while(c --> 0) {\n\n if(!iter.hasNext()) {\n\n return false;\n\n }\n\n a = iter.next();\n\n }\n\n set.remove(a);\n\n for(Node n : chd) {\n\n if(!n.dfs(set)) {\n\n return false;\n\n }\n\n }\n\n return set.isEmpty() || set.first() > a;\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 \/\/ IRAND ~= 3e8\n\n \/\/ IMAX ~= 2e10\n\n \/\/ LMAX ~= 9e18\n\n \/\/ constants\n\n static final int IBIG = 1000000007;\n\n static final int IRAND = 327859546;\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 \/\/ 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 floori(double d) {return (int)d;}\n\n static int ceili(double d) {return (int)ceil(d);}\n\n static long floorl(double d) {return (long)d;}\n\n static long ceill(double d) {return (long)ceil(d);}\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 reverse(T[] a) {for(int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {T swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}\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 shuffle(char[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); char swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}\n\n static void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}\n\n static void rsort(int[] a) {shuffle(a); Arrays.sort(a);}\n\n static void rsort(long[] a) {shuffle(a); Arrays.sort(a);}\n\n static void rsort(double[] a) {shuffle(a); Arrays.sort(a);}\n\n static void rsort(char[] a) {shuffle(a); Arrays.sort(a);}\n\n static void rsort(T[] a) {shuffle(a); Arrays.sort(a);}\n\n static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}\n\n \/\/ input\n\n static void r() throws IOException {input = new StringTokenizer(__in.readLine());}\n\n static int ri() throws IOException {return Integer.parseInt(__in.readLine());}\n\n static long rl() throws IOException {return Long.parseLong(__in.readLine());}\n\n static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}\n\n static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}\n\n static char[] rcha() throws IOException {return __in.readLine().toCharArray();}\n\n static String rline() throws IOException {return __in.readLine();}\n\n static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}\n\n static int ni() {return Integer.parseInt(input.nextToken());}\n\n static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}\n\n static long nl() {return Long.parseLong(input.nextToken());}\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(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());}\n\n static void h() {__out.println(\"hlfd\");}\n\n static void flush() {__out.flush();}\n\n static void close() {__out.close();}\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.io.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.io.OutputStream;\n\nimport java.io.PrintWriter;\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.Iterator;\n\nimport java.util.LinkedList;\n\nimport java.util.List;\n\nimport java.util.Map;\n\nimport java.util.Map.Entry;\n\nimport java.util.PriorityQueue;\n\nimport java.util.Queue;\n\nimport java.util.Random;\n\nimport java.util.Stack;\n\nimport java.util.StringTokenizer;\n\nimport java.util.TreeMap;\n\nimport java.util.TreeSet;\n\n\n\npublic class hacker49 {\n\n\n\n\tstatic 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\tstatic long[] x= {1,1,1,0,0,0,-1,-1,-1};\n\n\tstatic long[] y= {1,-1,0,-1,0,1,1,-1,0};\n\n\tpublic static void main(String[] args) {\n\n\t\tOutputStream outputStream =System.out;\n\n\t PrintWriter out =new PrintWriter(outputStream);\n\n\t\tFastReader s=new FastReader();\n\n\tlong x=s.nextLong();\n\n\tlong n=s.nextLong();\n\n\tif(x>n) {\n\n\t\tSystem.out.println(-1);\n\n\t}else {\n\n\tif(n==0 && x==0) {\n\n\t\tSystem.out.println(0);\n\n\t}\n\n\telse if(n==x) {\n\n\t\t\tSystem.out.println(1);\n\n\t\t\tSystem.out.println(x);\n\n\t\t}else if(((n-1)^1) ==x){\n\n\t\t\tSystem.out.println(2);\n\n\t\t\tSystem.out.println((n-1)+\" \"+1);\n\n\t\t}\n\n\t\t\t\n\n\t\telse if((n-x)%2==0) {\n\n\t\t\tif(x==0) {\n\n\t\t\t\tSystem.out.println(2);\n\n\t\t\t\tSystem.out.println((n\/2)+\" \"+(n\/2));\n\n\t\t\t}\n\n\t\t\telse {\n\n\t\t\t\t\n\n\t\t\t\tboolean p=false;\n\n\t\t\t\tlong d=(n^x);\n\n\t\t\t\td\/=2;\n\n\t\t\t\tlong k=n-d;\n\n\t\t\t\tif((d^k)==x) {\n\n\t\t\t\t\tSystem.out.println(2);\n\n\t\t\t\t\tSystem.out.println(d+\" \"+k);\n\n\t\t\t\t}else {\n\n\t\t\tSystem.out.println(3);\n\n\t\t\tSystem.out.println(x+\" \"+(n-x)\/2+\" \"+(n-x)\/2);\n\n\t\t}}\n\n\t}else {\n\n\t\tSystem.out.println(-1);\n\n\t}\n\n\t\t}\n\n\t\n\n\t\n\n\t\t\tout.close();\n\n\t}\n\n\t\n\n\tpublic static int[] KMP( String str) {\n\n\t\tint[] a=new int[str.length()];\n\n\t\tint j;\n\n\t\tint i;\n\n for(i=1,j=0;i=qlow && high<=qhigh) {\n\n\t\t\treturn segtree[pos];\n\n\t\t}\n\n\t\tif(qhighhigh) {\n\n\t\t\treturn 0;\n\n\t\t}\n\n\t\tint mid=(low+high)\/2;\n\n\treturn GCD(RS(segtree,qlow,qhigh,low,mid,2*pos+1),RS(segtree,qlow,qhigh,mid+1,high,2*pos+2));\n\n\t}\n\n\tpublic static void US(long[] segtree,int low,int high,int pos ,long new_val,int index,long prev_val,int c,int n) {\n\n\/\/\t\tif(index>high || index> 1; \n\n\t n |= n >> 2; \n\n\t n |= n >> 4; \n\n\t n |= n >> 8; \n\n\t n |= n >> 16; \n\n\t n++; \n\n\t \n\n\t return n; \n\n\t} \n\n\n\n\tpublic static int longest_Repeating_Subsequence(String str,int n) {\n\n\t\tint[][] dp=new int[n+1][n+1];\n\n\t\t\n\n\t\tfor(int i=1;i<=n;i++) {\n\n\t\t\tfor(int j=1;j<=n;j++) {\n\n\t\t\t\tif(str.charAt(i-1)==str.charAt(j-1) && i!=j) {\n\n\t\t\t\t\tdp[i][j]=1+dp[i-1][j-1];\n\n\t\t\t\t}else {\n\n\t\t\t\t\tdp[i][j]=Math.max(dp[i][j-1], dp[i-1][j]);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\t\n\n\t\treturn dp[n][n];\n\n\t}\n\n\tpublic static int d1(ArrayList e,int n,int i) {\n\n\t\tint l=-1;\n\n\t\tint r=n;\n\n\t\t\t\t;\n\n\t\twhile(r>l+1) {\n\n\t\t\tint mid=(l+r)\/2;\n\n\/\/\t\t\tlong h=mid^n;\n\n\/\/\t\t\tSystem.out.println(e.get(mid)+\" \"+mid);\n\n\t\t\tif(e.get(mid)>i) {\n\n\t\t\t\tr=mid;\n\n\t\t\t}else {\n\n\t\t\t\tl=mid;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn r;\n\n\t\t\t\t\n\n\t}\n\n\tpublic static int upper_bound(int[] a ,int x,int n) {\n\n\t\tint l=-1;\n\n\t\tint r=n;\n\n\t\twhile(r>l+1) {\n\n\t\t\tint mid=(l+r)\/2;\n\n\t\t\tif(a[mid]>x) {\n\n\t\t\t\tr=mid;\n\n\t\t\t}else {\n\n\t\t\t\tl=mid;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn r;\n\n\t\t\t\t\n\n\t}\n\n\tpublic static int lower_bound(long[] a ,long x,int n) {\n\n\t\tint l=-1;\n\n\t\tint r=n;\n\n\t\twhile(r>l+1) {\n\n\t\t\tint mid=(l+r)\/2;\n\n\t\t\tif(a[mid]<=x) {\n\n\t\t\t\tl=mid;\n\n\t\t\t}else {\n\n\t\t\t\tr=mid;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn l;\n\n\t\t\t\t\n\n\t}\n\n\tstatic long get=0;\n\n\tstatic int[] ans=new int[200001];\n\n\/\/\tstatic int[] dx= {2,2,-2,-2,-1,-1,1,1};\n\n\/\/\tstatic int[] dy= {1,-1,-1,1,-2,2,-2,2};\n\n\/\/\tstatic int[][] vis1=new int[101][101];\n\n\/\/\tstatic boolean valid(int x,int y,int n) {\n\n\/\/\t\tif(x>=1 && x<=n && y>=1 && y<=n) {\n\n\/\/\t\t\treturn true;\n\n\/\/\t\t}\n\n\/\/\t\treturn false;\n\n\/\/\t}\n\n\/\/\tstatic void dfs(int x,int y,char[][] a,int n,char t) {\n\n\/\/\t\ta[x][y]=t;\n\n\/\/\t\tvis1[x][y]=1;\n\n\/\/\t\tfor(int i=0;i<8;i++) {\n\n\/\/\t\t\tif(valid(x+dx[i],y+dy[i],n) && vis1[x+dx[i]][y+dy[i]]==0) {\n\n\/\/\t\t\t\tdfs(x+dx[i],y+dy[i],a,n,(t=='W')?'B':'W');\n\n\/\/\t\t\t}\n\n\/\/\t\t}\n\n\/\/\t}\n\n \n\n\tstatic int[] par=new int[200001];\n\n\tstatic void bfs() {\n\n\t\tQueue q=new LinkedList<>();\n\n\t\tq.add(1);\n\n\t\tvis[1]=1;\n\n\t\th[1]=1;\n\n\t\twhile(!q.isEmpty()) {\n\n\t\t\tint node=q.poll();\n\n\t\t\t\n\n\t\t\tfor(int i=0;i e=new HashMap<>();\n\n\tstatic ArrayList[] f1=new ArrayList[200001];\t\n\n\tstatic PriorityQueue q=new PriorityQueue<>();\t\n\n\tstatic ArrayList[] f=new ArrayList[200001]; \n\n\/\/\tstatic void bfs() {\n\n\/\/\t\tQueue q=new LinkedList<>();\n\n\/\/\t\tq.add(new node(1,0));\n\n\/\/\t\th[1]=0;\n\n\/\/\t\tvis[1]=1;\n\n\/\/\t\twhile(!q.isEmpty()) {\n\n\/\/\t\t\tnode p=q.poll();\n\n\/\/\/\/\t\t\th[p.a]=p.b;\n\n\/\/\t\t\tfor(int i=0;i{\n\n\t\tprivate long a;\n\n\t\tprivate long b;\n\n\t\tprivate long c;\n\n\t\t\n\n\t\tpair(long a,long b,long c){\n\n\t\t\tthis.a=a;\n\n\/\/\t\t\tthis.f=f;\n\n\t\t\tthis.b=b;\n\n\t\t\tthis.c=c;\n\n\/\/\t\t\tthis.d=d;\n\n\/\/\t\t\tthis.e=e;\n\n\t\t}\n\n\t\tpublic int compareTo(pair o) {\n\n\t\t\tif(o.c!=this.c) {\n\n\/\/\t\t\treturn Integer.compare(o.c, this.c);}\n\n\/\/\t\telse {\n\n\t\t\t\treturn Long.compare(this.c,o.c);\n\n\t\t\t}else {\n\n\t\t\t\treturn Long.compare(this.a*this.b,o.a*o.b);\n\n\t\t\t}\n\n\t\t}\n\n\/\/\t\t\n\n\t\t\n\n\t}\n\n\tstatic class node implements Comparable{\n\n\t\tprivate long a;\n\n\t\tprivate long b;\n\n\t\tprivate long c;\n\n\t\tnode(long a,long b,long 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\tpublic int compareTo(node o) {\n\n\/\/\t\t\treturn Long.compare(arg0, arg1)\n\n\t\t\tif(this.c!=o.c) {\n\n\t\t\t\treturn Long.compare(o.c, this.c);\n\n\t\t\t}else {\n\n\t\t\t\treturn Long.compare(this.b, o.b);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\/\/\tpublic static int upper_bound(long[] a ,long x,int n) {\n\n\/\/\t\tint l=-1;\n\n\/\/\t\tint r=n;\n\n\/\/\t\twhile(r>l+1) {\n\n\/\/\t\t\tint mid=(l+r)\/2;\n\n\/\/\t\t\tif(a[mid]l+1) {\n\n\/\/\t\t\tint mid=(l+r)\/2;\n\n\/\/\t\t\tif(a[mid]>=x) {\n\n\/\/\t\t\t\tr=mid;\n\n\/\/\t\t\t}else {\n\n\/\/\t\t\t\tl=mid;\n\n\/\/\t\t\t}\n\n\/\/\t\t}\n\n\/\/\t\treturn r;\n\n\/\/\t\t\t\t\n\n\/\/\t}\n\n\tpublic static long lb(int n,long[] pre,long k,long a,long b,long x,long y) {\n\n\t\tlong l=0;\n\n\t\tlong r=n+1;\n\n\t\twhile(l=y) {\n\n\t\t\t\tsum+=((pre[(int) a1]-pre[(int) g])*x)\/100;\n\n\t\t\t\tsum+=(((pre[(int)(a1+b1-g)]-pre[(int)(a1)])*y))\/100;\n\n\t\t\t}else {\n\n\t\t\t\tsum+=((pre[(int) b1]-pre[(int) g])*y)\/100;\n\n\t\t\t\tsum+=(((pre[(int)(a1+b1-g)]-pre[(int)(b1)])*x))\/100;\n\n\t\t\t}\n\n\t\t\tif(sum>=k) {\n\n\t\t\t\tr=mid;\n\n\t\t\t}else {\n\n\t\t\t\tl=mid+1;\n\n\t\t\t}\n\n\/\/\t\t\tSystem.out.println(mid+\" \"+h);\n\n\t\t}\n\n\t\t\n\n\t\treturn r;\n\n\t\t\t\t\n\n\t}\n\n\t\n\n\t\n\n\t\n\n\tpublic static long[] merge_sort(long[] A, int start, int end) {\n\n\t\tif (end > start) {\n\n\t\t\tint mid = (end + start) \/ 2;\n\n\t\t\tlong[] v = merge_sort(A, start, mid);\n\n\t\t\tlong[] o = merge_sort(A, mid + 1, end);\n\n\t\t\treturn (merge(v, o));\n\n\t\t} else {\n\n\t\t\tlong[] y = new long[1];\n\n\t\t\ty[0] = A[start];\n\n\t\t\treturn y;\n\n\t\t}\n\n\t}\n\n\tpublic static long[] merge(long a[], long b[]) {\n\n\t\t\n\n\t\tlong[] temp = new long[a.length + b.length];\n\n\t\tint m = a.length;\n\n\t\tint n = b.length;\n\n\t\tint i = 0;\n\n\t\tint j = 0;\n\n\t\tint c = 0;\n\n\t\twhile (i < m && j < n) {\n\n\t\t\tif (a[i] < b[j]) {\n\n\t\t\t\ttemp[c++] = a[i++];\n\n\t\t\t\n\n\t\t\t} else {\n\n\t\t\t\ttemp[c++] = b[j++];\n\n\t\t\t}\n\n\t\t}\n\n\t\twhile (i < m) {\n\n\t\t\ttemp[c++] = a[i++];\n\n\t\t}\n\n\t\twhile (j < n) {\n\n\t\t\ttemp[c++] = b[j++];\n\n\t\t}\n\n\t\treturn temp;\n\n\t}\t\n\n\tpublic static int[] Create(int[] a,int n) {\n\n\t\tint[] b=new int[n+1];\n\n\t\tfor(int i=1;i<=n;i++) {\n\n\t\t\tint j=i;\n\n\t\t\tint h=a[i];\n\n\t\t\twhile(i<=n) {\n\n\t\t\t\tb[i]+=h;\n\n\t\t\t\ti=get_next(i);\n\n\t\t\t}\n\n\t\t\ti=j;\n\n\t\t}\n\n\t\treturn b;\n\n\t}\n\npublic static int get_next(int a) {\n\n\treturn a+(a&-a);\n\n}\n\npublic static int get_parent(int a) {\n\n\treturn a-(a&-a);\n\n}\n\npublic static int query_1(int[] b,int index) {\n\n\tint sum=0;\n\n\tif(index<=0) {\n\n\t\treturn 0;\n\n\t}\n\n\twhile(index>0) {\n\n\t\tsum+=b[index];\n\n\t\tindex=get_parent(index);\n\n\t}\n\n\treturn sum;\n\n}\n\npublic static int query(int[] b,int n,int l,int r) {\n\n\tint sum=0;\n\n\tsum+=query_1(b,r);\n\n\tsum-=query_1(b,l-1);\n\n\treturn sum;\n\n}\n\npublic static void update(int[] a,int[] b,int n,int index,int val) {\n\n\tint diff=val-a[index];\n\n\ta[index]+=diff;\n\n\twhile(index<=n) {\n\n\t\tb[index]+=diff;\n\n\t\tindex=get_next(index);\n\n\t}\t\n\n}\n\n\t\n\n\/\/\tpublic static void Create(int[] a,pair[] segtree,int low,int high,int pos) {\n\n\/\/\t\tif(low>high) {\n\n\/\/\t\t\treturn;\n\n\/\/\t\t}\n\n\/\/\t\tif(low==high) {\n\n\/\/\t\t\tsegtree[pos].b.add(a[low]);\n\n\/\/\t\t\treturn ;\n\n\/\/\t\t}\n\n\/\/\t\tint mid=(low+high)\/2;\n\n\/\/\t\tCreate(a,segtree,low,mid,2*pos);\n\n\/\/\t\tCreate(a,segtree,mid+1,high,2*pos+1);\n\n\/\/\t\tsegtree[pos].b.addAll(segtree[2*pos].b);\n\n\/\/\t\tsegtree[pos].b.addAll(segtree[2*pos+1].b);\n\n\/\/\t}\n\n\/\/\tpublic static void update(pair[] segtree,int low,int high,int index,int pos,int val,int prev) {\n\n\/\/\t\tif(index>high || index=qlow && high<=qhigh) {\n\n\/\/\t\t\treturn segtree[pos];\n\n\/\/\t\t}\n\n\/\/\t\tif(qhighhigh) {\n\n\/\/\t\t\treturn new pair();\n\n\/\/\t\t}\n\n\/\/\t\tint mid=(low+high)\/2;\n\n\/\/\t pair a1=query(segtree,low,mid,qlow,qhigh,2*pos);\n\n\/\/\t pair a2=query(segtree,mid+1,high,qlow,qhigh,2*pos+1);\n\n\/\/\t pair a3=new pair();\n\n\/\/\t a3.b.addAll(a1.b);\n\n\/\/\t a3.b.addAll(a2.b);\n\n\/\/\t return a3;\n\n\/\/\t \n\n\/\/\t}\n\n\/\/\t\n\n\/\/\tpublic static int nextPowerOf2(int n) \n\n\/\/\t{ \n\n\/\/\t n--; \n\n\/\/\t n |= n >> 1; \n\n\/\/\t n |= n >> 2; \n\n\/\/\t n |= n >> 4; \n\n\/\/\t n |= n >> 8; \n\n\/\/\t n |= n >> 16; \n\n\/\/\t n++; \n\n\/\/\t return n; \n\n\/\/\t} \n\n\/\/\t\n\n\/\/\/\/\tstatic class pair implements Comparable{\n\n\/\/\/\/\t\tprivate int a;\n\n\/\/\/\/\t\tprivate long b;\n\n\/\/\/\/\/\/\t\tprivate long c;\n\n\/\/\/\/\t\tpair(int a,long b){\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\tpublic int compareTo(pair o) {\n\n\/\/\/\/\/\/\t\tif(this.a!=o.a) {\n\n\/\/\/\/\/\/\t\t\treturn Long.compare(this.a, o.a);\n\n\/\/\/\/\/\/\t\t}else {\n\n\/\/\/\/\t\t\treturn Long.compare(o.b,this.b);\n\n\/\/\/\/\/\/\t\t}\n\n\/\/\/\/\t\t}\n\n\/\/\/\/\t}\n\n\/\/\tstatic class pair implements Comparable{\n\n\/\/\t\tprivate int a;\n\n\/\/\t\tprivate int b;\n\n\/\/\t\tpair(int a,int b){\n\n\/\/\/\/\t\t\tthis.b=new HashSet<>();\n\n\/\/\t\t\tthis.a=a;\n\n\/\/\t\t\tthis.b=b;\n\n\/\/\t\t}\n\n\/\/\t\tpublic int compareTo(pair o) {\n\n\/\/\t\t\treturn Integer.compare(this.b, o.b);\n\n\/\/\t\t}\n\n\/\/\t}\n\n\tpublic static int lower_bound(ArrayList a ,int n,long x) {\n\n\t\tint l=0;\n\n\t\tint r=n;\n\n\t\twhile(r>l+1) {\n\n\t\t\tint mid=(l+r)\/2;\n\n\t\t\tif(a.get(mid)<=x) {\n\n\t\t\t\tl=mid;\n\n\t\t\t}else {\n\n\t\t\t\tr=mid;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn l;\t\t\n\n\t}\n\n\tpublic static int[] is_prime=new int[10000001];\n\n\tpublic static ArrayList primes=new ArrayList<>();\n\n \tpublic static void sieve() {\n\n\t\tlong maxN=100000000;\n\n\t\tfor(long i=1;i<=maxN;i++) {\n\n\t\t\tis_prime[(int) i]=1;\n\n\t\t}\n\n\t\tis_prime[0]=0;\n\n\t\tis_prime[1]=0;\n\n\t\tfor(long i=2;i*i<=maxN;i++) {\n\n\t\t\tif(is_prime[(int) i]==1) {\n\n\/\/\t\t\t\tprimes.add((int) i);\n\n\t\t\t\tfor(long j=i*i;j<=maxN;j+=i) {\n\n\t\t\t\t\tis_prime[(int) j]=0;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tfor(long i=0;i<=maxN;i++) {\n\n\t\t\tif(is_prime[(int) i]==1) {\n\n\t\t\t\tprimes.add(i);\n\n\t\t\t}\n\n\t\t}\t\t\n\n\t}\n\n\/\/\tpublic static pair[] merge_sort(pair[] A, int start, int end) {\n\n\/\/\t\tif (end > start) {\n\n\/\/\t\t\tint mid = (end + start) \/ 2;\n\n\/\/\t\t\tpair[] v = merge_sort(A, start, mid);\n\n\/\/\t\t\tpair[] o = merge_sort(A, mid + 1, end);\n\n\/\/\t\t\treturn (merge(v, o));\n\n\/\/\t\t} else {\n\n\/\/\t\t\tpair[] y = new pair[1];\n\n\/\/\t\t\ty[0] = A[start];\n\n\/\/\t\t\treturn y;\n\n\/\/\t\t}\n\n\/\/\t}\n\n\/\/\tpublic static pair[] merge(pair a[], pair b[]) {\n\n\/\/\t\tpair[] temp = new pair[a.length + b.length];\n\n\/\/\t\tint m = a.length;\n\n\/\/\t\tint n = b.length;\n\n\/\/\t\tint i = 0;\n\n\/\/\t\tint j = 0;\n\n\/\/\t\tint c = 0;\n\n\/\/\t\twhile (i < m && j < n) {\n\n\/\/\t\t\tif (a[i].b >= b[j].b) {\n\n\/\/\t\t\t\ttemp[c++] = a[i++];\n\n\/\/\t\t\t\n\n\/\/\t\t\t} else {\n\n\/\/\t\t\t\ttemp[c++] = b[j++];\n\n\/\/\t\t\t}\n\n\/\/\t\t}\n\n\/\/\t\twhile (i < m) {\n\n\/\/\t\t\ttemp[c++] = a[i++];\n\n\/\/\t\t}\n\n\/\/\t\twhile (j < n) {\n\n\/\/\t\t\ttemp[c++] = b[j++];\n\n\/\/\t\t}\n\n\/\/\t\treturn temp;\n\n\/\/\t}\n\n\tpublic static long im(long a) {\n\n\t\treturn binary_exponentiation_1(a,mod-2)%mod;\n\n\t}\n\n\tpublic static long binary_exponentiation_1(long a,long n) {\n\n\t\tlong res=1;\n\n\t\twhile(n>0) {\n\n\t\t\tif(n%2!=0) {\n\n\t\t\t\tres=((res)%(mod) * (a)%(mod))%(mod);\n\n\t\t\t\tn--;\n\n\t\t\t}else {\n\n\t\t\t\ta=((a)%(mod) *(a)%(mod))%(mod);\n\n\t\t\t\tn\/=2;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn (res)%(mod);\n\n\t\t\n\n\t}\n\n\tpublic static long b1(long a,long n) {\n\n\t\tlong res=1;\n\n\t\twhile(n>0) {\n\n\t\t\tif(n%2!=0) {\n\n\t\t\t\tres=((res)%(mod) * (a)%(mod))%(mod);\n\n\t\t\t\tn--;\n\n\t\t\t}else {\n\n\t\t\t\ta=((a)%(mod) *(a)%(mod))%(mod);\n\n\t\t\t\tn\/=2;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn (res)%(mod);\n\n\t\t\n\n\t}\n\n\n\n\tpublic static double bn1(double a,double n) {\n\n\t\tdouble res=1;\n\n\t\twhile(n>0) {\n\n\t\t\tif(n%2!=0) {\n\n\/\/\t\t\t\tres=((res)%(1000000007) * (a)%(1000000007))%(1000000007);\n\n\t\t\t\tres=(res*a);\n\n\t\t\t\tn--;\n\n\t\t\t}else {\n\n\/\/\t\t\t\ta=((a)%(1000000007) *(a)%(1000000007))%(1000000007);\n\n\t\t\t\ta=(a*a);\n\n\t\t\t\tn\/=2;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn (res);\t\n\n\t}\n\n\tpublic static long bn(long a,long n) {\n\n\t\tlong res=1;\n\n\t\twhile(n>0) {\n\n\t\t\tif(n%2!=0) {\n\n\t\t\t\tres=res*a;\n\n\t\t\t\tn--;\n\n\t\t\t}else {\n\n\t\t\t\ta*=a;\n\n\t\t\t\tn\/=2;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn res;\n\n\t\t\n\n\t}\n\npublic static long[] fac=new long[300001];\n\npublic static void ff() {\n\n\t\tfac[0]=(long)1;\n\n\t\tfac[1]=(long)1;\n\n\t\tfor(long i=2;i<=300000;i++) {\n\n\t\t\tfac[(int) i]=(fac[(int) (i-1)]*i)%(mod);\n\n\t\t}\n\n\t}\t\n\npublic static long mod=1000000007;\n\npublic static long GCD(long a,long b) {\n\n\t\tif(b==(long)0) {\n\n\t\t\treturn a;\n\n\t\t}\n\n\t\treturn GCD(b , a%b);\n\n\t}\n\npublic static long c=0;\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\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 int L=(y-x);\n\n int jump=a+b;\n\n if(L%jump==0){\n\n System.out.println((int)L\/jump);\n\n }else{\n\n System.out.println(\"-1\");\n\n }\n\n }\n\n }\n\n}\n\n","language":"java"} +{"contest_id":"1294","problem_id":"A","statement":"A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1\u2264a,b,c,n\u22641081\u2264a,b,c,n\u2264108) \u2014 the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print \"YES\" if Polycarp can distribute all nn coins between his sisters and \"NO\" otherwise.ExampleInputCopy5\n5 3 2 8\n100 101 102 105\n3 2 1 100000000\n10 20 15 14\n101 101 101 3\nOutputCopyYES\nYES\nNO\nNO\nYES\n","tags":["math"],"code":"import java.util.*;\n\npublic class Main\n\n{\n\n\tpublic static void main(String[] args) {\n\n Scanner s=new Scanner(System.in);\n\n int n=s.nextInt();\n\n while(n-->0)\n\n {\n\n int a=s.nextInt();\n\n int b=s.nextInt();\n\n int c=s.nextInt();\n\n int q=s.nextInt();\n\n int target=(a+b+c+q)\/3;\n\n if((a<=target)&&(b<=target)&&(c<=target)&&((a+b+c+q)%3==0))\n\n {\n\n System.out.println(\"YES\");\n\n }\n\n else\n\n {\n\n System.out.println(\"NO\");\n\n }\n\n }\n\n}\n\n}\n\n","language":"java"} +{"contest_id":"13","problem_id":"A","statement":"A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A\u2009-\u20091.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3\u2009\u2264\u2009A\u2009\u2264\u20091000).OutputOutput should contain required average value in format \u00abX\/Y\u00bb, where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7\/3InputCopy3OutputCopy2\/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.","tags":["implementation","math"],"code":"import java.math.BigInteger;\n\nimport java.util.Scanner;\n\n\n\npublic class Main {\n\n public static void main(String[] args){\n\n Scanner in = new Scanner(System.in);\n\n int num = in.nextInt();\n\n int div;\n\n int radix = 2;\n\n int res = 0;\n\n while(radix <= num-1){\n\n div = num;\n\n while(div >= radix){\n\n res += div%radix;\n\n div \/= radix;\n\n }\n\n res += div;\n\n radix += 1;\n\n }\n\n\n\n int count = num-2;\n\n int gcd = BigInteger.valueOf(res).gcd(BigInteger.valueOf(count)).intValue();\n\n System.out.println(res\/gcd + \"\/\" + count\/gcd);\n\n }\n\n}\n\n","language":"java"} +{"contest_id":"1295","problem_id":"B","statement":"B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss\u2026t=ssss\u2026 For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q\u2212cnt1,qcnt0,q\u2212cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string \"abcd\" has 5 prefixes: empty string, \"a\", \"ab\", \"abc\" and \"abcd\".InputThe first line contains the single integer TT (1\u2264T\u22641001\u2264T\u2264100) \u2014 the number of test cases.Next 2T2T lines contain descriptions of test cases \u2014 two lines per test case. The first line contains two integers nn and xx (1\u2264n\u22641051\u2264n\u2264105, \u2212109\u2264x\u2264109\u2212109\u2264x\u2264109) \u2014 the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si\u2208{0,1}si\u2208{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers \u2014 one per test case. For each test case print the number of prefixes or \u22121\u22121 if there is an infinite number of such prefixes.ExampleInputCopy4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01\nOutputCopy3\n0\n1\n-1\nNoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.","tags":["math","strings"],"code":"import java.util.*;\n\nimport java.io.*;\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\n\n static void solve() {\n\n int n = i();\n\n int x = i();\n\n \n\n String str = s();\n\n int cnt0 = 0;\n\n for(int i =0;i=0){\n\n ans++;\n\n }\n\n }\n\n if(str.charAt(i)=='0') cbal++;\n\n else cbal--;\n\n }\n\n \n\n System.out.println(ans);\n\n }\n\n\n\n public static void main(String[] args) {\n\n sb = new StringBuilder();\n\n int test = i();\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":"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.*;\nimport java.util.*;\n \npublic class E\n{\n static class SegNode\n {\n int lo, hi, mid;\n int sum, id = -1;\n SegNode left, right;\n\n SegNode(int a, int b)\n {\n lo = a;\n hi = b;\n mid = (lo + hi) \/ 2;\n\n if (lo != hi)\n {\n left = new SegNode(lo, mid);\n right = new SegNode(mid+1, hi);\n }\n }\n\n void set(int pos, int val, int id)\n {\n if (lo == hi)\n {\n sum = val;\n this.id = id;\n return;\n }\n\n if (pos <= mid)\n left.set(pos, val, id);\n else\n right.set(pos, val, id);\n\n sum = left.sum + right.sum;\n }\n\n int sum(int a, int b)\n {\n if (a <= lo && hi <= b)\n return sum;\n\n int val = 0;\n\n if (a <= mid)\n val += left.sum(a, Math.min(mid, b));\n if (mid+1 <= b)\n val += right.sum(Math.max(mid+1, a), b);\n\n return val;\n }\n\n int getId(int pos)\n {\n if (lo == hi)\n return id;\n\n if (pos <= mid)\n return left.getId(pos);\n else\n return right.getId(pos);\n }\n\n }\n static void solve(FastIO io)\n {\n int n = io.nextInt();\n int m = io.nextInt();\n\n int[] msg = new int[m];\n int[] min = new int[n];\n int[] max = new int[n];\n\n for (int i = 0; i < n; i++)\n min[i] = max[i] = i;\n\n for (int i = 0; i < m; i++)\n {\n msg[i] = io.nextInt() - 1;\n\n min[msg[i]] = 0;\n }\n\n int[] pos = new int[n];\n SegNode root = new SegNode(0, n + m);\n\n for (int i = 0; i < n; i++)\n {\n pos[i] = m + i;\n root.set(m+i, 1, i);\n }\n\n int ptr = m - 1;\n\n for (int i = 0; i < m; i++)\n {\n int k = msg[i];\n int p = root.sum(0, pos[k] - 1);\n\n max[k] = Math.max(max[k], p);\n\n root.set(pos[k], 0, -1);\n\n pos[k] = ptr--;\n\n root.set(pos[k], 1, k);\n }\n\n ptr = 0;\n\n for (int i = 0; i < n + m; i++)\n {\n int k = root.getId(i);\n if (k != -1)\n max[k] = Math.max(max[k], ptr++);\n }\n\n for (int i = 0; i < n; i++)\n io.println((min[i] + 1) + \" \" + (max[i] + 1));\n }\n \n public static void main(String[] args) \n {\n FastIO io = new FastIO();\n \n solve(io);\n \n io.close();\n }\n \n static class FastIO extends PrintWriter\n {\n StringTokenizer st = new StringTokenizer(\"\");\n BufferedReader r = new BufferedReader(new InputStreamReader(System.in));\n \n FastIO()\n {\n super(System.out);\n }\n \n String next()\n {\n while (!st.hasMoreTokens())\n {\n try {\n st = new StringTokenizer(r.readLine());\n } catch (Exception e) { }\n }\n return st.nextToken();\n }\n \n int nextInt()\n {\n return Integer.parseInt(next());\n }\n \n long nextLong()\n {\n return Long.parseLong(next());\n }\n \n double nextDouble()\n {\n return Double.parseDouble(next());\n }\n }\n}","language":"java"} +{"contest_id":"1324","problem_id":"F","statement":"F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n\u22121n\u22121 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw\u2212cntbcntw\u2212cntb.InputThe first line of the input contains one integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the number of vertices in the tree.The second line of the input contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u226410\u2264ai\u22641), where aiai is the color of the ii-th vertex.Each of the next n\u22121n\u22121 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1\u2264ui,vi\u2264n,ui\u2260vi(1\u2264ui,vi\u2264n,ui\u2260vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,\u2026,resnres1,res2,\u2026,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9\nOutputCopy2 2 2 2 2 1 1 0 2 \nInputCopy4\n0 0 1 0\n1 2\n1 3\n1 4\nOutputCopy0 -1 1 -1 \nNoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.","tags":["dfs and similar","dp","graphs","trees"],"code":"import java.lang.*;\nimport java.math.*;\nimport java.io.*;\nimport java.security.SecureRandom;\nimport java.util.*;\npublic class Main{\n public static int mod=(int)(1e9) + 7;\n\n public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n public static PrintWriter ot=new PrintWriter(System.out);\n\n public static int[] take_arr(int n){\n int a[]=new int[n];\n try {\n String s[]=br.readLine().trim().split(\" \");\n for(int i=0;i take_list(int n){\n List a=new ArrayList<>();\n try {\n String s[]=br.readLine().trim().split(\" \");\n for(int i=0;i0){\n \n String s[]=br.readLine().trim().split(\" \");\n \n int n = Integer.parseInt(s[0]);\n \/\/ int m = Integer.parseInt(s[1]);\n \/\/ solve(br.readLine());\n \/\/ int k = Integer.parseInt(s[2]);\n \/\/ char ch[] = br.readLine().trim().toCharArray();\n \/\/ int a[] = take_arr(n);\n \/\/ int b[] = take_arr(m);\n \/\/ long n = Long.parseLong(s[0]);\n \/\/ long m = Long.parseLong(s[1]);\n solve(n);\n \/\/ solve()\n \/\/ solve(n, m);\n\n \/\/ solve(ch);\n }\n ot.close();\n br.close();\n }catch(Exception e){\n e.printStackTrace();\n return;\n }\n }\n static void solve(int n) throws IOException{\n String s[] = br.readLine().trim().split(\" \");\n c = new int[n + 1];\n for(int i = 1; i <= n; i++)\n c[i] = Integer.parseInt(s[i - 1]);\n adj = new ArrayList<>();\n for(int i = 0; i <= n; i++)\n adj.add(new ArrayList<>());\n for(int i = 1; i < n; i++){\n s = br.readLine().trim().split(\" \");\n int u = Integer.parseInt(s[0]);\n int v = Integer.parseInt(s[1]);\n adj.get(u).add(v);\n adj.get(v).add(u);\n }\n dp = new int[n + 1];\n ans = new int[n + 1];\n dfs(1, -1);\n dfs2(1, -1);\n for(int i = 1; i <= n; i++)\n ot.print(ans[i] + \" \");\n ot.println();\n }\n static void dfs2(int node, int par){\n ans[node] = dp[node];\n for(int ngr : adj.get(node)){\n if(ngr != par){\n dp[node] -= Math.max(0, dp[ngr]);\n dp[ngr] += Math.max(0, dp[node]);\n dfs2(ngr, node);\n dp[ngr] -= Math.max(0, dp[node]);\n dp[node] += Math.max(0, dp[ngr]);\n }\n }\n }\n static int dfs(int node, int par){\n int ans = (c[node] == 0 ? -1 : 1);\n for(int ngr : adj.get(node)){\n if(ngr != par){\n ans += Math.max(0, dfs(ngr, node));\n }\n }\n return dp[node] = ans;\n }\n static int ans[];\n static int c[];\n static int dp[];\n static List> adj;\n}","language":"java"} +{"contest_id":"1299","problem_id":"C","statement":"C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n), and redistribute water in tanks l,l+1,\u2026,rl,l+1,\u2026,r evenly. In other words, replace each of al,al+1,\u2026,aral,al+1,\u2026,ar by al+al+1+\u22ef+arr\u2212l+1al+al+1+\u22ef+arr\u2212l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1\u2264n\u22641061\u2264n\u2264106)\u00a0\u2014 the number of water tanks.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641061\u2264ai\u2264106)\u00a0\u2014 initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10\u2212910\u22129.Formally, let your answer be a1,a2,\u2026,ana1,a2,\u2026,an, and the jury's answer be b1,b2,\u2026,bnb1,b2,\u2026,bn. Your answer is accepted if and only if |ai\u2212bi|max(1,|bi|)\u226410\u22129|ai\u2212bi|max(1,|bi|)\u226410\u22129 for each ii.ExamplesInputCopy4\n7 5 5 7\nOutputCopy5.666666667\n5.666666667\n5.666666667\n7.000000000\nInputCopy5\n7 8 8 10 12\nOutputCopy7.000000000\n8.000000000\n8.000000000\n10.000000000\n12.000000000\nInputCopy10\n3 9 5 5 1 7 5 3 8 7\nOutputCopy3.000000000\n5.000000000\n5.000000000\n5.000000000\n5.000000000\n5.000000000\n5.000000000\n5.000000000\n7.500000000\n7.500000000\nNoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.","tags":["data structures","geometry","greedy"],"code":"import java.io.IOException;\n\nimport java.io.BufferedReader;\n\nimport java.io.InputStreamReader;\n\nimport java.util.StringTokenizer;\n\nimport java.io.BufferedWriter;\n\nimport java.io.OutputStreamWriter;\n\npublic class Solution {\n\n static Reader input = new Reader();\n\n static int n;\n\n static int[] a;\n\n public static void main(String[] args) throws IOException {\n\n n = input.nextInt();\n\n a = new int[n];\n\n for(int i = 0; i < n; ++i) {\n\n a[i] = input.nextInt();\n\n }\n\n long[] dp = new long[n];\n\n int[] next = new int[n];\n\n double[] answer = new double[n];\n\n answer[n-1] = a[n-1];\n\n next[n-1] = n-1;\n\n dp[n-1] = a[n-1];\n\n for(int i = n-2; i > -1; --i) {\n\n dp[i] = a[i];\n\n next[i] = i;\n\n for(int j = i+1; j < n; j = next[j]+1) {\n\n if(((double)dp[i]\/(double)(next[i]-i+1)) >= answer[j]) {\n\n next[i] = next[j];\n\n dp[i] += dp[j];\n\n } else break;\n\n }\n\n answer[i] = (double)dp[i]\/(double)(next[i]-i+1);\n\n }\n\n BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));\n\n int i = 0, j;\n\n String temp;\n\n while(i < n) {\n\n temp = String.format(\"%.9f\", answer[i]);\n\n for(j = i; j <= next[i]; ++j) {\n\n writer.write(temp+\"\\n\");\n\n }\n\n i = j;\n\n }\n\n writer.flush();\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 }\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":"\/*\n\n * To change this license header, choose License Headers in Project Properties.\n\n * To change this template file, choose Tools | Templates\n\n * and open the template in the editor.\n\n *\/\n\n\n\nimport java.io.BufferedWriter;\n\nimport java.io.DataInputStream;\n\nimport java.io.FileInputStream;\n\nimport java.io.FileOutputStream;\n\nimport java.io.IOException;\n\nimport java.io.OutputStreamWriter;\n\n\n\n\/**\n\n *\n\n * @author kacho\n\n *\/\n\npublic class Codeforce {\n\n \n\n static class Reader { \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 \n\n static int n;\n\n static int arr[][][];\n\n static char res[][];\n\n\n\n \/**\n\n * @param args the command line arguments\n\n *\/\n\n public static void main(String[] args) throws Exception {\n\n Reader rd = new Reader();\n\n BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new\n\n FileOutputStream(java.io.FileDescriptor.out), \"ASCII\"), 512);\n\n n = rd.nextInt();\n\n arr = new int[n][n][2];\n\n res = new char[n][n];\n\n for (int i = 0; i < n; i++) {\n\n for (int j = 0; j < n; j++) {\n\n arr[i][j][0] = rd.nextInt();\n\n arr[i][j][1] = rd.nextInt();\n\n }\n\n }\n\n \n\n for (int i = 0; i < n; i++) {\n\n for (int j = 0; j < n; j++) {\n\n if (arr[i][j][0] == -1) {\n\n if (res[i][j] != '\\u0000') continue;\n\n if (i < n - 1 && arr[i + 1][j][0] == -1) {\n\n res[i][j] = 'D';\n\n res[i + 1][j] = 'U';\n\n } else if (j < n - 1 && arr[i][j + 1][0] == -1) {\n\n res[i][j] = 'R';\n\n res[i][j + 1] = 'L';\n\n } else if (i > 0 && arr[i - 1][j][0] == -1) {\n\n res[i][j] = 'U';\n\n res[i - 1][j] = 'D';\n\n } else if (j > 0 && arr[i][j - 1][0] == -1) {\n\n res[i][j] = 'L';\n\n res[i][j - 1] = 'R';\n\n } else {\n\n System.out.println(\"INVALID\");\n\n return;\n\n }\n\n } else if (i == arr[i][j][0] - 1 && j == arr[i][j][1] - 1) {\n\n dfs(arr[i][j][0] - 1, arr[i][j][1] - 1, 'X');\n\n }\n\n }\n\n }\n\n \n\n for (char[] charr : res) {\n\n for (char ch : charr)\n\n if (ch == '\\u0000') {\n\n System.out.println(\"INVALID\");\n\n return;\n\n }\n\n }\n\n \n\n System.out.println(\"VALID\");\n\n \n\n for (char[] charr : res) {\n\n for (char ch : charr)\n\n out.write(ch);\n\n out.write('\\n');\n\n }\n\n out.flush();\n\n }\n\n \n\n static void dfs(int i, int j, char ch) {\n\n if (res[i][j] != '\\u0000') return;\n\n res[i][j] = ch;\n\n if (i < n - 1 && arr[i + 1][j][0] == arr[i][j][0] && arr[i + 1][j][1] == arr[i][j][1])\n\n dfs(i + 1, j, 'U');\n\n if (j < n - 1 && arr[i][j + 1][0] == arr[i][j][0] && arr[i][j + 1][1] == arr[i][j][1])\n\n dfs(i, j + 1, 'L');\n\n if (i > 0 && arr[i - 1][j][0] == arr[i][j][0] && arr[i - 1][j][1] == arr[i][j][1])\n\n dfs(i - 1, j, 'D');\n\n if (j > 0 && arr[i][j - 1][0] == arr[i][j][0] && arr[i][j - 1][1] == arr[i][j][1])\n\n dfs(i, j - 1, 'R');\n\n }\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\n\n\npublic class AddOddSubEven {\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 while (t-- > 0) {\n\n long a = sc.nextLong();\n\n long b = sc.nextLong();\n\n if (a == b)\n\n System.out.println(0);\n\n else {\n\n long sub = b - a;\n\n if (sub > 0) {\n\n if (sub % 2 != 0)\n\n System.out.println(1);\n\n else\n\n System.out.println(2);\n\n } else {\n\n if (sub % 2 == 0)\n\n System.out.println(1);\n\n else\n\n System.out.println(2);\n\n }\n\n }\n\n }\n\n }\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.io.*;\n\nimport java.util.*;\n\n\n\npublic class CF1303C {\n\n static String alp = \"abcdefghijklmnopqrstuvwxyz\";\n\n public static void main(String[] args) throws IOException{\n\n BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n\n int t = Integer.parseInt(in.readLine());\n\n Outer:\n\n for (int x = 0; x < t; x++) {\n\n String s = in.readLine();\n\n String result = \"\"+s.charAt(0);\n\n for (int i = 1; i < s.length(); i++) {\n\n char c = s.charAt(i);\n\n char d = s.charAt(i-1);\n\n int idx1 = result.indexOf(c);\n\n int idx2 = result.indexOf(d);\n\n if (idx1 == idx2) {\n\n System.out.println(\"NO\");\n\n continue Outer;\n\n }\n\n if (idx1 < 0) {\n\n if (idx2 == 0) result = c+result;\n\n else if (idx2 == result.length()-1) result += c;\n\n else {\n\n System.out.println(\"NO\");\n\n continue Outer;\n\n }\n\n }\n\n else {\n\n if (Math.abs(idx1-idx2) != 1) {\n\n System.out.println(\"NO\");\n\n continue Outer;\n\n }\n\n }\n\n }\n\n for (int i = 0; i < 26; i++) {\n\n if (!result.contains(\"\"+alp.charAt(i))) result += alp.charAt(i);\n\n }\n\n System.out.println(\"YES\");\n\n System.out.println(result);\n\n }\n\n }\n\n}","language":"java"} +{"contest_id":"1299","problem_id":"A","statement":"A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)\u2212yf(x,y)=(x|y)\u2212y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)\u22126=15\u22126=9f(11,6)=(11|6)\u22126=15\u22126=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,\u2026,an][a1,a2,\u2026,an] is defined as f(f(\u2026f(f(a1,a2),a3),\u2026an\u22121),an)f(f(\u2026f(f(a1,a2),a3),\u2026an\u22121),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105).The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u22641090\u2264ai\u2264109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4\n4 0 11 6\nOutputCopy11 6 4 0InputCopy1\n13\nOutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.","tags":["brute force","greedy","math"],"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.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 *\n * @author Manav\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 AAnuHasAFunction solver = new AAnuHasAFunction();\n solver.solve(1, in, out);\n out.close();\n }\n\n static class AAnuHasAFunction {\n public void solve(int testNumber, InputReader in, OutputWriter out) {\n int n = in.nextInt();\n int[] a = in.nextIntArray(n);\n int[] bits = new int[32];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < 32; j++) {\n if ((a[i] & (1 << j)) > 0) {\n bits[j]++;\n }\n }\n }\n\/\/ out.println(bits);\n int max = -1;\n for (int j = 31; j >= 0; j--) {\n if (bits[j] == 1) {\n max = j;\n break;\n }\n }\n\/\/ out.println(max);\n int[] ans = new int[n];\n if (max == -1) {\n ans = a;\n } else {\n int first = -1;\n for (int i = 0; i < n; i++) {\n if ((a[i] & (1 << max)) > 0) {\n first = a[i];\n break;\n }\n }\n\/\/ out.println(first,\"first\");\n int j = 1;\n if (max != -1 && first != -1) {\n ans[0] = first;\n for (int i = 0; i < n; i++) {\n if (a[i] != first && first != 0) {\n ans[j++] = a[i];\n }\n }\n } else {\n Arrays.sort(a);\n out.println(a);\n }\n\n }\n\n out.println(ans);\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 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 int[] nextIntArray(int n) {\n int[] array = new int[n];\n for (int i = 0; i < n; ++i) array[i] = nextInt();\n return array;\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(int[] array) {\n for (int i = 0; i < array.length; i++) {\n if (i != 0) {\n writer.print(' ');\n }\n writer.print(array[i]);\n }\n }\n\n public void println(int[] array) {\n print(array);\n writer.println();\n }\n\n public void close() {\n writer.close();\n }\n\n }\n}\n\n","language":"java"} +{"contest_id":"13","problem_id":"A","statement":"A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A\u2009-\u20091.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3\u2009\u2264\u2009A\u2009\u2264\u20091000).OutputOutput should contain required average value in format \u00abX\/Y\u00bb, where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7\/3InputCopy3OutputCopy2\/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.","tags":["implementation","math"],"code":"\/**\n\n * 10\/31\/21 night\n\n * https:\/\/codeforces.com\/problemset\/problem\/13\/A\n\n *\/\n\n\/\/ package codeforce.practice.L1000;\n\n\n\nimport java.util.*;\n\nimport java.io.*;\n\n\n\npublic class A13 {\n\n\n\n static PrintWriter pw;\n\n\n\n void solve(int a) {\n\n int res = 0, divide = a - 2;\n\n for (int base = 2; base < a; base++) {\n\n int sum = sumOfDigit(a, base);\n\n res += sum;\n\n }\n\n int g = gcd(res, divide);\n\n res \/= g;\n\n divide \/= g;\n\n pr(res + \"\/\" + divide);\n\n }\n\n\n\n int sumOfDigit(int x, int base) {\n\n int res = 0;\n\n while (x > 0) {\n\n res += x % base;\n\n x \/= base;\n\n }\n\n return res;\n\n }\n\n\n\n int gcd(int a, int b) {\n\n return b == 0 ? a : gcd(b, a % b);\n\n }\n\n\n\n private void run() {\n\n \/\/ read_write_file(); \/\/ comment this before submission\n\n FastScanner fs = new FastScanner();\n\n int a = fs.nextInt();\n\n solve(a);\n\n }\n\n\n\n private final String INPUT = \"input.txt\";\n\n private final String OUTPUT = \"output.txt\";\n\n\n\n void read_write_file() {\n\n FileInputStream instream = null;\n\n PrintStream outstream = null;\n\n try {\n\n instream = new FileInputStream(INPUT);\n\n outstream = new PrintStream(new FileOutputStream(OUTPUT));\n\n System.setIn(instream);\n\n System.setOut(outstream);\n\n } catch (Exception e) {\n\n }\n\n }\n\n\n\n public static void main(String[] args) {\n\n pw = new PrintWriter(System.out);\n\n new A13().run();\n\n pw.close();\n\n }\n\n\n\n void pr(int num) {\n\n pw.println(num);\n\n }\n\n\n\n void pr(long num) {\n\n pw.println(num);\n\n }\n\n\n\n void pr(double num) {\n\n pw.println(num);\n\n }\n\n\n\n void pr(String s) {\n\n pw.println(s);\n\n }\n\n\n\n void pr(char c) {\n\n pw.println(c);\n\n }\n\n\n\n class FastScanner {\n\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n StringTokenizer st = new StringTokenizer(\"\");\n\n\n\n String next() {\n\n while (!st.hasMoreTokens())\n\n try {\n\n st = new StringTokenizer(br.readLine());\n\n } catch (IOException e) {\n\n e.printStackTrace();\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 int[] readArray(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 return a;\n\n }\n\n\n\n Integer[] readIntegerArray(int n) {\n\n Integer[] a = new Integer[n];\n\n for (int i = 0; i < n; i++)\n\n a[i] = nextInt();\n\n return a;\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 void tr(Object... o) {\n\n pw.println(Arrays.deepToString(o));\n\n }\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 (x0s>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.*;\n\nimport java.math.*;\n\nimport java.io.*;\n\n\n\npublic class Main {\n\n\n\n\tstatic ArrayList prime = new ArrayList<>();\n\n\tstatic int mod = (int)(1e9\t+ 7 ) ;\n\n\tstatic ArrayList arr;\n\n\tstatic ArrayList prefix;\n\n\tstatic ArrayList pre = new ArrayList<>();\n\n\tstatic final long LMAX = 9223372036854775807L;\n\n\tstatic ArrayList arr1 = new ArrayList<>();\n\n\tstatic ArrayList> vis = new ArrayList<>();\n\n\tstatic int dr[] = {1, 0, -1, 0};\n\n\tstatic int dc[] = {0, -1, 0, 1};\n\n\n\n\n\n\tstatic class FastReader {\n\n\t\tBufferedReader br;\n\n\t\tStringTokenizer st;\n\n\t\tpublic FastReader() {\n\n\t\t\tbr = new BufferedReader(new InputStreamReader(System.in));\n\n\t\t}\n\n\t\tString next() {\n\n\t\t\twhile (st == null || !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\t}\n\n\t\t\treturn st.nextToken();\n\n\t\t}\n\n\t\tint nextInt() {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\t\tlong nextLong() {\n\n\t\t\treturn Long.parseLong(next());\n\n\t\t}\n\n\t\tdouble nextDouble() {\n\n\t\t\treturn Double.parseDouble(next());\n\n\t\t}\n\n\t\tString nextLine() {\n\n\t\t\tString str = \"\";\n\n\t\t\ttry {\n\n\t\t\t\tstr = br.readLine().trim();\n\n\t\t\t} catch (Exception e) {\n\n\t\t\t\te.printStackTrace();\n\n\t\t\t}\n\n\t\t\treturn str;\n\n\t\t}\n\n\t}\n\n\tstatic class FastWriter {\n\n\t\tprivate final BufferedWriter bw;\n\n\t\tpublic FastWriter() {\n\n\t\t\tthis.bw = new BufferedWriter(new OutputStreamWriter(System.out));\n\n\t\t}\n\n\t\tpublic void print(Object object) throws IOException {\n\n\t\t\tbw.append(\"\" + object);\n\n\t\t}\n\n\t\tpublic void println(Object object) throws IOException {\n\n\t\t\tprint(object);\n\n\t\t\tbw.append(\"\\n\");\n\n\t\t}\n\n\t\tpublic void close() throws IOException {\n\n\t\t\tbw.close();\n\n\t\t}\n\n\t}\n\n\tpublic static class Pair {\n\n\t\tint first;\n\n\t\tint second;\n\n\t\tPair(int first , int second ) {\n\n\t\t\tthis.first = first ;\n\n\t\t\tthis.second = second;\n\n\t\t}\n\n\t}\n\n\n\n\n\n\tpublic static void main(String[] args) {\n\n\t\ttry {\n\n\t\t\tFastReader in = new FastReader();\n\n\t\t\tFastWriter out = new FastWriter();\n\n\n\n\n\n\t\t\t\/\/ Collections.sort(arr, new Comparator() {\n\n\t\t\t\/\/ \t\t@Override public int compare(Pair o1, Pair o2) {\n\n\t\t\t\/\/ \t\t\tif (o1.second < o2.second ) { \/\/ change (>) for desending order\n\n\t\t\t\/\/ \t\t\t\treturn -1;\n\n\t\t\t\/\/ \t\t\t} else if (o1.second == o2.second ) {\n\n\t\t\t\/\/ \t\t\t\treturn 0;\n\n\t\t\t\/\/ \t\t\t} else {\n\n\t\t\t\/\/ \t\t\t\treturn 1;\n\n\t\t\t\/\/ \t\t\t}\n\n\t\t\t\/\/ \t\t}\n\n\t\t\t\/\/ \t});\n\n\n\n\n\n\t\t\t\/\/ int testcases = in.nextInt();\n\n\n\n\n\n\n\n\t\t\tint testcases = 1;\n\n\n\n\t\t\twhile ( testcases -- > 0 ) {\n\n\t\t\t\tlong ans1 = 0, ans2 = 0, ans3 = 0, ans4 = 0;\n\n\n\n\n\n\t\t\t\tdouble n = in.nextDouble();\n\n\n\n\t\t\t\tdouble ans = 0.0 ;\n\n\t\t\t\tfor ( int i = 1; i <= n; ++i ) {\n\n\t\t\t\t\tdouble x = (double) 1 \/ i ;\n\n\t\t\t\t\tans += x ;\n\n\t\t\t\t\t\/\/ out.print(x);\n\n\t\t\t\t}\n\n\t\t\t\tout.println(ans);\n\n\n\n\n\n\n\n\n\n\t\t\t}\n\n\n\n\n\n\n\n\t\t\tout.close();\n\n\n\n\t\t} catch (Exception e) {\n\n\t\t\treturn;\n\n\t\t}\n\n\t}\n\n\n\n\n\n\tprivate static void dfs(int i, int j , int n , int m , char arr[][] ) {\n\n\t\tif ( arr[i][j] == '#' ) return ;\n\n\t\tarr[i][j] = '#';\n\n\t\t\/\/ ~~~~~\n\n\t\tfor ( int k = 0; k < 4; ++k ) {\n\n\t\t\tint x = dr[k] + i;\n\n\t\t\tint y = dc[k] + j;\n\n\t\t\tif ( x >= 0 && x < n && y >= 0 && y < m && arr[x][y] == '.' ) {\n\n\t\t\t\tdfs(x, y, n , m , arr );\n\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/ ~~~~~\n\n\t}\n\n\n\n\tprivate static void bfs( Stack q, char[][] arr , int[][] vis ) {\n\n\t\tint n = arr.length;\n\n\t\tint m = arr[0].length;\n\n\t\twhile (!q.isEmpty()) {\n\n\t\t\tint i = q.peek().first;\n\n\t\t\tint j = q.peek().second;\n\n\t\t\tvis[i][j] = 1;\n\n\t\t\tq.pop();\n\n\t\t\tint dr[] = {1, 0, -1, 0};\n\n\t\t\tint dc[] = {0, -1, 0, 1};\n\n\t\t\tfor ( int k = 0; k < 4; ++k ) {\n\n\t\t\t\tint x = dr[k] + i;\n\n\t\t\t\tint y = dc[k] + j;\n\n\t\t\t\tif ( x >= 0 && x < n && y >= 0 && y < m && arr[x][y] == '.' && vis[x][y] != 1 ) {\n\n\t\t\t\t\tq.add(new Pair(x, y));\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\tpublic static boolean isSatisfy( ArrayList arr , int l , int r ) {\n\n\t\tint ans = 0;\n\n\t\tif ( l == 0 || arr.get(l) < arr.get(l - 1) ) ans++;\n\n\t\tif ( r == arr.size() - 1 || arr.get(r) < arr.get(r + 1) ) ans++;\n\n\t\tif ( ans == 2 ) return true;\n\n\t\treturn false;\n\n\t}\n\n\n\n\tpublic static ArrayList prefixSum() {\n\n\n\n\t\tint mod = 100000;\n\n\t\t\/\/ ArrayList arr ;\n\n\t\tArrayList prefix = new ArrayList<>();\n\n\t\tlong prev = 0;\n\n\t\tfor ( long i = 0; i <= mod; ++i ) {\n\n\t\t\tprev += i;\n\n\t\t\tprefix.add(prev);\n\n\t\t}\n\n\t\treturn prefix;\n\n\t}\n\n\n\n\tpublic static long sumRem(int x ) {\n\n\t\tif ( x <= 1 ) return 1;\n\n\t\treturn x + sumRem(x - 1);\n\n\t}\n\n\n\n\tpublic static boolean isSquare( int n ) {\n\n\t\tint sqrt = (int) Math.sqrt(n);\n\n\t\treturn (sqrt * sqrt == n );\n\n\t}\n\n\tpublic static void swap ( int l , int r , ArrayList a ) {\n\n\t\tint t = a.get(l) ;\n\n\t\ta.add(l, a.get(r) );\n\n\t\ta.add(r, t);\n\n\t}\n\n\tpublic static void fib( int a , int b , int n) {\n\n\t\tint x = Math.floorMod(a, mod);\n\n\t\tint y = Math.floorMod(b, mod);\n\n\t\tarr = new ArrayList<>();\n\n\t\tarr.add(a);\n\n\t\tarr.add(b);\n\n\t\tfor ( int i = 2; i <= n; ++i ) {\n\n\t\t\tint cur = Math.floorMod((y - x), mod);\n\n\t\t\tx = y;\n\n\t\t\ty = cur;\n\n\t\t\tarr.add(y);\n\n\t\t}\n\n\t}\n\n\tpublic static String reverseString( String s1 ) {\n\n\t\tString s = \"\";\n\n\t\tfor ( int i = s1.length() - 1; i >= 0; --i ) {\n\n\t\t\ts += s1.charAt(i);\n\n\t\t}\n\n\t\treturn s;\n\n\t}\n\n\n\n\tpublic static long countSetBits(long n) {\n\n\t\tlong count = 0;\n\n\t\twhile (n > 0) {\n\n\t\t\tcount += n & 1;\n\n\t\t\tn >>= 1;\n\n\t\t}\n\n\t\treturn count;\n\n\t}\n\n\tpublic static void sortbykey(HashMap map) {\n\n\t\tTreeMap sorted = new TreeMap<>();\n\n\t\tsorted.putAll(map);\n\n\t}\n\n\n\n\tpublic static long sum(int n) {\n\n\t\tif ( n <= 1 ) return n;\n\n\t\treturn n + sum(n - 1);\n\n\t}\n\n\n\n\tpublic static ArrayList prefix( ArrayList arr1 ) {\n\n\t\tCollections.sort(arr1);\n\n\t\tArrayList arr = new ArrayList<>();\n\n\t\tlong prefix = 0;\n\n\t\tfor ( int i = 0; i < arr1.size(); ++i ) {\n\n\t\t\tprefix += arr1.get(i);\n\n\t\t\tarr.add(prefix);\n\n\t\t}\n\n\t\treturn arr;\n\n\t}\n\n\n\n\tpublic static int solve(int[][] m, int n) {\n\n\t\tint ans = 0;\n\n\t\tint vis[][] = new int[n][n];\n\n\t\tint di[] = {1, 0, 0, -1};\n\n\t\tint dj[] = {0, -1, 1, 0};\n\n\t\tif (m[0][0] == 1) mazerunner(0, 0, m, n, ans, \"\", vis, di, dj);\n\n\t\treturn ans;\n\n\t}\n\n\tpublic static void mazerunner(int i, int j, int m[][], int n, int ans, String move, int vis[][], int di[] , int dj[]) {\n\n\t\tif ( i == n - 1 && j == n - 1) {\n\n\t\t\tans++;\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tString dir = \"DLRU\";\n\n\t\tfor (int ind = 0; ind < 4; ind++) {\n\n\t\t\tint nexti = i + di[ind];\n\n\t\t\tint nextj = j + dj[ind];\n\n\t\t\tif (nexti >= 0 && nextj >= 0 && nexti < n && nextj < n && vis[nexti][nextj] == 0 && m[nexti][nextj] == 1) {\n\n\t\t\t\tvis[i][j] = 0;\n\n\t\t\t\tmazerunner(nexti, nextj, m, n, ans, move + dir.charAt(ind), vis, di, dj);\n\n\t\t\t\tvis[i][j] = -1;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tpublic static long pow( long k , long n ) {\n\n\t\tlong ans = 1;\n\n\t\twhile ( n > 0 ) {\n\n\t\t\tif ( n % 2 == 1 ) {\n\n\t\t\t\tans = (ans * k) % mod;\n\n\t\t\t\tn--;\n\n\t\t\t} else {\n\n\t\t\t\tk = (k * k) % mod;\n\n\t\t\t\tn \/= 2;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn ans % mod;\n\n\t}\n\n\n\n\tpublic static long fact(long n ) {\n\n\t\tlong ans = 0;\n\n\t\tfor (int i = 1; i < n; ++i) {\n\n\t\t\tans += (long)i;\n\n\t\t}\n\n\t\treturn ans;\n\n\t}\n\n\tpublic static boolean isValid( long mid, long arr[] , long k ) {\n\n\n\n\t\tlong req = 0;\n\n\n\n\t\tfor ( int i = 1; i < arr.length; ++i) {\n\n\t\t\treq += Math.min( (arr[i] - arr[i - 1] ) , mid );\n\n\t\t}\n\n\t\treq += mid;\n\n\n\n\t\tif ( req >= k ) return true;\n\n\n\n\t\treturn false;\n\n\t}\n\n\n\n\tpublic static String sortString(String inputString) {\n\n\t\tchar tempArray[] = inputString.toCharArray();\n\n\t\tArrays.sort(tempArray);\n\n\t\treturn new String(tempArray);\n\n\t}\n\n\n\n\tprivate static void reverse( ArrayList arr , int i, int j ) {\n\n\t\twhile ( i <= j ) {\n\n\t\t\tswap( arr, i, j);\n\n\t\t\ti++; j--;\n\n\t\t}\n\n\t}\n\n\n\n\tprivate static void swap( ArrayList arr , int i, int j ) {\n\n\t\tlong temp = arr.get(i);\n\n\t\tarr.set(i, arr.get(j));\n\n\t\tarr.set(j, temp);\n\n\t}\n\n\n\n\n\n\tprivate static boolean isPrime(long n ) {\n\n\t\tif ( n == 1 ) return true;\n\n\n\n\t\tfor ( int i = 2; i <= Math.sqrt(n); i++) {\n\n\t\t\tif ( n % i == 0 ) {\n\n\t\t\t\treturn false ;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\tprivate static boolean[] sieve() {\n\n\t\tint n = 100000000;\n\n\t\tboolean sieve[] = new boolean[n + 1];\n\n\t\tArrays.fill(sieve, 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\tsieve[j] = false;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn sieve;\n\n\t}\n\n\tprivate static ArrayList generatePrimes(int n ) {\n\n\t\tboolean sieve[] = sieve();\n\n\t\tfor ( int i = 2; i <= n; i++) {\n\n\t\t\tif ( sieve[i] == true ) {\n\n\t\t\t\tprime.add(i);\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn prime;\n\n\t}\n\n\tprivate static void segmentedSieve( int l , int r ) {\n\n\t\tint n = (int) Math.sqrt(r);\n\n\t\tArrayList pr = generatePrimes(n);\n\n\t\tint dummy[] = new int[r - l + 1];\n\n\t\tArrays.fill(dummy, 1);\n\n\n\n\t\tfor ( int p : pr ) {\n\n\n\n\t\t\tint firstMultiple = (l \/ p) * p;\n\n\t\t\tif ( firstMultiple < l ) firstMultiple += p;\n\n\t\t\tfor ( int j = Math.max(firstMultiple, p * p); j <= r; j += p) {\n\n\t\t\t\tdummy[j - l] = 0;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tfor ( int i = l; i <= r; i++) {\n\n\t\t\tif ( dummy[i - l] == 1 ) {\n\n\t\t\t\tSystem.out.println(i);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tprivate static int[] primeFactors() {\n\n\t\tint n = 1000000;\n\n\t\tint prime[] = new int[n + 1];\n\n\t\tfor (int i = 1; i <= n; i++) {\n\n\t\t\tprime[i] = i;\n\n\t\t}\n\n\t\tfor (int i = 2; i * i <= n; i++) {\n\n\t\t\tif ( prime[i] == i ) {\n\n\t\t\t\tfor (int j = i * i; j <= n; j += i) {\n\n\t\t\t\t\tif ( prime[j] == j ) {\n\n\t\t\t\t\t\tprime[j] = i;\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\treturn prime;\n\n\t}\n\n\n\n\n\n\tprivate static boolean isPalindrome(String s ) {\n\n\t\tint i = 0, j = s.length() - 1;\n\n\t\twhile ( i <= j ) {\n\n\t\t\tif ( s.charAt(i) != s.charAt(j) ) {\n\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t\ti++; j--;\n\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\n\n\tprivate static long power( long a , long b ) {\n\n\t\tlong ans = 1;\n\n\t\twhile ( b > 0 ) {\n\n\t\t\tif ( (b & 1) != 0 ) {\n\n\t\t\t\tans = binMultiply(ans, a);\n\n\t\t\t}\n\n\t\t\ta = binMultiply(a, a );\n\n\t\t\tb >>= 1;\n\n\t\t}\n\n\t\treturn ans;\n\n\t}\n\n\n\n\tprivate static long binMultiply(long a , long b ) {\n\n\t\tlong ans = 0;\n\n\t\twhile ( b > 0 ) {\n\n\t\t\tif ( (b & 1) != 0 ) {\n\n\t\t\t\tans = (ans + a % mod ); \/\/ if m is given in ques than use ans = ans+a % m ;\n\n\t\t\t}\n\n\t\t\ta = (a + a) % mod; \/\/ if m is given in ques than use a = (a+a)%m;\n\n\t\t\tb >>= 1;\n\n\t\t}\n\n\t\treturn ans;\n\n\t}\n\n\n\n\tprivate static int GCD ( int a , int b ) {\n\n\t\tif ( b == 0) return a;\n\n\t\treturn GCD( b , a % b);\n\n\t}\n\n\n\n\n\n\tprivate static int binarySearch(int l , int r , int[] arr , int find ) {\n\n\t\tint mid = l + (r - l) \/ 2;\n\n\t\tif ( arr[mid] == find ) {\n\n\t\t\treturn mid;\n\n\t\t} else if ( arr[mid] > find ) {\n\n\t\t\treturn binarySearch(l, mid - 1, arr, find);\n\n\t\t}\n\n\n\n\t\treturn binarySearch(mid + 1, r, arr, find);\n\n\t}\n\n\tprivate static int upper_bound(ArrayList arr , int element ) {\n\n\t\tint l = 0 ;\n\n\t\tint h = arr.size() - 1;\n\n\t\tint mid = 0;\n\n\t\twhile ( h - l > 1 ) {\n\n\t\t\tmid = (h + l) \/ 2;\n\n\t\t\tif ( arr.get(mid) <= element ) {\n\n\t\t\t\tl = mid + 1;\n\n\t\t\t} else {\n\n\t\t\t\th = mid ;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( arr.get(l) > element ) return l;\n\n\t\tif ( arr.get(h) > element ) return h;\n\n\t\treturn -1;\n\n\t}\n\n\tprivate static int lower_bound( long arr[] , long element ) {\n\n\t\tint l = 0 ;\n\n\t\tint h = arr.length - 1;\n\n\t\tint mid = 0;\n\n\t\twhile ( h - l > 1 ) {\n\n\t\t\tmid = (h - l) \/ 2;\n\n\t\t\tif ( arr[mid] < element ) {\n\n\t\t\t\tl = mid + 1;\n\n\t\t\t} else {\n\n\t\t\t\th = mid ;\n\n\t\t\t}\n\n\t\t}\n\n\t\tif ( arr[l] >= element ) return l;\n\n\t\tif ( arr[h] >= element ) return h;\n\n\t\treturn -1;\n\n\t}\n\n}\n\nclass DisjointSet {\n\n\tList rank = new ArrayList<>();\n\n\tList parent = new ArrayList<>();\n\n\tList size = new ArrayList<>();\n\n\n\n\tpublic DisjointSet(int n ) {\n\n\t\tfor ( int i = 0; i <= n; ++i ) {\n\n\t\t\trank.add(0);\n\n\t\t\tparent.add(i);\n\n\t\t\tsize.add(1);\n\n\t\t}\n\n\t}\n\n\tpublic int findUPar(int node ) {\n\n\t\tif ( node == parent.get(node) ) return node;\n\n\t\tint ulp = findUPar(parent.get(node));\n\n\t\tparent.set(node, ulp);\n\n\t\treturn parent.get(node);\n\n\t}\n\n\tpublic void unionBySize(int u, int v) {\n\n\t\tint ulp_u = findUPar(u);\n\n\t\tint ulp_v = findUPar(v);\n\n\t\tif ( ulp_u == ulp_v ) return ;\n\n\t\tif ( size.get(ulp_u) < size.get(ulp_v) ) {\n\n\t\t\tparent.set(ulp_u, ulp_v);\n\n\t\t\tsize.set(ulp_v, size.get(ulp_v) + size.get(ulp_u) );\n\n\t\t} else {\n\n\t\t\tparent.set(ulp_v, ulp_u);\n\n\t\t\tsize.set(ulp_u, size.get(ulp_v) + size.get(ulp_u) );\n\n\t\t}\n\n\t}\n\n\tpublic void unionByRank(int u, int v) {\n\n\t\tint ulp_u = findUPar(u);\n\n\t\tint ulp_v = findUPar(v);\n\n\t\tif ( ulp_u == ulp_v ) return ;\n\n\t\tif ( rank.get(ulp_u) < rank.get(ulp_v) ) {\n\n\t\t\tparent.set(ulp_u, ulp_v);\n\n\t\t} else if ( rank.get(ulp_v) < rank.get(ulp_u) ) {\n\n\t\t\tparent.set(ulp_v, ulp_u);\n\n\t\t} else {\n\n\t\t\tparent.set(ulp_v, ulp_u);\n\n\t\t\tint rankU = rank.get(ulp_u);\n\n\t\t\trank.set(ulp_u, rankU + 1);\n\n\t\t}\n\n\t}\n\n}\n\nclass Pair {\n\n\tint first;\n\n\tint second;\n\n\tPair(int first , int second ) {\n\n\t\tthis.first = first ;\n\n\t\tthis.second = second;\n\n\t}\n\n}\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.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.util.StringTokenizer;\n\n\/*\n\n1\n\n2 3\n\n *\/\n\npublic class D {\n\n\n\n\tstatic int ind1, ind2;\n\n\t\n\n\tpublic static void main(String[] args) {\n\n\t\tFastScanner fs=new FastScanner();\n\n\t\tint n=fs.nextInt(), m=fs.nextInt();\n\n\t\t\n\n\t\tint[][] arrays=new int[n][m];\n\n\t\tfor (int i=0; i=min) mask+=1< 0) {\n\n\t\t\tst = new StringTokenizer(br.readLine());\n\n\t\t\tString str = st.nextToken();\n\n\t\t\tboolean[] vis = new boolean[26];\n\n\t\t\tArrayList res = new ArrayList();\n\n\t\t\tboolean ispos = true;\n\n\t\t\tint ix = -1;\n\n\t\t\tfor (char ch : str.toCharArray()) {\n\n\t\t\t\tif (vis[ch - 'a']) {\n\n\t\t\t\t\tif (ix - 1 >= 0 && res.get(ix - 1) == ch)\n\n\t\t\t\t\t\tix--;\n\n\t\t\t\t\telse if (ix + 1 < res.size() && res.get(ix + 1) == ch)\n\n\t\t\t\t\t\tix++;\n\n\t\t\t\t\telse {\n\n\t\t\t\t\t\tispos = false;\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\n\n\t\t\t\t} else {\n\n\t\t\t\t\tif (ix + 1 == res.size()) {\n\n\t\t\t\t\t\tres.add(ch);\n\n\t\t\t\t\t\tix++;\n\n\t\t\t\t\t} else if (ix == 0) {\n\n\t\t\t\t\t\tres.add(0, ch);\n\n\t\t\t\t\t\tix = 0;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tispos = false;\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tvis[ch - 'a'] = true;\n\n\t\t\t\t}\n\n\t\t\t\tif (!ispos)\n\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\tif (!ispos) {\n\n\t\t\t\tpw.println(\"NO\");\n\n\t\t\t} else {\n\n\t\t\t\tpw.println(\"YES\");\n\n\t\t\t\tfor (char ch : res) {\n\n\t\t\t\t\tpw.print(ch);\n\n\t\t\t\t}\n\n\t\t\t\tfor (int i = 0; i < 26; i++) {\n\n\t\t\t\t\tif (!vis[i]) {\n\n\t\t\t\t\t\tpw.print((char) (i + 'a'));\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tpw.println();\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tpw.close();\n\n\n\n\t}\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.*;\npublic class Game23 {\n public static void main(String[]args){\n Scanner sc = new Scanner(System.in);\n int a= sc.nextInt();\n int b= sc.nextInt();\n int count=0;\n if(b%a!=0){\n System.out.println(-1);\n return;\n }\n int x=b\/a;\n while(x%3==0){\n count++;\n x=x\/3;\n }\n while(x%2==0){\n count++;\n x=x\/2;\n }\n if(x!=1){\n System.out.println(-1);\n return;\n }\n System.out.println(count);\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.*;\n\nimport java.util.*;\n\npublic class Main {\n\n\tpublic static void main(String[] args) throws IOException \n\n\t{ \n\n\t\tFastScanner f = new FastScanner(); \n\n\t\tint t=1;\n\n\/\/\t\tt=f.nextInt();\n\n\t\tPrintWriter out=new PrintWriter(System.out);\n\n\t\tfor(int tt=0;tt-1;i--) {\n\n\t\t\t\tfor(int j=i+1; j q = new ArrayList<>();\n\n for (long i: p) q.add((int) i);\n\n Collections.sort(q);\n\n for (int i = 0; i < p.length; i++) p[i] = q.get(i);\n\n }\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\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\t\t\n\n\t\tint nextInt() {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\t\tint[] readArray(int n) {\n\n\t\t\tint[] a=new int[n];\n\n\t\t\tfor (int i=0; i ls;\n\n \n\n private static long k;\n\n \n\n private static void check(){\n\n if(k > 0) return;\n\n \n\n PrintWriter pw = new PrintWriter(System.out);\n\n \n\n pw.println(\"YES\");\n\n pw.println(ls.size());\n\n \n\n for(Step step : ls)\n\n pw.println(+step.no+\" \"+step.comm);\n\n \n\n pw.flush();\n\n pw.close();\n\n \n\n System.exit(0);\n\n }\n\n \n\n private static void addStep(long no, String comm){\n\n if(no == 0 || comm.length() == 0)\n\n return;\n\n \n\n Step ns = new Step(no, comm);\n\n ls.add(ns);\n\n \n\n k -= no*comm.length();\n\n check();\n\n \n\n \/\/System.out.println(+k);\n\n }\n\n\n\n public static void main(String []args){\n\n Scanner sc = new Scanner(System.in);\n\n int r = sc.nextInt(), c = sc.nextInt();\n\n k = sc.nextLong();\n\n long max = 4*r*c-2*r-2*c;\n\n \n\n if(k > max){\n\n System.out.println(\"NO\");\n\n System.exit(0);\n\n }\n\n \n\n ls = new ArrayList<>();\n\n \n\n for(int i=0; i0)\n\n\t\t{\n\n\t\t long n=sc.nextLong();\n\n\t\t while(n>1)\n\n\t\t {\n\n\t\t if(n%2==0)\n\n\t\t {\n\n\t\t System.out.print(1);\n\n\t\t n=n-2;\n\n\t\t }\n\n\t\t else if(n==3)\n\n\t\t {System.out.print(\"7\");\n\n\t\t break;}\n\n\t\t else if (n%2==1)\n\n\t\t {\n\n\t\t n=n-3;\n\n\t\t System.out.print(\"7\");\n\n\t\t n=n\/2;\n\n\t\t while(n-->0)\n\n\t\t {\n\n\t\t System.out.print(\"1\");\n\n\t\t }\n\n\t\t break;\n\n\t\t }\n\n\t\t }\n\n\t\t System.out.println();\n\n\t\t}\n\n\t}\n\n}\n\n","language":"java"} +{"contest_id":"1296","problem_id":"E2","statement":"E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1\u2264res\u2264n1\u2264res\u2264n) \u2014 the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1\u2264ci\u2264res1\u2264ci\u2264res and cici means the color of the ii-th character.ExamplesInputCopy9\nabacbecfd\nOutputCopy2\n1 1 2 1 2 1 2 1 2 \nInputCopy8\naaabbcbb\nOutputCopy2\n1 2 1 2 1 2 1 1\nInputCopy7\nabcdedc\nOutputCopy3\n1 1 1 1 1 2 3 \nInputCopy5\nabcde\nOutputCopy1\n1 1 1 1 1 \n","tags":["data structures","dp"],"code":"\/\/ package codeforce.cf617;\n\n\n\nimport java.io.PrintWriter;\n\nimport java.util.*;\n\n\n\npublic class E2 {\n\n public static void main(String[] args) {\n\n Scanner sc = new Scanner(System.in);\n\n PrintWriter pw = new PrintWriter(System.out);\n\n\/\/ int t = sc.nextInt();\n\n int t = 1;\n\n for (int i = 0; i < t; i++) {\n\n solve(sc, pw);\n\n }\n\n pw.close();\n\n }\n\n\n\n static void solve(Scanner in, PrintWriter out){\n\n int n = in.nextInt();\n\n char[] cs = in.next().toCharArray();\n\n int[] dp = new int[26];\n\n List ans = new ArrayList<>();\n\n for (int i = 0; i < n; i++) {\n\n int idx = cs[i] - 'a';\n\n int state = 0;\n\n for (int j = idx + 1; j < 26; j++) {\n\n state |= dp[j];\n\n }\n\n for (int j = 0; j < 26; j++) {\n\n if ((state | (1 << j)) != state){\n\n ans.add(j + 1);\n\n dp[idx] |= (1 << j);\n\n break;\n\n }\n\n }\n\n }\n\n int st = 0;\n\n for (int i = 0; i < 26; i++) {\n\n st |= dp[i];\n\n }\n\n int cnt = 0;\n\n for (int i = 0; i < 26; i++) {\n\n if ((st | (1 << i)) == st){\n\n cnt++;\n\n }\n\n }\n\n out.println(cnt);\n\n for(int x : ans){\n\n out.print(x+\" \");\n\n }\n\n out.println();\n\n }\n\n\n\n \/\/ Use this instead of Arrays.sort() on an array of ints. Arrays.sort() is n^2\n\n \/\/ worst case since it uses a version of quicksort. Although this would never\n\n \/\/ actually show up in the real world, in codeforces, people can hack, so\n\n \/\/ this is needed.\n\n static void ruffleSort(int[] a) {\n\n \/\/ruffle\n\n int n=a.length;\n\n Random r=new Random();\n\n for (int i=0; i stack = new Stack();\n\n\t\t\tfor (int i = n - 1; i >= 0; i--) {\n\n\t\t\t\tdouble sum = a[i];\n\n\t\t\t\tint len = 1;\n\n\t\t\t\twhile (!stack.isEmpty()) {\n\n\t\t\t\t\tdouble[] top = stack.peek();\n\n\t \n\n\t\t\t\t\tif (sum \/ len > top[0]) {\n\n\t\t\t\t\t\tsum += top[0] * top[1];\n\n\t\t\t\t\t\tlen += top[1];\n\n\t\t\t\t\t\tstack.pop();\n\n\t\t\t\t\t} else\n\n\t\t\t\t\t\tbreak;\n\n\t \n\n\t\t\t\t}\n\n\t\t\t\tdouble curr = sum \/ len;\n\n\t\t\t\tstack.push(new double[] { curr, len });\n\n\t\t\t}\n\n\t\t\twhile (!stack.isEmpty()) {\n\n\t\t\t\tdouble[] curr = stack.pop();\n\n\t\t\t\twhile (curr[1]-- > 0)\n\n\t\t\t\t\tout.println(curr[0]);\n\n\t\t\t}\n\n\t\t}\n\n\t\tout.close();\n\n\t} \n\n\tstatic void sort(int[] p) {\n\n ArrayList q = new ArrayList<>();\n\n for (int i: p) q.add( i);\n\n Collections.sort(q);\n\n for (int i = 0; i < p.length; i++) p[i] = q.get(i);\n\n }\n\n static long gcd(long a,long b) {\n\n \tif(a==0) return b;\n\n \treturn gcd(b%a,a);\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\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\t\t\n\n\t\tint nextInt() {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\t\tint[] readArray(int n) {\n\n\t\t\tint[] a=new int[n];\n\n\t\t\tfor (int i=0; i st = new Stack<>();\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tif (s[i] == ')' && !st.isEmpty() && st.peek().x == '(') {\n\t\t\t\t\tst.pop();\n\t\t\t\t\tif (s[i] == '(') {\n\t\t\t\t\t\topen++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclose++;\n\t\t\t\t\t}\n\t\t\t\t\tif (st.isEmpty()) {\n\t\t\t\t\t\topen = close = 0;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tst.push(new pair(s[i], i));\n\t\t\t\t\tif (s[i] == '(') {\n\t\t\t\t\t\topen++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclose++;\n\t\t\t\t\t}\n\t\t\t\t\tif (open == close) {\n\n\t\t\t\t\t\tres += (open + close);\n\t\t\t\t\t\topen = close = 0;\n\t\t\t\t\t\tst.clear();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tpn(res);\n\t\t}\n\t}\n\n\tclass pair {\n\t\tchar x;\n\t\tint y;\n\n\t\tpair(char x, int y) {\n\t\t\tthis.x = x;\n\t\t\tthis.y = y;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"(\" + x + \",\" + y + \")\";\n\t\t}\n\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":"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":"\n\n\n\nimport java.io.*;\n\nimport java.math.*;\n\nimport java.util.*;\n\n\n\n\/\/ @author : Dinosparton \n\n\n\npublic class test {\n\n\n\n\tstatic class Pair {\n\n\t\tDouble x;\n\n\t\tint y;\n\n\n\n\t\tPair(Double x, int y) {\n\n\t\t\tthis.x = x;\n\n\t\t\tthis.y = y;\n\n\n\n\t\t}\n\n\t}\n\n\n\n\tstatic class Compare {\n\n\n\n\t\tvoid compare(Pair arr[], int n) {\n\n\t\t\t\/\/ Comparator to sort the pair according to second element\n\n\t\t\tArrays.sort(arr, new Comparator() {\n\n\t\t\t\t@Override\n\n\t\t\t\tpublic int compare(Pair p1, Pair p2) {\n\n\t\t\t\t\tif (p1.x != p2.x) {\n\n\t\t\t\t\t\treturn (int) (p1.x - p2.x);\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\treturn (int) (p1.y - p2.y);\n\n\t\t\t\t\t}\n\n\/\/\t\t \treturn Double.compare(a[0], b[0]);\n\n\t\t\t\t}\n\n\t\t\t});\n\n\n\n\/\/\t\t for (int i = 0; i < n; i++) { \n\n\/\/\t\t System.out.print(arr[i].x + \" \" + arr[i].y + \" \"); \n\n\/\/\t\t } \n\n\/\/\t\t System.out.println(); \n\n\t\t}\n\n\t}\n\n\n\n\tstatic class Scanner {\n\n\t\tBufferedReader br;\n\n\t\tStringTokenizer st;\n\n\n\n\t\tpublic Scanner() {\n\n\t\t\tbr = new BufferedReader(new InputStreamReader(System.in));\n\n\t\t}\n\n\n\n\t\tString next() {\n\n\t\t\twhile (st == null || !st.hasMoreElements()) {\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\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\tlong nextLong() {\n\n\t\t\treturn Long.parseLong(next());\n\n\t\t}\n\n\n\n\t\tdouble nextDouble() {\n\n\t\t\treturn Double.parseDouble(next());\n\n\t\t}\n\n\n\n\t\tString nextLine() {\n\n\t\t\tString str = \"\";\n\n\t\t\ttry {\n\n\t\t\t\tstr = br.readLine();\n\n\t\t\t} catch (IOException e) {\n\n\t\t\t\te.printStackTrace();\n\n\t\t\t}\n\n\t\t\treturn str;\n\n\t\t}\n\n\t}\n\n\n\n\tstatic int dp[][][][];\n\n\n\n\tstatic int recursion(int p[], int index,int odd,int even,int last) {\n\n \n\n\t\tif (index == p.length) {\n\n\t\t\treturn 0;\n\n\t\t}\n\n\n\n\t\tif(dp[index][odd][even][last] != -1) {\n\n\t\t\treturn dp[index][odd][even][last];\n\n\t\t}\n\n\t\tif(p[index] == 0) {\n\n\t\t\t\n\n\t\t\tint pos1 = 1000;\n\n\t\t\tint pos2 = 1000;\n\n\t\t\t\n\n\t\t\tif(odd > 0) {\n\n\t\t\t\t pos1 = (last!=0 && last == 1 ? 0 : 1) + recursion(p,index+1,odd-1,even,1);\n\n\t\t\t}\n\n\t\t\tif(even > 0) {\n\n\t\t\t\t pos2 = (last!=0 && last == 2 ? 0 : 1) + recursion(p,index+1,odd,even-1,2);\n\n\t\t\t}\n\n\t\t\t\n\n\t\t\treturn dp[index][odd][even][last] = Math.min(pos1, pos2);\n\n\t\t}\n\n\t\treturn dp[index][odd][even][last] = (last!=0 && last == p[index] ? 0 : 1) + recursion(p,index+1,odd,even,p[index]);\n\n\t}\n\n\n\n\tpublic static void main(String args[]) throws Exception {\n\n\n\n\t\tScanner sc = new Scanner();\n\n\t\tStringBuilder res = new StringBuilder();\n\n\n\n\t\tint tc = 1;\n\n\n\n\t\twhile (tc-- > 0) {\n\n\n\n\t\t\tint n = sc.nextInt();\n\n\n\n\t\t\tint p[] = new int[n];\n\n\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tp[i] = sc.nextInt();\n\n\t\t\t}\n\n\n\n\t\t\tboolean visit[] = new boolean[n + 1];\n\n\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tif (p[i] != 0) {\n\n\t\t\t\t\tvisit[p[i]] = true;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tif (p[i] == 0) {\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\t} else {\n\n\n\n\t\t\t\t\tp[i] = (p[i] % 2 == 0) ? 2 : 1;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tint odd = 0;\n\n\t\t\tint even = 0;\n\n\n\n\t\t\tfor (int i = 1; i <= n; i++) {\n\n\t\t\t\tif (!visit[i]) {\n\n\t\t\t\t\tif (i % 2 == 0) {\n\n\t\t\t\t\t\teven++;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\todd++;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\n\t\t\tdp = new int[n+1][odd + 1][even + 1][3];\n\n\n\n\t\t\tfor (int i = 0; i <= n; i++) {\n\n\t\t\t\tfor (int j = 0; j <= odd; j++) {\n\n\t\t\t\t\tfor (int k = 0; k <= even; k++) {\n\n\t\t\t\t\t\tfor(int l=0;l<3;l++) {\n\n\t\t\t\t\t\t\tdp[i][j][k][l] = -1;\n\n\t\t\t\t\t\t}\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\/\/ System.out.println(odd);\n\n\t\t\tres.append(recursion(p, 0,odd,even,0) - 1 + \"\\n\");\n\n\t\t}\n\n\t\tSystem.out.println(res);\n\n\t}\n\n}\n\n","language":"java"} +{"contest_id":"1141","problem_id":"F1","statement":"F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],\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\u2264501\u2264n\u226450) \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":["greedy"],"code":"\/*\n\n Author: Anthony Ngene\n\n Created: 05\/10\/2020 - 14:12\n\n*\/\n\n\n\nimport java.io.*;\n\nimport java.util.*;\n\n\n\npublic class F {\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();\n\n int[] arr = in.nextIntArray(n);\n\n HashMap> subSum = new HashMap<>();\n\n\n\n Integer best = null;\n\n for (int i = 0; i < n; i++) {\n\n int total = 0;\n\n for (int j = i; j < n; j++) {\n\n total += arr[j];\n\n if (!subSum.containsKey(total)) subSum.put(total, new ArrayDeque<>());\n\n Deque rs = subSum.get(total);\n\n if (rs.size() > 0 && rs.peekLast().b > j) rs.pollLast();\n\n if (rs.size() == 0 || rs.peekLast().b < i)\n\n rs.add(new Tuple(i, j));\n\n if (best == null || rs.size() > subSum.get(best).size())\n\n best = total;\n\n }\n\n }\n\n Deque bestList = subSum.get(best);\n\n out.println(bestList.size());\n\n for (Tuple aa: bestList)\n\n out.pp(aa.a + 1, aa.b + 1);\n\n\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 F().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":"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.io.*;\n\nimport java.util.*;\n\n\/*\n\n Set hash_Set = new HashSet();\n\n\/\/ Demonstrating Set using HashSet\n\n \/\/ Declaring object of type String\n\n Set hash_Set = new HashSet();\n\n\n\n \/\/ Adding elements to the Set\n\n \/\/ using add() method\n\n hash_Set.add(\"Geeks\");\n\n hash_Set.add(\"For\");\n\n hash_Set.add(\"Geeks\");\n\n hash_Set.add(\"Example\");\n\n hash_Set.add(\"Set\");\n\n\n\n \/\/ Printing elements of HashSet object\n\n System.out.println(hash_Set);\n\n *\/\n\npublic class Main {\n\n static boolean flag = false;\n\n static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));\n\n static PrintWriter out = new PrintWriter(System.out);\n\n static StringTokenizer tok;\n\n\n\n public static void check() throws IOException {\n\n if (tok == null || !tok.hasMoreTokens())\n\n tok = new StringTokenizer(read.readLine());\n\n }\n\n\n\n public static int nextInt() throws IOException {\n\n return Integer.parseInt(nextString());\n\n }\n\n\n\n public static long nextLong() throws IOException {\n\n return Long.parseLong(nextString());\n\n }\n\n\n\n public static double nextDouble() throws IOException {\n\n return Double.parseDouble(nextString());\n\n }\n\n\n\n public static String nextString() throws IOException {\n\n check();\n\n return tok.nextToken();\n\n }\n\n\n\n public static void println(Object o) {\n\n out.println(o);\n\n out.flush();\n\n }\n\n\n\n public static int[] nextArray(int n) throws IOException {\n\n int[] a = new int[n];\n\n for (int i = 0; i < n; i++)\n\n a[i] = nextInt();\n\n return a;\n\n }\n\n\n\n static int findLCM(int x, int y) {\n\n \/\/ LCM(a, b) = (a x b) \/ GCD(a, b)\n\n return (x * y) \/ findGCD(x, y);\n\n }\n\n\n\n static int findGCD(int x, int y) {\n\n int r = 0, a, b;\n\n a = (x > y) ? x : y;\n\n b = (x < y) ? x : y;\n\n r = b;\n\n while (a % b != 0) {\n\n r = a % b;\n\n a = b;\n\n b = r;\n\n }\n\n return r;\n\n }\n\n\n\n \/*\n\n boolean [] primes = new boolean[n+1];\n\n for(int i =0; i[] DIVS = computeDivisors(20000);\n\n static int[] solve(int a, int b, int c) {\n int[] ans = new int[4];\n \/\/ a,b,c in [1,10000]\n ans[0] = 50000;\n\n \/\/ Evaluate possible values of the middle number\n for (int v = 1; v <= 20000; v++) {\n int[] curr = new int[] {a, a, v, c};\n for (int x : DIVS[v]) {\n if (Math.abs(a - x) < curr[0]) {\n curr[0] = Math.abs(a - x);\n curr[1] = x;\n }\n }\n curr[0] += Math.abs(b - v);\n int r = c % v;\n if (c < v) {\n curr[0] += v - c;\n curr[3] = v;\n } else if (r != 0) {\n if (r <= v - r) {\n curr[0] += r;\n curr[3] = c - r;\n } else {\n curr[0] += v - r;\n curr[3] = c + (v - r);\n }\n }\n if (curr[0] < ans[0]) {\n ans = curr;\n }\n }\n return ans;\n }\n\n static List[] computeDivisors(int n) {\n List[] divs = new ArrayList[n + 1];\n for (int i = 0; i <= n; i++) {\n divs[i] = new ArrayList<>();\n }\n for (int i = 1; i <= n; i++) {\n for (int j = i; j <= n; j += i) {\n divs[j].add(i);\n }\n }\n return divs;\n }\n\n static void test(int[] exp, int a, int b, int c) {\n int[] ans = solve(a, b, c);\n boolean ok = exp[0] == ans[0] && exp[1] == ans[1] && exp[2] == ans[2] && exp[3] == ans[3];\n System.out.format(\"%d %d %d => %d %d %d %d %s\\n\",\n a, b, c, ans[0], ans[1], ans[2], ans[3],\n ok ? \"\":\"Expected \" + exp[0] + \" \" + exp[1] + \" \" + exp[2] + \" \" + exp[3]);\n }\n\n static boolean test = false;\n static void doTest() {\n if (!test) {\n return;\n }\n long t0 = System.currentTimeMillis();\n test(new int[] {2, 137, 10001, 10001}, 137, 10000, 10000);\n System.out.format(\"%d msec\\n\", System.currentTimeMillis() - t0);\n System.exit(0);\n }\n\n public static void main(String[] args) {\n doTest();\n MyScanner in = new MyScanner();\n int T = in.nextInt();\n for (int t = 1; t <= T; t++) {\n int a = in.nextInt();\n int b = in.nextInt();\n int c = in.nextInt();\n int[] ans = solve(a, b, c);\n System.out.format(\"%d\\n%d %d %d\\n\", ans[0], ans[1], ans[2], ans[3]);\n }\n }\n\n static void output(int[] a) {\n if (a == null) {\n System.out.println(\"-1\");\n return;\n }\n StringBuilder sb = new StringBuilder();\n for (int v : a) {\n sb.append(v);\n sb.append(' ');\n if (sb.length() > 4000) {\n System.out.print(sb.toString());\n sb.setLength(0);\n }\n }\n System.out.println(sb.toString());\n }\n\n static void myAssert(boolean cond) {\n if (!cond) {\n throw new RuntimeException(\"Unexpected\");\n }\n }\n\n static class MyScanner {\n BufferedReader br;\n StringTokenizer st;\n\n public MyScanner() {\n try {\n final String USERDIR = System.getProperty(\"user.dir\");\n String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(\".MyScanner\", \"\");\n cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;\n final File fin = new File(USERDIR + \"\/io\/c\" + cname.substring(1,5) + \"\/\" + cname + \".in\");\n br = new BufferedReader(new InputStreamReader(fin.exists()\n ? new FileInputStream(fin) : System.in));\n } catch (Exception e) {\n br = new BufferedReader(new InputStreamReader(System.in));\n }\n }\n\n public String next() {\n try {\n while (st == null || !st.hasMoreElements()) {\n st = new StringTokenizer(br.readLine());\n }\n return st.nextToken();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public int nextInt() {\n return Integer.parseInt(next());\n }\n\n public long nextLong() {\n return Long.parseLong(next());\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.BufferedReader;\n\nimport java.io.File;\n\nimport java.io.FileInputStream;\n\nimport java.io.InputStreamReader;\n\nimport java.lang.invoke.MethodHandles;\n\nimport java.util.*;\n\n\n\n\n\n \n\n \n\n \n\n \n\npublic class b {\n\n \n\n\n\n\tpublic static void main(String []args) {\n\n\t\tMyScanner s=new MyScanner();\n\n\t\t\n\n\tint n=s.nextInt();\n\n\t\tlong a=s.nextLong();\n\n\t\tlong b=s.nextLong();\n\n\t\tlong k=s.nextLong();\n\n\t\tlong []f=new long [n];\n\n\t\tfor(int i=0;ia) {\n\n\t\t\t\t long c=f[i]%(a+b);\n\n\t\t\t\t if(c==0) {\n\n\t\t\t\t\t long e=b\/a;\n\n\t\t\t\t\t if(b%a!=0)\n\n\t\t\t\t\t\t e++;\n\n\t\t\t\t\t t[i]=e;\n\n\t\t\t\t }\n\n\t\t\t\t else {\n\n\t\t\t\t\t long d=c\/a;\n\n\t\t\t\t\t if(c%a!=0)\n\n\t\t\t\t\t\t d++;\n\n\t\t\t\t\t if(d>1)\n\n\t\t\t\t\t t[i]=d-1;\n\n\t\t\t\t\t else t[i]=0; \n\n\t\t\t\t }\n\n\t\t\t }\n\n\t\t\t\n\n\t\t}\n\n\t\tArrays.sort(t);\n\n\t\tint res=0;\n\n\t\tfor(long x:t) {\n\n\t\t\tif(k-x>=0) {\n\n\t\t\t\tres++;\n\n\t\t\t\tk=k-x;\n\n\t\t\t}\n\n\t\t\t\/\/ System.out.println(x);\n\n\t\t}\n\n\t\t\t\n\n\t\t\t System.out.println(res);\n\n\t\t\t\t\t\n\n\t}\n\n\t\t\t\n\n\t\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\t\n\n\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\t\t\t\n\n\t\n\n\t\t\t\n\n\tpublic static boolean is(String s) {\n\n\t\tint l=0;\n\n\t\tint r=s.length()-1;\n\n\t\twhile(l 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;\n\n\t final File fin = new File(USERDIR + \"\/io\/c\" + cname.substring(1,5) + \"\/\" + cname + \".in\");\n\n\t br = new BufferedReader(new InputStreamReader(fin.exists()\n\n\t ? new FileInputStream(fin) : System.in));\n\n\t } catch (Exception e) {\n\n\t br = new BufferedReader(new InputStreamReader(System.in));\n\n\t }\n\n\t }\n\n\t \n\n\t public String next() {\n\n\t try {\n\n\t while (st == null || !st.hasMoreElements()) {\n\n\t st = new StringTokenizer(br.readLine());\n\n\t }\n\n\t return st.nextToken();\n\n\t } catch (Exception e) {\n\n\t throw new RuntimeException(e);\n\n\t }\n\n\t }\n\n\t \n\n\t public int nextInt() {\n\n\t return Integer.parseInt(next());\n\n\t }\n\n\t \n\n\t public long nextLong() {\n\n\t return Long.parseLong(next());\n\n\t }\n\n\t }\n\n\t\n\n\t\t}","language":"java"} +{"contest_id":"1292","problem_id":"C","statement":"C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon \"Xenon\" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker \"X\" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n\u22121n\u22121 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n\u22122n\u22122 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=\u22111\u2264u> g;\n\n int[][] parent;\n int[][] size;\n\n long[][] dp;\n\n int find_size(int v, int p) {\n if (size[p][v] != 0) {\n return size[p][v];\n }\n size[p][v] = 1;\n for (int u : g.get(v)) {\n if (u == p) continue;\n size[p][v] += find_size(u, v);\n }\n return size[p][v];\n }\n\n void find_parent(int root, int v, int p) {\n parent[v][root] = p;\n for (int u : g.get(v)) {\n if (u == p) continue;\n find_parent(root, u, v);\n }\n }\n\n void find_dp(int u, int v) {\n if (dp[u][v] != -1) return;\n find_dp(parent[u][v], v);\n find_dp(parent[v][u], u);\n dp[u][v] = size[parent[u][v]][u] * size[parent[v][u]][v] + Math.max(dp[parent[u][v]][v], dp[parent[v][u]][u]);\n }\n\n public void solve(InputReader in, PrintWriter out) {\n int n = in.nextInt();\n g = new ArrayList<>();\n for (int i = 0; i < n; ++i) {\n g.add(new ArrayList<>());\n }\n for (int i = 1; i < n; ++i) {\n int u = in.nextInt() - 1, v = in.nextInt() - 1;\n g.get(u).add(v);\n g.get(v).add(u);\n }\n\n parent = new int[n][n];\n for (int i = 0; i < n; ++i) {\n find_parent(i, i, -1);\n }\n\n size = new int[n][n];\n for (int i = 0; i < n; ++i) {\n for (int v : g.get(i)) {\n find_size(i, v);\n }\n }\n\n dp = new long[n][n];\n for (int i = 0; i < n; ++i) {\n Arrays.fill(dp[i], -1);\n }\n for (int i = 0; i < n; ++i) {\n dp[i][i] = 0;\n }\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n if (i == j) continue;\n find_dp(i, j);\n }\n }\n\n long answer = 0;\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n answer = Math.max(answer, dp[i][j]);\n }\n }\n out.println(answer);\n }\n\n public static void main(String[] args) {\n InputReader in = new InputReader(System.in);\n PrintWriter out = new PrintWriter(System.out);\n new Main().solve(in, out);\n out.flush();\n }\n\n static class InputReader {\n public BufferedReader reader;\n public 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 long nextLong() {\n return Long.parseLong(next());\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.util.*;\n\npublic class UnusualCompetitions {\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\tString s=sc.next();\n\n\t\tchar crr[]=s.toCharArray();\n\n\t\tint o=0,c=0,pos=-1,ans=0;\n\n\t\tfor(int i=0;i0) {\n\n\t\t\t\tfor(int j=i;j0){\n\n\t\t\t\to--;\n\n\t\t\t}\n\n\t\t\telse {\n\n\t\t\t\tc++;\n\n\t\t\t\tif(pos==-1) {\n\n\t\t\t\t\tpos=i;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tSystem.out.println(ans);\n\n\t}\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.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.util.StringTokenizer;\n\npublic class Solution {\n\n public static void main(String[] args) throws IOException {\n\n Reader input = new Reader();\n\n int n = input.nextInt();\n\n int[] a = new int[n];\n\n for(int i = 0; i < n; ++i) {\n\n a[i] = input.nextInt();\n\n }\n\n int maxBit = getMaxBit(a);\n\n int mask = (1 << (maxBit-1));\n\n System.out.println(solve(a, mask));\n\n }\n\n static int solve(int[] a, int mask) {\n\n int answer = 0;\n\n while(mask > 0) {\n\n int zeros = 0;\n\n int ones = 0;\n\n for(int i = 0; i < a.length; ++i) {\n\n if((a[i]|mask) == a[i]) {\n\n ++ones;\n\n } else {\n\n ++zeros;\n\n }\n\n }\n\n if(zeros != 0 && ones != 0) {\n\n answer |= mask;\n\n int[] g1 = new int[ones];\n\n int[] g2 = new int[zeros];\n\n int onesPointer = 0, zerosPointer = 0;\n\n for(int i = 0; i < a.length; ++i) {\n\n if((a[i]|mask) == a[i]) {\n\n g1[onesPointer++] = a[i];\n\n } else {\n\n g2[zerosPointer++] = a[i];\n\n }\n\n }\n\n int temp1 = solve(g1, mask>>1), temp2 = solve(g2, mask>>1);\n\n if(temp1 < temp2) {\n\n answer = answer|temp1;\n\n } else {\n\n answer = answer|temp2;\n\n }\n\n break;\n\n }\n\n mask = mask >> 1;\n\n }\n\n return answer;\n\n }\n\n static int getMaxBit(int[] a) {\n\n int max = a[0];\n\n for(int i = 1; i < a.length; ++i) {\n\n if(a[i] > max) max = a[i];\n\n }\n\n int bits = 0;\n\n while(max > 0) {\n\n ++bits;\n\n max = max>>1;\n\n }\n\n return bits;\n\n }\n\n static class Reader {\n\n BufferedReader bufferedReader;\n\n StringTokenizer string;\n\n public Reader() {\n\n InputStreamReader inr = new InputStreamReader(System.in);\n\n bufferedReader = new BufferedReader(inr);\n\n }\n\n public String next() throws IOException {\n\n while(string == null || ! string.hasMoreElements()) {\n\n string = new StringTokenizer(bufferedReader.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 public double nextDouble() throws IOException {\n\n return Double.parseDouble(next());\n\n }\n\n public String nextLine() throws IOException {\n\n return bufferedReader.readLine();\n\n }\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.util.*;\n\n \n\npublic class Ap {\n\n \n\n\tpublic static void main(String[] args) {\n\n \n\n\t\tScanner s = new Scanner(System.in);\n\n \n\n\t\tint n = s.nextInt();\n\n\t\tString str = s.next();\n\n\t\t\n\n\t\tint sum=0;\n\n\t\tint pos=0;\n\n\t\tint co=0;\n\n\t\tfor(int i=0;iarr.length)\n\n\t\t\treturn 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\n\n int n = sc.nextInt();\n\n long m = sc.nextInt();\n\n\n\n \/\/now what??\n\n \/\/n!\n\n long[] fact = new long[n+1];\n\n fact[0] = 1;\n\n for(long i = 1; i <= n; i++){\n\n fact[(int)i] = (i*fact[(int)(i-1)])%m;\n\n }\n\n\n\n long segments = 0;\n\n \n\n for(long i = 1; i <= n; i++){\n\n long first = (long)(n-i+1);\n\n long second = fact[(int)(n-i+1)];\n\n long third = fact[(int)i];\n\n\n\n long fourth = (first * second)% m;\n\n long fifth = (fourth* third)%m;\n\n\n\n segments = (segments + fifth)%m;\n\n }\n\n\n\n out.println(segments);\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":"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.* ;\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 j = 0; j < tests; j++) {\n\t\t\tString[] input = reader.readLine().split(\" \");\n\t\t\tint n = Integer.parseInt(input[0]);\n\t\t\tint d = Integer.parseInt(input[1]);\n\t\t\tint[] a = new int[n + 1];\n\t\t\tString[] input1 = reader.readLine().split(\" \");\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\ta[i + 1] = Integer.parseInt(input1[i]);\n\t\t\t}\n\t\t\tfor (int i = 0; i < d; i++) {\n\t\t\t\tfor (int k = 2; k <= n; k++) {\n\t\t\t\t\tif (a[k] > 0) {\n\t\t\t\t\t\ta[k]--;\n\t\t\t\t\t\ta[k - 1]++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\twriter.write(a[1]+ \"\\n\");\n\t\t}\t\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.*;\n\nimport java.util.*;\n\npublic class Main{\n\n\tstatic int[][][]dest;\n\n\tstatic int []dx= {0,1,0,-1},dy= {1,0,-1,0};\n\n\tstatic char []dir= {'L','U','R','D'};\n\n\tstatic char ans[][];\n\n\tstatic boolean valid(int x,int y) {\n\n\t\treturn x>=0 && y>=0 && xbi+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":"\/\/package com.company;\/\/Read minute details if coming wrong for no idea questions\n\n\n\n\n\nimport java.util.*;\n\nimport java.io.*;\n\n\n\n\n\npublic class Main {\n\n\n\n public static class Suffix implements Comparable\n\n {\n\n int index;\n\n int rank;\n\n int next;\n\n public Suffix(int ind, int r, int nr)\n\n {\n\n index = ind;\n\n rank = r;\n\n next = nr;\n\n }\n\n public int compareTo(Suffix s)\n\n {\n\n if (rank != s.rank) return Integer.compare(rank, s.rank);\n\n return Integer.compare(next, s.next);\n\n }\n\n }\n\n public static int[] suffixArray(String s)\n\n {\n\n int n = s.length();\n\n Suffix[] su = new Suffix[n];\n\n for (int i = 0; i < n; i++)\n\n {\n\n su[i] = new Suffix(i, s.charAt(i) - '$', 0);\n\n }\n\n for (int i = 0; i < n; i++)\n\n su[i].next = (i + 1 < n ? su[i + 1].rank : -1);\n\n Arrays.sort(su);\n\n int[] ind = new int[n];\n\n for (int length = 4; length < 2 * n; length <<= 1)\n\n {\n\n int rank = 0, prev = su[0].rank;\n\n su[0].rank = rank;\n\n ind[su[0].index] = 0;\n\n for (int i = 1; i < n; i++)\n\n {\n\n if (su[i].rank == prev &&\n\n su[i].next == su[i - 1].next)\n\n {\n\n prev = su[i].rank;\n\n su[i].rank = rank;\n\n }\n\n else\n\n {\n\n prev = su[i].rank;\n\n su[i].rank = ++rank;\n\n }\n\n ind[su[i].index] = i;\n\n }\n\n for (int i = 0; i < n; i++)\n\n {\n\n int nextP = su[i].index + length \/ 2;\n\n su[i].next = nextP < n ?\n\n su[ind[nextP]].rank : -1;\n\n }\n\n Arrays.sort(su);\n\n }\n\n\n\n int[] suf = new int[n];\n\n\n\n for (int i = 0; i < n; i++)\n\n suf[i] = su[i].index;\n\n return suf;\n\n }\n\n\n\n\n\n\n\n\n\n static class pair implements Comparable {\n\n long a = 0;\n\n long b = 0;\n\n \/\/ int cnt;\n\n\n\n pair(long b, long a) {\n\n this.a = b;\n\n this.b = a;\n\n \/\/ cnt = x;\n\n }\n\n\n\n @Override\n\n public int compareTo(pair o) {\n\n\n\n if(this.a != o.a)\n\n return (int) (this.a - o.a);\n\n else\n\n return (int) (this.b - o.b);\n\n }\n\n public boolean equals(Object o) {\n\n if (o instanceof pair) {\n\n pair p = (pair) o;\n\n return p.a == a && p.b == b;\n\n }\n\n return false;\n\n }\n\n\n\n public int hashCode() {\n\n return (Long.valueOf(a).hashCode()) * 31 + (Long.valueOf(b).hashCode());\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.hasMoreTokens()) {\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().trim();\n\n } catch (Exception e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n\n\n static class FastWriter {\n\n private final BufferedWriter bw;\n\n\n\n public FastWriter() {\n\n this.bw = new BufferedWriter(new OutputStreamWriter(System.out));\n\n }\n\n\n\n public void prlong(Object object) throws IOException {\n\n\n\n bw.append(\"\" + object);\n\n }\n\n\n\n public void prlongln(Object object) throws IOException {\n\n prlong(object);\n\n bw.append(\"\\n\");\n\n }\n\n\n\n public void close() throws IOException {\n\n bw.close();\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 return gcd(b % a, a);\n\n }\n\n\n\n\n\n\n\n \/\/HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS\n\n\n\n\/\/ HashSet set = new HashSet<>();\n\n\/\/ for(int i = 0; i < s.length(); i++){\n\n\/\/ int b = 0;\n\n\/\/ long h = 1;\n\n\/\/ for(int j=i; j= 0; i--) {\n\n invfact[i] = (invfact[i + 1] * (i + 1)) % p;\n\n }\n\n }\n\n\n\n private long nCr(int n, int r) {\n\n if (r > n || n < 0 || r < 0) return 0;\n\n return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p;\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\n\n static void sort(long[] a ) {\n\n ArrayList l = new ArrayList<>();\n\n for(long i: a) {\n\n l.add(i);\n\n }\n\n Collections.sort(l);\n\n for(int i =0;iend||rend||rmid)\n\n {\n\n upd(a,tr,2*node+1,mid+1,end,idx,val,1+yo,x);\n\n }\n\n else\n\n {\n\n upd(a,tr,2*node,beg,mid,idx,val,1+yo,x);\n\n }\n\n\n\n\n\n { tr[node] = (tr[2 * node] + tr[2 * node + 1]);\n\n\n\n }\n\n\n\n\n\n }\n\n\n\n public static int upper_bound(long arr[], int key)\n\n {\n\n int mid, N = arr.length;\n\n int low = 0;\n\n int high = N;\n\n while (low < high && low != N) {\n\n mid = low + (high - low) \/ 2;\n\n if (key > arr[mid]) {\n\n low = mid + 1;\n\n }\n\n else {\n\n high = mid;\n\n }\n\n }\n\n if (low == N ) {\n\n return -1;\n\n }\n\n\n\n\n\n return low ;\n\n }\n\n public static void main(String[] args) {\n\n try {\n\n FastReader in = new FastReader();\n\n FastWriter out = new FastWriter();\n\n\/\/ int mx=1000000;\n\n\/\/ boolean isPrime[] = new boolean[mx+5]; int primeDiv[] = new int[mx+5];\n\n\/\/ for (int i = 0; i <= mx; i++) {\n\n\/\/ isPrime[i] = true;\n\n\/\/ }\n\n\/\/ for(int i =0;i[] divisors = new ArrayList[(int) 1e5 + 5];\n\n\/\/ for (int i = 0; i < divisors.length; i++) {\n\n\/\/ divisors[i] = new ArrayList<>();\n\n\/\/ }\n\n\/\/ for (int i = 1; i < divisors.length; i++) {\n\n\/\/ for (int j = 1; j <= Math.sqrt(i); j++) {\n\n\/\/ if (i % j == 0) {\n\n\/\/ divisors[i].add(j);\n\n\/\/ if (i \/ j != j)\n\n\/\/ divisors[i].add(i \/ j);\n\n\/\/ }\n\n\/\/ }\n\n\/\/ }\n\n\/\/ System.out.println(\n\n\/\/ String.format(\"%.12f\", x));\n\n\n\n\n\n int testCases=1;\n\n\n\n\n\n long mod =1000000007;\n\n\n\n\n\n\n\n \/\/ System.out.println(c);\n\n\n\n\n\n\n\n\n\n\n\n\n\n long fact[]=new long[300001];\n\n fact[0]=1;\n\n for(int i =1;i 0) {\n\n\n\nint n =in.nextInt();\n\nlong a[]=new long[n];\n\nfor(int i =0;ix[beg])\n\n {\n\n r=beg;\n\n beg++;\n\n\n\n }\n\n end--;\n\nr=Math.min(end,r);\n\n ans+=r+1;\n\n\n\n}\n\n\n\n System.out.println(ans);\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 }\n\n out.close();\n\n } catch (Exception e) {\n\n return;\n\n }\n\n }\n\n\/\/ \/\/\/DFS To calculate the number of child nodes and depth in tree kind of structure\n\n\/\/ public static int dfs(ArrayList> adj, int s, int d, int child[], int depth[]) {\n\n\/\/ depth[s] = d;\n\n\/\/ for(int v: adj.get(s)) {\n\n\/\/ if(depth[v] == -1) {\n\n\/\/ child[s] += dfs(adj, v, d+1, child, depth);\n\n\/\/ }\n\n\/\/ }\n\n\/\/ return child[s]+1;\n\n\/\/ }\n\n\n\n public static int dfs(ArrayList> adj , int node,int dp[],int vis[]) {\n\n\n\n int ans=1;\n\n vis[node]=-1;\n\n if(dp[node]!=-1)\n\n return ans;\n\n for(int i :adj.get(node)) {\n\n if(vis[i]==-1)\n\n {\n\n return Integer.MIN_VALUE;\n\n }\n\nelse\n\n ans = ans +dfs(adj, i, dp,vis);\n\n }\n\n return dp[node]= ans ;\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\n\n public static void sortby(int arr[][])\n\n {\n\n Arrays.sort(arr, new Comparator() {\n\n\n\n @Override\n\n \/\/ Compare values according to columns\n\n public int compare(final int[] entry1,\n\n final int[] entry2) {\n\n\n\n \/\/ To sort in descending order revert\n\n \/\/ the '>' Operator\n\n if (entry1[1] >entry2[1])\n\n return 1;\n\n else if(entry1[1]entry2[2])\n\n return 1;\n\n else return -1;\n\n }\n\n }); \/\/ End of function call sort().\n\n }\n\n\n\n static long comb(int r, int n)\n\n {\n\n long result;\n\n\n\n result = factorial(n)\/(factorial(r)*factorial(n-r));\n\n\n\n return result;\n\n\n\n }\n\n\n\n static long factorial(int n) {\n\n int c;\n\n long result = 1;\n\n\n\n for (c = 1; c <= n; c++)\n\n result = result*c;\n\n\n\n return result;\n\n }\n\n\n\n\n\n static void LongestPalindromicPrefix(String str,int lps[]){\n\n\n\n\/\/ String temp = str + '\/';\n\n\/\/ str = reverse(str);\n\n\/\/ temp += str;\n\n String temp =str;\n\n int n = temp.length();\n\n\n\n\n\n for(int i = 1; i < n; i++)\n\n {\n\n int len = lps[i - 1];\n\n while (len > 0 && temp.charAt(len) !=\n\n temp.charAt(i))\n\n {\n\n len = lps[len - 1];\n\n }\n\n if (temp.charAt(i) == temp.charAt(len))\n\n {\n\n len++;\n\n }\n\n lps[i] = len;\n\n }\n\n\n\n\/\/ return temp.substring(0, lps[n - 1]);\n\n }\n\n\n\n\n\n\n\n static String reverse(String input)\n\n {\n\n char[] a = input.toCharArray();\n\n int l, r = a.length - 1;\n\n\n\n for(l = 0; l < r; l++, r--)\n\n {\n\n char temp = a[l];\n\n a[l] = a[r];\n\n a[r] = temp;\n\n }\n\n return String.valueOf(a);\n\n }\n\n}\n\n\n\n\n\n\n\n\n\n\/*\n\n *\n\n *\u3000\u3000\u250f\u2513\u3000\u3000\u3000\u250f\u2513+ +\n\n *\u3000\u250f\u251b\u253b\u2501\u2501\u2501\u251b\u253b\u2513 + +\n\n *\u3000\u2503\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u2503\n\n *\u3000\u2503\u3000\u3000\u3000\u2501\u3000\u3000\u3000\u2503 ++ + + +\n\n * \u2588\u2588\u2588\u2588\u2501\u2588\u2588\u2588\u2588+\n\n * \u25e5\u2588\u2588\u25e4\u3000\u25e5\u2588\u2588\u25e4 +\n\n *\u3000\u2503\u3000\u3000\u3000\u253b\u3000\u3000\u3000\u2503\n\n *\u3000\u2503\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u2503 + +\n\n *\u3000\u2517\u2501\u2513\u3000\u3000\u3000\u250f\u2501\u251b\n\n *\u3000\u3000\u3000\u2503\u3000\u3000\u2503 JACKS PET FROM ANOTHER WORLD\n\n *\u3000\u3000\u3000\u2503\u3000\u3000\u2503\n\n *\u3000\u3000\u3000\u2503\u3000 \u3000 \u2517\u2501\u2501\u2501\u2513\n\n *\u3000\u3000\u3000\u2503 \u3000\u3000\u3000\u3000\u3000\u3000 \u2523\u2513-------\n\n *\u3000\u3000 \u2503 \u3000\u3000\u3000\u3000\u3000 \u3000\u250f\u251b-------\n\n *\u3000 \u2517\u2513\u2513\u250f\u2501\u2533\u2513\u250f\u251b + + + +\n\n *\u3000\u3000\u3000\u3000\u2503\u252b\u252b\u3000\u2503\u252b\u252b\n\n *\u3000\u3000\u3000\u3000\u2517\u253b\u251b\u3000\u2517\u253b\u251b+ + + +\n\n *\/\n\n\n\n\/\/RULES\n\n\/\/TAKE INPUT AS LONG IN CASE OF SUM OR MULITPLICATION OR CHECK THE CONTSRaint of the array\n\n\/\/Always use stringbuilder of out.println for strinof out.println for string or high level output\n\n\n\n\n\n\/\/ IMPORTANT TRs1 TO USE BRUTE FORCE TECHNIQUE TO SOLVE THE PROs1 OTHER CERTAIN LIMIT IS GIVENIT IS GIVEN\n\n\n\n\/\/Read minute details if coming wrong for no idea questions","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":"\n\n\n\n\n\n\n\n\n\nimport java.util.*;\n\nimport java.io.*;\n\n\n\n\n\npublic class Main {\n\n\t\n\n\t\n\n static class FastReader{\n\n\t BufferedReader br;\n\n\t StringTokenizer st;\n\n\t FastReader(){\n\n\t\t br=new BufferedReader(new InputStreamReader(System.in));\n\n\t }\n\n\t String next() {\n\n\t\t while(st==null||!st.hasMoreElements()) {\n\n\t\t try {\n\n\t\t\t st=new StringTokenizer(br.readLine());\n\n\t\t }catch(IOException e) {\n\n\t\t e.printStackTrace();\n\n\t\t }\n\n\t\t }\n\n\t\t return st.nextToken();\n\n\t }\n\n\t \n\n\t int nextInt() {\n\n\t\t return Integer.parseInt(next());\n\n\t }\n\n\t long nextLong() {\n\n\t\t return Long.parseLong(next());\n\n\t }\n\n\t double nextDouble() {\n\n\t\t return Double.parseDouble(next());\n\n\t }\n\n\t String nextLine() {\n\n\t\t String str=\"\";\n\n\t\t try {\n\n\t\t\t str=br.readLine();\n\n\t\t } catch(IOException e) {\n\n\t\t\t e.printStackTrace();\n\n\t\t }\n\n\t\t return str;\n\n\t }\n\n }\n\n\n\n\tstatic class Pair{ \n\n\t\/\/implements Comparable {\n\n\t\t long x;\n\n\t\t long y;\n\n\t\t Pair(long x,long y){\n\n\t\t\t this.x=x;\n\n\t\t\t this.y=y;\n\n\t\t }\n\n\/\/\t\t @Override\n\n\/\/\t\t public int compareTo(Pair o) {\n\n\/\/\t\t\treturn this.y-o.y; \n\n\/\/\t\t }\n\n\t\t}\n\n\n\n \n\n\t\n\n static long gcd(long a,long b) {\n\n\t if(b==0) return a;\n\n\telse\n\n\t return gcd(b,a%b);\n\n }\n\n \n\n static List primeFactors(int n){\n\n List ar=new ArrayList<>();\n\n int ct=0;\n\n for(int i=2;i*i<=n;i++) {\n\n\t if(n%i==0) {\n\n\t\t ar.add(i);\n\n\t\t ct++;\n\n\t while(n%i==0) {\n\n\t n\/=i;\n\n\t }\n\n }\n\n }\n\n if(n>1) {\n\n \tct++;\n\n\t ar.add(n);\n\n }\n\n return ar;\n\n }\n\n \n\n static int lb(ArrayListar,long k) {\n\n\tint s=0;\n\n\tint e=ar.size();\n\n\twhile(s!=e) {\n\n\t int mid=s+e>>1;\n\n\t if(ar.get(mid)ar,int k) {\n\n\tint s=0;\n\n\tint e=ar.size();\n\n\twhile(s!=e) {\n\n\t int mid=s+e>>1;\n\n\t if(ar.get(mid)<=k)\n\n\t\t s=mid+1;\n\n\t else\n\n\t\t e=mid;\n\n }\n\n\tif(s==ar.size())\n\n\t\treturn -1;\n\n return s;\n\n }\n\n \n\n static boolean isPrime(long n) {\n\n\t boolean flag=true;\n\n\t if(n<2)\n\n\t\t flag=false;\n\n\t else {\n\n\t\t for(int i=2;i*i<=n;i++){\n\n\t\t\tif(n%i==0) {\n\n\t\t\t flag=false;\n\n\t\t\t break;\n\n\t\t\t}\n\n\t\t }\n\n\t }\n\n\t return flag;\n\n }\n\n \n\n static void pArray(int a[]) {\n\n\t for(int i=0;i ar[]) {\n\n\/\/\tPriorityQueuepq=new PriorityQueue<>();\n\n\/\/\tpq.add(new Pair(src,0));\n\n\/\/\tSetvis=new HashSet<>();\n\n\/\/\tint dist[]=new int[n+1];\n\n\/\/\tdist[src]=0;\n\n\/\/\tArrays.fill(dist, Integer.MAX_VALUE);\n\n\/\/\n\n\/\/\twhile(pq.size()>0) {\n\n\/\/\t\t\n\n\/\/\t \tPair cur=pq.poll();\n\n\/\/\t \tif(!vis.contains(cur.x)){\n\n\/\/\t \t\t\n\n\/\/\t \t\tvis.add(cur.x);\n\n\/\/\t \t\t\n\n\/\/\t \t\tdist[cur.x]=cur.y;\n\n\/\/\t \t\t\n\n\/\/\t \t for(Edge e:ar[cur.x]) {\n\n\/\/\t \t\t if(!vis.contains(e.dest)&&dist[e.dest]>cur.y+e.w )\n\n\/\/\t \t\t\tpq.add(new Pair(e.dest,cur.y+e.w));\n\n\/\/\t \t }\n\n\/\/\t \t}\n\n\/\/\t }\n\n\/\/\treturn dist;\n\n\/\/ }\n\n\/\/ \n\n public static String addCharToString(String str, char c,\n\n int pos)\n\n{\n\n\n\nStringBuffer stringBuffer = new StringBuffer(str);\n\nstringBuffer.insert(pos, c);\n\nreturn stringBuffer.toString();\n\n}\n\n \n\n static int BigMod(String num, int a)\n\n {\n\n int res = 0;\n\n for (int i = 0; i < num.length(); i++)\n\n res = (res * 10 + (int)num.charAt(i)); \n\n return res;\n\n\n\n }\n\n static boolean isSquare(int n) {\n\n\t\tfor(int i=1;i*i<=n;i++) {\n\n\t\t\tif((i*i)==n)\n\n\t\t\t\treturn true;\n\n\t\t}\n\n\t\treturn false;\n\n }\n\n\n\n static long firstsetBitPower(long n)\n\n {\n\n int k = (int)(Math.log(n) \/ Math.log(2));\n\n \n\n return 1 << k;\n\n }\n\n\n\n\n\n public static void main(String[] args) {\n\n try {\n\n \n\n \n\n FastReader sc = new FastReader();\n\n \n\n \/\/int t=sc.nextInt();\n\n \n\n \/\/while(t-->0) { \n\n int n=sc.nextInt();\n\n int a[]=new int[n];\n\n int b[]=new int[n];\n\n for(int i=0;isec) {\n\n System.out.println(\"1\");\t\n\n }\n\n else {\n\n System.out.println((sec\/fir)+1);\t\n\n }\n\n \/\/}\n\n \n\n }catch(Exception e) {return;}\n\n }\n\n}\n\n\n\n\n\n\n\n\/\/https:\/\/www.codechef.com\/MP3TO401?order=desc&sortBy=successful_submissions\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\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\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\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\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\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\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\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\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\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":"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)) {\n\n pw.println(\"NO\");\n\n }\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 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 static StringBuilder diff(Point p1, Point p2) {\n\n int xDiff = p2.x - p1.x;\n\n int yDiff = p2.y - p1.y;\n\n StringBuilder res = new StringBuilder();\n\n res.append(\"R\".repeat(Math.max(0, xDiff)));\n\n res.append(\"U\".repeat(Math.max(0, yDiff)));\n\n return res;\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 static java.lang.Integer.parseInt;\nimport static java.lang.Long.parseLong;\nimport static java.lang.System.exit;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.util.Random;\nimport java.util.StringTokenizer;\n\npublic class F {\n\n\tstatic final int primes[] = new int[100000];\n\tstatic {\n\t\tprimes[0] = 2;\n\t\tprimes[1] = 3;\n\t\tlong bitset[] = new long[7000];\n\t\tfor (int i = 2, p = 1, dp = 4; i < primes.length; i++) {\n\t\t\tdo {\n\t\t\t\tp += dp;\n\t\t\t\tdp = 6 - dp;\n\t\t\t} while ((bitset[(p \/ 3) >> 6] & (1L << (p \/ 3))) != 0);\n\t\t\tprimes[i] = p;\n\t\t\tif (p <= 46340) {\n\t\t\t\tfor (int q = p * p, dq = dp * p, l = 6 * p, j;\n\t\t\t\t\t(j = q \/ 3) >> 6 < bitset.length; q += dq, dq = l - dq) {\n\t\t\t\t\tbitset[j >> 6] |= 1L << j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstatic final long factors[] = new long[100];\n\tstatic int factorCount;\n\n\tstatic void addFactor(long p) {\n\t\tif (factorCount >= factors.length) {\n\t\t\treturn;\n\t\t}\n\t\tfor (int i = 0; i < factorCount; i++) {\n\t\t\tif (factors[i] == p) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tfactors[factorCount++] = p;\n\t}\n\n\tstatic void addFactors(long v) {\n\t\tfor (long p: primes) {\n\t\t\tif (p * p > v) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (v % p == 0) {\n\t\t\t\taddFactor(p);\n\t\t\t\tdo {\n\t\t\t\t\tv \/= p;\n\t\t\t\t} while (v % p == 0);\n\t\t\t}\n\t\t}\n\t\tif (v > 1) {\n\t\t\taddFactor(v);\n\t\t}\n\t}\n\n\tstatic void solve() throws Exception {\n\/\/\t\tSystem.err.println(\"START\");\n\t\tint n = scanInt();\n\/\/\t\tint n = 200000;\n\t\tlong a[] = new long[n];\n\t\tlong seed = 123;\n\/\/\t\tRandom trng = new Random();\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\ta[i] = scanLong();\n\/\/\t\t\ta[i] = new BigInteger(40, 100, trng).longValue();\n\t\t\tseed = seed * 1000000009 ^ a[i];\n\t\t}\n\/\/\t\tSystem.err.println(\"GEN\");\n\t\tRandom rng = new Random(seed);\n\t\tfactorCount = 0;\n\t\tfor (int i = 0; i < 100 && factorCount < factors.length; i++) {\n\t\t\tint j = rng.nextInt(n);\n\t\t\taddFactors(a[j]);\n\t\t\taddFactors(a[j] + 1);\n\t\t\tif (a[j] > 1) {\n\t\t\t\taddFactors(a[j] - 1);\n\t\t\t}\n\t\t}\n\/\/\t\tSystem.err.println(\"FACT\");\n\t\tlong ans = n;\n\t\ti: for (int i = 0; i < factorCount; i++) {\n\t\t\tlong p = factors[i];\n\t\t\tlong cans = 0;\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tlong c = a[j], v;\n\t\t\t\tif (c < p) {\n\t\t\t\t\tv = p - c;\n\t\t\t\t} else {\n\t\t\t\t\tv = c % p;\n\t\t\t\t\tif (2 * v > p) {\n\t\t\t\t\t\tv = p - v;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcans += v;\n\t\t\t\tif (cans >= ans) {\n\t\t\t\t\tcontinue i;\n\t\t\t\t}\n\t\t\t}\n\t\t\tans = cans;\n\t\t}\n\/\/\t\tSystem.err.println(\"CALC\");\n\t\tout.print(ans);\n\t}\n\n\tstatic int scanInt() throws IOException {\n\t\treturn parseInt(scanString());\n\t}\n\n\tstatic long scanLong() throws IOException {\n\t\treturn parseLong(scanString());\n\t}\n\n\tstatic String scanString() throws IOException {\n\t\twhile (tok == null || !tok.hasMoreTokens()) {\n\t\t\ttok = new StringTokenizer(in.readLine());\n\t\t}\n\t\treturn tok.nextToken();\n\t}\n\n\tstatic BufferedReader in;\n\tstatic PrintWriter out;\n\tstatic StringTokenizer tok;\n\n\tpublic static void main(String[] args) {\n\t\ttry {\n\t\t\tin = new BufferedReader(new InputStreamReader(System.in));\n\t\t\tout = new PrintWriter(System.out);\n\t\t\tsolve();\n\t\t\tin.close();\n\t\t\tout.close();\n\t\t} catch (Throwable e) {\n\t\t\te.printStackTrace();\n\t\t\texit(1);\n\t\t}\n\t}\n}","language":"java"} +{"contest_id":"1305","problem_id":"E","statement":"E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the \"Proof by AC\" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,\u2026,ana1,a2,\u2026,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1\u2264a1=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 \n\n public static void sort(int arr[],int l,int r) { \/\/sort(arr,0,n-1);\n\n if(l==r) {\n\n return;\n\n }\n\n int mid=(l+r)\/2;\n\n sort(arr,l,mid);\n\n sort(arr,mid+1,r);\n\n merge(arr,l,mid,mid+1,r);\n\n }\n\n public static void merge(int arr[],int l1,int r1,int l2,int r2) {\n\n int tmp[]=new int[r2-l1+1];\n\n int indx1=l1,indx2=l2;\n\n \/\/sorting the two halves using a tmp array\n\n for(int i=0;ir1) {\n\n tmp[i]=arr[indx2];\n\n indx2++;\n\n continue;\n\n }\n\n if(indx2>r2) {\n\n tmp[i]=arr[indx1];\n\n indx1++;\n\n continue;\n\n }\n\n if(arr[indx1]r1) {\n\n tmp[i]=arr[indx2];\n\n indx2++;\n\n continue;\n\n }\n\n if(indx2>r2) {\n\n tmp[i]=arr[indx1];\n\n indx1++;\n\n continue;\n\n }\n\n if(arr[indx1] map=new HashMap<>();\n\n freq[3]++;\n\n for(int i=2;i map) {\n\n int ans=-1;\n\n while(l<=r) {\n\n int mid=(l+r)\/2;\n\n int get=get(mid,freq,map);\n\n if(get<=m) {\n\n ans=mid;\n\n r=mid-1;\n\n }\n\n else {\n\n l=mid+1;\n\n }\n\n }\n\n return ans;\n\n }\n\n public static void add(int arr[],int freq[],int indx,HashMap map) {\n\n for(int i=0;i map) {\n\n if(ele map) {\n\n if(ele2a+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 DeadPixel_1315A {\n\n public static void main(String[] args) {\n\n Scanner s = new Scanner(System.in);\n\n int t = s.nextInt();\n\n while(t-->0){\n\n int a = s.nextInt();\n\n int b = s.nextInt();\n\n int x = s.nextInt();\n\n int y = s.nextInt();\n\n int horizontal = Math.max(x,a-1-x);\n\n int vertical = Math.max(y,b-1-y);\n\n int a1 = horizontal*b;\n\n int a2 = vertical*a;\n\n System.out.println(Math.max(a1,a2));\n\n }\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":"\n\nimport java.io.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.util.*;\n\nimport java.util.Map.Entry;\n\n\n\n public class codeforces {\n\n\t \n\n\n\n\t \n\nstatic int mod = 1000000007;\n\n\t \n\npublic static void main(String[] args) {\n\n\t\n\n\t FastReader sc = new FastReader();\n\n\t try {\n\n StringBuilder ss = new StringBuilder();\n\n int n = sc.nextInt();\n\n String s = sc.next();\n\n int cnt = 0 ;\n\n int ans = 0;\n\n boolean flag =true;\n\n for(int i = 0 ; i =cnt1) {\n\n \t\t \t\t int min = Math.min(cnt, cnt1);\n\n \t\t \t\t cnt -= min;\n\n \t\t \t\t cnt1 -= min;\n\n \t\t \t }\n\n \t\t \t \n\n \t\t }\n\n \t }\n\n \t \/\/System.out.println(cnt +\" \"+cnt1);\n\n \t if(cnt1 != 0 || cnt!= 0) {\n\n \tss.append(-1);\n\n \t }\n\n \t else {\n\n \t\t ss.append(2*ans);\n\n \t }\n\n \t \n\n \n\n \n\n \n\n \n\n \n\n \n\n \n\n\t\t System.out.println(ss);\n\n\t }\n\n\t \n\n\t catch(Exception e) {\n\n\t\t System.out.println(e.getMessage());\n\n\t }\n\n }\n\n \n\n \n\n \n\n \n\n \n\n static long pow(long a, long b) {\n\n\t long ans = 1;\n\n\t long temp = a;\n\n\t while(b>0) {\n\n\t\t if((b&1) == 1) {\n\n\t\t\t ans*=temp;\n\n\t\t }\n\n\t\t temp = temp*temp;\n\n\t b = b>>1;\n\n\t }\n\n\t return ans;\n\n }\n\n \n\n \n\n \n\n static long ncr(int n, int r) { \n\n\t return fact(n) \/ (fact(r) *\n\n fact(n - r));\n\n}\n\n \n\n\n\nstatic long fact(long n)\n\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 static long gcd(long a, long b) {\n\n\t if(b == 0) {\n\n\t\t return a;\n\n\t } \n\n\t return gcd(b , a%b);\n\n\t \n\n\t \n\n\t \n\n\t \n\n\t \n\n }\n\n \n\n static ArrayList factor(long n) {\n\n\t ArrayList al = new ArrayList<>();\n\n\t \n\n\t for(int i = 1 ; i*i<=n;i++) {\n\n\t\t if(n%i == 0) {\n\n\t\t\t if(n\/i == i) {\n\n\t\t\t\t al.add(i);\n\n\t\t\t }\n\n\t\t\t else {\n\n\t\t\t\t \n\n\t\t\t\t al.add(i);\n\n\n\n\t\t\t\t al.add((int) (n\/i));\n\n\t\t\t\t }\n\n\t\t }\n\n\t }\n\n\t \n\n\t return al;\n\n }\n\n \n\n \n\n \n\n \n\n static class Pair implements Comparable{\n\n\t long a;\n\n\t int b ;\n\n\t\n\n\t Pair(long a, int b){\n\n\t\t this.a = a;\n\n\t\t this.b = b;\n\n\t\t\n\n\t\t \n\n\t\t \n\n\t\n\n\t }\n\n\t@Override\n\n\tpublic int compareTo(Pair o) {\n\n\t\t\/\/ TODO Auto-generated method stub\n\n\t return (int)(this.a - o.a);\n\n\t}\n\n }\n\n \n\n \n\n \n\n \n\n static ArrayList sieve(int n) {\n\n\t boolean a[] = new boolean[n+1];\n\n\t Arrays.fill(a, false);\n\n\t \n\n\t for(int i = 2 ; i*i <=n ; i++) {\n\n\t\t if(!a[i]) {\n\n\t\t\t for(int j = 2*i ; j<=n ; j+=i) {\n\n\t\t\t\t a[j] = true;\n\n\t\t\t }\n\n\t\t }\n\n\t }\n\n\t \n\n\t ArrayList al = new ArrayList<>();\n\n\t for(int i = 2 ; i <=n;i++) {\n\n\t\t if(!a[i]) {\n\n\t\t\t al.add(i);\n\n\t\t }\n\n\t }\n\n\t return al;\n\n\t}\n\n \n\n static ArrayList pf(long n) {\n\n\t ArrayList al = new ArrayList<>();\n\n\t while(n%2 == 0) {\n\n\t\t al.add(2l);\n\n\t\t n = n\/2;\n\n\t }\n\n\t \n\n\t for(long i = 3 ; i*i<=n ; i+=2) {\n\n\t\t while(n%i == 0) {\n\n\t\t\t al.add(i);\n\n\t\t\t n = n\/i;\n\n\t\t }\n\n\t }\n\n\t \n\n\t if(n>2) {\n\n\t\t al.add( n);\n\n\t }\n\n\t \n\n\t return al;\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 {\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\n\n \n\n } ","language":"java"} +{"contest_id":"1141","problem_id":"B","statement":"B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day \u2014 it is a sequence a1,a2,\u2026,ana1,a2,\u2026,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 number of hours per day.The second line contains nn integer numbers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u226410\u2264ai\u22641), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5\n1 0 1 0 1\nOutputCopy2\nInputCopy6\n0 1 0 1 1 0\nOutputCopy2\nInputCopy7\n1 0 1 1 1 0 1\nOutputCopy3\nInputCopy3\n0 0 0\nOutputCopy0\nNoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.","tags":["implementation"],"code":"import java.util.*;\nimport java.io.*;\n\npublic class MaximalContinuousRest {\n public static void main(String[] args)throws IOException{\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int size = Integer.parseInt(br.readLine());\n int[] hours = new int[size * 2];\n StringTokenizer st = new StringTokenizer(br.readLine());\n for(int i = 0; i < size; i++){\n int currNum = Integer.parseInt(st.nextToken());\n hours[i] = currNum;\n hours[i + size] = currNum;\n }\n ArrayList sizes = new ArrayList<>();\n int counter = 0;\n for(int i = 0; i < size * 2; i++){\n if(hours[i] == 0){\n sizes.add(counter);\n counter = 0;\n }\n else if(hours[i] == 1){\n counter++;\n }\n }\n int max = sizes.get(0);\n for(int i = 0; i < sizes.size(); i++){\n if(sizes.get(i) > max){\n max = sizes.get(i);\n }\n }\n System.out.println(max);\n }\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.*;\n\npublic class Solution{\n\n public static void main(String[] args)\n\n {\n\n Scanner in=new Scanner(System.in);\n\n int n=in.nextInt();\n\n int m=in.nextInt();\n\n in.nextLine();\n\n String s1=in.nextLine();\n\n String s2=in.nextLine();\n\n String[] str1=s1.split(\" \");\n\n String[] str2=s2.split(\" \");\n\n int q=in.nextInt();\n\n for(int c=0;ci&&C[ptr-1]+C[i]>=(1< ADD = (x, y) -> (x + y);\n\n static BiFunction, ArrayList, ArrayList> ADD_ARRAY_LIST = (x, y) -> {\n\n x.addAll(y);\n\n return x;\n\n };\n\n\n\n static Function, Integer> GET_FIRST = (x) -> (x.first);\n\n static Function, Integer> GET_SECOND = (x) -> (x.second);\n\n static Comparator> C = Comparator.comparing(x -> x.first + x.second);\n\n static long MOD = 1_000_000_000 + 7;\n\n\n\n\n\n public static void main(String[] args) throws Exception {\n\n long startTime = System.nanoTime();\n\n int t = in.nextInt();\n\n while (t-- > 0) {\n\n solve();\n\n }\n\n long endTime = System.nanoTime();\n\n err.println(\"Execution Time : +\" + (endTime - startTime) \/ 1000000 + \" ms\");\n\n exit(0);\n\n }\n\n\n\n static void solve() {\n\n int n = in.nextInt();\n\n int[] data = ArrayUtils.reverse(ArrayUtils.MergeSort(in.readAllInts(n)));\n\n for(int a:data){\n\n out.print(a + \" \");\n\n }\n\n out.println(\"\");\n\n }\n\n\n\n static void debug(Object... args) {\n\n for (Object a : args) {\n\n out.println(a);\n\n }\n\n }\n\n\n\n static int dist(Pair a, Pair b) {\n\n return Math.abs(a.first - b.first) + Math.abs(a.second - b.second);\n\n }\n\n\n\n static void y() {\n\n out.println(\"YES\");\n\n }\n\n\n\n static void n() {\n\n out.println(\"NO\");\n\n }\n\n\n\n static int[] stringToArray(String s) {\n\n return s.chars().map(x -> Character.getNumericValue(x)).toArray();\n\n }\n\n\n\n static T min(T a, T b, Comparator C) {\n\n if (C.compare(a, b) <= 0) {\n\n return a;\n\n }\n\n return b;\n\n }\n\n\n\n static T max(T a, T b, Comparator C) {\n\n if (C.compare(a, b) >= 0) {\n\n return a;\n\n }\n\n return b;\n\n }\n\n\n\n static void fail() {\n\n out.println(\"-1\");\n\n }\n\n\n\n static class Pair {\n\n public T first;\n\n public R second;\n\n\n\n public Pair(T first, R second) {\n\n this.first = first;\n\n this.second = second;\n\n }\n\n\n\n @Override\n\n public boolean equals(final Object o) {\n\n if (this == o) {\n\n return true;\n\n }\n\n if (o == null || getClass() != o.getClass()) {\n\n return false;\n\n }\n\n final Pair pair = (Pair) o;\n\n return Objects.equals(first, pair.first) && Objects.equals(second, 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 \"Pair{\" + \"a=\" + first + \", b=\" + second + '}';\n\n }\n\n\n\n public T getFirst() {\n\n return first;\n\n }\n\n\n\n public R getSecond() {\n\n return second;\n\n }\n\n }\n\n\n\n static Pair make_pair(T a, R b) {\n\n return new Pair<>(a, b);\n\n }\n\n\n\n static long mod_inverse(long a, long m) {\n\n Number x = new Number(0);\n\n Number y = new Number(0);\n\n extended_gcd(a, m, x, y);\n\n return (m + x.v % m) % m;\n\n }\n\n\n\n static long extended_gcd(long a, long b, Number x, Number y) {\n\n long d = a;\n\n if (b != 0) {\n\n d = extended_gcd(b, a % b, y, x);\n\n y.v -= (a \/ b) * x.v;\n\n } else {\n\n x.v = 1;\n\n y.v = 0;\n\n }\n\n return d;\n\n }\n\n\n\n static class Number {\n\n long v = 0;\n\n\n\n public Number(long v) {\n\n this.v = v;\n\n }\n\n }\n\n\n\n static long lcm(long a, long b, long c) {\n\n return lcm(a, lcm(b, c));\n\n }\n\n\n\n static long lcm(long a, long b) {\n\n long p = 1L * a * b;\n\n return p \/ gcd(a, b);\n\n }\n\n\n\n static long gcd(long a, long b) {\n\n while (b != 0) {\n\n long t = b;\n\n b = a % b;\n\n a = t;\n\n }\n\n return a;\n\n }\n\n\n\n static long gcd(long a, long b, long c) {\n\n return gcd(a, gcd(b, c));\n\n }\n\n\n\n static class ArrayUtils {\n\n\n\n static void swap(int[] a, int i, int j) {\n\n int temp = a[i];\n\n a[i] = a[j];\n\n a[j] = temp;\n\n }\n\n\n\n static void swap(char[] a, int i, int j) {\n\n char temp = a[i];\n\n a[i] = a[j];\n\n a[j] = temp;\n\n }\n\n\n\n static void print(char[] a) {\n\n for (char c : a) {\n\n out.print(c);\n\n }\n\n out.println(\"\");\n\n }\n\n\n\n static int[] reverse(int[] data) {\n\n int[] p = new int[data.length];\n\n for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {\n\n p[i] = data[j];\n\n }\n\n return p;\n\n }\n\n\n\n static void prefixSum(long[] data) {\n\n for (int i = 1; i < data.length; i++) {\n\n data[i] += data[i - 1];\n\n }\n\n }\n\n\n\n static void prefixSum(int[] data) {\n\n for (int i = 1; i < data.length; i++) {\n\n data[i] += data[i - 1];\n\n }\n\n }\n\n\n\n static long[] reverse(long[] data) {\n\n long[] p = new long[data.length];\n\n for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {\n\n p[i] = data[j];\n\n }\n\n return p;\n\n }\n\n\n\n static char[] reverse(char[] data) {\n\n char[] p = new char[data.length];\n\n for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {\n\n p[i] = data[j];\n\n }\n\n return p;\n\n }\n\n\n\n static int[] MergeSort(int[] A) {\n\n if (A.length > 1) {\n\n int q = A.length \/ 2;\n\n int[] left = new int[q];\n\n int[] right = new int[A.length - q];\n\n System.arraycopy(A, 0, left, 0, q);\n\n System.arraycopy(A, q, right, 0, A.length - q);\n\n int[] left_sorted = MergeSort(left);\n\n int[] right_sorted = MergeSort(right);\n\n return Merge(left_sorted, right_sorted);\n\n } else {\n\n return A;\n\n }\n\n }\n\n\n\n static int[] Merge(int[] left, int[] right) {\n\n int[] A = new int[left.length + right.length];\n\n int i = 0;\n\n int j = 0;\n\n for (int k = 0; k < A.length; k++) {\n\n \/\/ To handle left becoming empty\n\n if (i == left.length && j < right.length) {\n\n A[k] = right[j];\n\n j++;\n\n continue;\n\n }\n\n \/\/ To handle right becoming empty\n\n if (j == right.length && i < left.length) {\n\n A[k] = left[i];\n\n i++;\n\n continue;\n\n }\n\n if (left[i] <= right[j]) {\n\n A[k] = left[i];\n\n i++;\n\n } else {\n\n A[k] = right[j];\n\n j++;\n\n }\n\n }\n\n return A;\n\n }\n\n\n\n static long[] MergeSort(long[] A) {\n\n if (A.length > 1) {\n\n int q = A.length \/ 2;\n\n long[] left = new long[q];\n\n long[] right = new long[A.length - q];\n\n System.arraycopy(A, 0, left, 0, q);\n\n System.arraycopy(A, q, right, 0, A.length - q);\n\n long[] left_sorted = MergeSort(left);\n\n long[] right_sorted = MergeSort(right);\n\n return Merge(left_sorted, right_sorted);\n\n } else {\n\n return A;\n\n }\n\n }\n\n\n\n static long[] Merge(long[] left, long[] right) {\n\n long[] A = new long[left.length + right.length];\n\n int i = 0;\n\n int j = 0;\n\n for (int k = 0; k < A.length; k++) {\n\n \/\/ To handle left becoming empty\n\n if (i == left.length && j < right.length) {\n\n A[k] = right[j];\n\n j++;\n\n continue;\n\n }\n\n \/\/ To handle right becoming empty\n\n if (j == right.length && i < left.length) {\n\n A[k] = left[i];\n\n i++;\n\n continue;\n\n }\n\n if (left[i] <= right[j]) {\n\n A[k] = left[i];\n\n i++;\n\n } else {\n\n A[k] = right[j];\n\n j++;\n\n }\n\n }\n\n return A;\n\n }\n\n\n\n static int upper_bound(int[] data, int num, int start) {\n\n int low = start;\n\n int high = data.length - 1;\n\n int mid = 0;\n\n int ans = -1;\n\n while (low <= high) {\n\n mid = (low + high) \/ 2;\n\n if (data[mid] < num) {\n\n low = mid + 1;\n\n } else if (data[mid] >= num) {\n\n high = mid - 1;\n\n ans = mid;\n\n }\n\n }\n\n if (ans == -1) {\n\n return 100000000;\n\n }\n\n return data[ans];\n\n }\n\n\n\n static int lower_bound(int[] data, int num, int start) {\n\n int low = start;\n\n int high = data.length - 1;\n\n int mid = 0;\n\n int ans = -1;\n\n while (low <= high) {\n\n mid = (low + high) \/ 2;\n\n if (data[mid] <= num) {\n\n low = mid + 1;\n\n ans = mid;\n\n } else if (data[mid] > num) {\n\n high = mid - 1;\n\n }\n\n }\n\n if (ans == -1) {\n\n return 100000000;\n\n }\n\n return data[ans];\n\n }\n\n }\n\n\n\n static boolean[] primeSieve(int n) {\n\n boolean[] primes = new boolean[n + 1];\n\n Arrays.fill(primes, true);\n\n primes[0] = false;\n\n primes[1] = false;\n\n for (int i = 2; i <= Math.sqrt(n); i++) {\n\n if (primes[i]) {\n\n for (int j = i * i; j <= n; j += i) {\n\n primes[j] = false;\n\n }\n\n }\n\n }\n\n return primes;\n\n }\n\n\n\n \/\/ Iterative Version\n\n static HashMap subsets_sum_iter(int[] data) {\n\n HashMap temp = new HashMap();\n\n temp.put(data[0], true);\n\n for (int i = 1; i < data.length; i++) {\n\n HashMap t1 = new HashMap(temp);\n\n t1.put(data[i], true);\n\n for (int j : temp.keySet()) {\n\n t1.put(j + data[i], true);\n\n }\n\n temp = t1;\n\n }\n\n return temp;\n\n }\n\n\n\n static HashMap subsets_sum_count(int[] data) {\n\n HashMap temp = new HashMap<>();\n\n temp.put(data[0], 1);\n\n for (int i = 1; i < data.length; i++) {\n\n HashMap t1 = new HashMap<>(temp);\n\n t1.merge(data[i], 1, ADD);\n\n for (int j : temp.keySet()) {\n\n t1.merge(j + data[i], temp.get(j) + 1, ADD);\n\n }\n\n temp = t1;\n\n }\n\n return temp;\n\n }\n\n\n\n static class Graph {\n\n ArrayList[] g;\n\n\n\n boolean[] visited;\n\n\n\n ArrayList[] graph(int n) {\n\n g = new ArrayList[n];\n\n visited = new boolean[n];\n\n for (int i = 0; i < n; i++) {\n\n g[i] = new ArrayList<>();\n\n }\n\n return g;\n\n }\n\n\n\n void BFS(int s) {\n\n Queue Q = new ArrayDeque<>();\n\n visited[s] = true;\n\n Q.add(s);\n\n while (!Q.isEmpty()) {\n\n int v = Q.poll();\n\n for (int a : g[v]) {\n\n if (!visited[a]) {\n\n visited[a] = true;\n\n Q.add(a);\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n static class SparseTable {\n\n int[] log;\n\n int[][] st;\n\n\n\n public SparseTable(int n, int k, int[] data, BiFunction f) {\n\n log = new int[n + 1];\n\n st = new int[n][k + 1];\n\n log[1] = 0;\n\n for (int i = 2; i <= n; i++) {\n\n log[i] = log[i \/ 2] + 1;\n\n }\n\n for (int i = 0; i < data.length; i++) {\n\n st[i][0] = data[i];\n\n }\n\n for (int j = 1; j <= k; j++)\n\n for (int i = 0; i + (1 << j) <= data.length; i++)\n\n st[i][j] = f.apply(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);\n\n }\n\n\n\n public int query(int L, int R, BiFunction f) {\n\n int j = log[R - L + 1];\n\n return f.apply(st[L][j], st[R - (1 << j) + 1][j]);\n\n }\n\n }\n\n\n\n static class InputReader {\n\n public BufferedReader reader;\n\n public StringTokenizer tokenizer;\n\n\n\n public InputReader(InputStream stream) {\n\n reader = new BufferedReader(new InputStreamReader(stream), 2048);\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 long nextLong() {\n\n return Long.parseLong(next());\n\n }\n\n\n\n public int nextInt() {\n\n return Integer.parseInt(next());\n\n }\n\n\n\n public int[] readAllInts(int n) {\n\n int[] p = new int[n];\n\n for (int i = 0; i < n; i++) {\n\n p[i] = in.nextInt();\n\n }\n\n return p;\n\n }\n\n\n\n public int[] readAllInts(int n, int s) {\n\n int[] p = new int[n + s];\n\n for (int i = s; i < n + s; i++) {\n\n p[i] = in.nextInt();\n\n }\n\n return p;\n\n }\n\n\n\n public long[] readAllLongs(int n) {\n\n long[] p = new long[n];\n\n for (int i = 0; i < n; i++) {\n\n p[i] = in.nextLong();\n\n }\n\n return p;\n\n }\n\n\n\n public long[] readAllLongs(int n, int s) {\n\n long[] p = new long[n + s];\n\n for (int i = s; i < n + s; i++) {\n\n p[i] = in.nextLong();\n\n }\n\n return p;\n\n }\n\n\n\n public double nextDouble() {\n\n return Double.parseDouble(next());\n\n }\n\n }\n\n\n\n static void exit(int a) {\n\n out.close();\n\n err.close();\n\n System.exit(a);\n\n }\n\n\n\n static InputStream inputStream = System.in;\n\n static OutputStream outputStream = System.out;\n\n static OutputStream errStream = System.err;\n\n static InputReader in = new InputReader(inputStream);\n\n static PrintWriter out = new PrintWriter(outputStream);\n\n static PrintWriter err = new PrintWriter(errStream);\n\n static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n\n\n}\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.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.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 BDifferentRules solver = new BDifferentRules();\n int testCount = Integer.parseInt(in.next());\n for (int i = 1; i <= testCount; i++)\n solver.solve(i, in, out);\n out.close();\n }\n\n static class BDifferentRules {\n public void solve(int testNumber, InputReader in, OutputWriter out) {\n int n = in.nextInt(), x = in.nextInt(), y = in.nextInt();\n\/\/ out.println(x-1-Math.min(x-1,n-y-1),y-1-Math.min(y-1,n-x-1));\n out.println(Math.max(x - 1 - Math.min(x - 1, Math.max(0, n - y - 1)), y - 1 - Math.min(y - 1, Math.max(0, n - x - 1))) + 1, (n - Math.min(n - x - Math.min(n - x, y - 1), n - y - Math.min(n - y, x - 1))));\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 }\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\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 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 A_ConnerR_and_the_A_R_C_Markland_N {\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 = f.nextInt();\n\n\n\n while(t-- > 0){\n\n solve(f, out);\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 int s = f.nextInt();\n\n int k = f.nextInt();\n\n\n\n HashSet hs = new HashSet<>();\n\n for(int i = 0; i < k; i++) {\n\n hs.add(f.nextInt());\n\n }\n\n\n\n int ans = 0;\n\n int i = s;\n\n int j = s;\n\n while(hs.contains(i) && hs.contains(j)) {\n\n ans++;\n\n if(i > 1) {\n\n i--;\n\n }\n\n if(j < n) {\n\n j++;\n\n }\n\n }\n\n\n\n out.println(ans);\n\n\n\n\n\n }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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 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 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 public static int gcd(int a, int b) {\n\n int dividend = a > b ? a : b;\n\n int divisor = a < b ? a : b;\n\n \n\n while(divisor > 0) {\n\n int reminder = dividend % divisor;\n\n dividend = divisor;\n\n divisor = reminder;\n\n }\n\n return dividend;\n\n }\n\n\n\n public static int lcm(int a, int b) {\n\n int lcm = gcd(a, b);\n\n int hcf = (a * b) \/ lcm;\n\n return hcf;\n\n }\n\n\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 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 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\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","language":"java"} +{"contest_id":"1300","problem_id":"B","statement":"B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,\u2026,a2k+1][a1,a2,\u2026,a2k+1] of odd number of elements is defined as follows: let [b1,b2,\u2026,b2k+1][b1,b2,\u2026,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u22641041\u2264t\u2264104). The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105)\u00a0\u2014 the number of students halved.The second line of each test case contains 2n2n integers a1,a2,\u2026,a2na1,a2,\u2026,a2n (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3\n1\n1 1\n3\n6 5 4 1 2 3\n5\n13 4 20 13 2 5 8 3 17 16\nOutputCopy0\n1\n5\nNoteIn the first test; there is only one way to partition students\u00a0\u2014 one in each class. The absolute difference of the skill levels will be |1\u22121|=0|1\u22121|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4\u22123|=1|4\u22123|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.","tags":["greedy","implementation","sortings"],"code":"import java.util.*;\n\npublic class gh{\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 while(t-->0)\n\n {\n\n int n=sc.nextInt();\n\n int[] ar=new int[2*n];\n\n for(int i=0;i<2*n;i++)\n\n ar[i]=sc.nextInt();\n\n Arrays.sort(ar);\n\n int min=Integer.MAX_VALUE;\n\n for(int i=0;i' 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":"import java.io.*;\n\nimport java.util.*;\n\npublic class Main {\n\n\tpublic static void main(String[] args) throws IOException \n\n\t{ \n\n\t\tFastScanner f = new FastScanner(); \n\n\t\tint ttt=1;\n\n\t\tttt=f.nextInt();\n\n\t\tPrintWriter out=new PrintWriter(System.out);\n\n\t\tfor(int tt=0;tt')\n\n\t\t\t\t{\n\n\t\t\t\t\tfor (int j = i; j >= last; j--)\n\n\t\t\t\t\t\tans[j] = num--;\n\n\t\t\t\t\tlast = i + 1;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tfor (int i:ans) System.out.print(i+\" \");\n\n\t\t\tSystem.out.println();\n\n\t\t\tans=new int[n];\n\n\t\t\tnum = 1;\n\n\t\t\tlast = 0;\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t{\n\n\t\t\t\tif (i == n - 1 || l[i] == '<')\n\n\t\t\t\t{\n\n\t\t\t\t\tfor (int j = i; j >= last; j--)\n\n\t\t\t\t\t\tans[j] = num++;\n\n\t\t\t\t\tlast = i + 1;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tfor (int i:ans) System.out.print(i+\" \");\n\n\t\t\tSystem.out.println();\n\n\t\t}\n\n\t\tout.close();\n\n\t} \n\n\tstatic void sort(int[] p) {\n\n ArrayList q = new ArrayList<>();\n\n for (int i: p) q.add( i);\n\n Collections.sort(q);\n\n for (int i = 0; i < p.length; i++) p[i] = q.get(i);\n\n }\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\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\t\t\n\n\t\tint nextInt() {\n\n\t\t\treturn Integer.parseInt(next());\n\n\t\t}\n\n\t\tint[] readArray(int n) {\n\n\t\t\tint[] a=new int[n];\n\n\t\t\tfor (int i=0; i 0 && (base[i] & (1 << j)) != 0) {\n\n base[i] ^= base[j];\n\n }\n\n for (int j = i - 1; j >= 0; j--) if ((base[j] & (1 << i)) != 0) {\n\n base[j] ^= base[i];\n\n }\n\n return true;\n\n }\n\n vector ^= base[i];\n\n }\n\n return false;\n\n }\n\n\n\n public class ArrayHash {\n\n int[] array;\n\n\n\n public ArrayHash(int[] array) {\n\n this.array = Arrays.copyOf(array, array.length);\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 ArrayHash arrayHash = (ArrayHash) o;\n\n return Arrays.equals(array, arrayHash.array);\n\n }\n\n\n\n @Override\n\n public int hashCode() {\n\n return Arrays.hashCode(array);\n\n }\n\n }\n\n\n\n public class DisjointSet {\n\n int[] arr;\n\n public DisjointSet(int n) {\n\n arr = new int[n];\n\n Arrays.fill(arr, -1);\n\n }\n\n int find(int x) {\n\n if (arr[x] < 0) return x;\n\n return arr[x] = find(arr[x]);\n\n }\n\n boolean union(int a, int b) {\n\n int ra = find(a), rb = find(b);\n\n if (ra == rb) return false;\n\n arr[ra] = rb;\n\n return true;\n\n }\n\n }\n\n\n\n public class Pair {\n\n int a, b;\n\n public Pair(int a, int b) {\n\n this.a = a;\n\n this.b = b;\n\n }\n\n }\n\n\n\n public class Triple {\n\n int a, b, c;\n\n public Triple(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 Triple(int[] z) {\n\n this.a = z[0];\n\n this.b = z[1];\n\n this.c = z[2];\n\n }\n\n }\n\n int S = 374;\n\n\n\n int[] xorValues;\n\n int[] root;\n\n int[] parent;\n\n int[][] inputEdges;\n\n int[][] dpVal;\n\n boolean[] off;\n\n List additionalEdges;\n\n List[] treeEdges;\n\n List[] treeBasis;\n\n int[] treeBasisIndex;\n\n Map basisToIndex;\n\n List indexToBasis;\n\n int[][] basisTransition = new int[S][S];\n\n\n\n void dfs(int u, int p, int r, int val) {\n\n root[u] = r;\n\n parent[u] = p;\n\n xorValues[u] = val;\n\n for (Pair v: treeEdges[u]) if (v.a != p) {\n\n dfs(v.a, u, r, val ^ v.b);\n\n }\n\n }\n\n int mod = 1_000_000_007;\n\n int add(int a, int b) {\n\n int c = a + b;\n\n if (c >= mod) return c - mod;\n\n return c;\n\n }\n\n\n\n int getIndexOfBasis(int[] basis) {\n\n ArrayHash ar = new ArrayHash(basis);\n\n if (!basisToIndex.containsKey(ar)) {\n\n basisToIndex.put(ar, basisToIndex.size());\n\n indexToBasis.add(ar);\n\n }\n\n if (basisToIndex.size() > S) throw new RuntimeException();\n\n return basisToIndex.get(ar);\n\n }\n\n\n\n int merge(int basisIndex1, int basisIndex2) {\n\n if (basisTransition[basisIndex1][basisIndex2] == -2) {\n\n int[] basis1 = Arrays.copyOf(indexToBasis.get(basisIndex1).array, 5);\n\n int[] basis2 = Arrays.copyOf(indexToBasis.get(basisIndex2).array, 5);\n\n boolean valid = true;\n\n for (int b : basis2) {\n\n if (b != 0) {\n\n if (!insertVector(basis1, b)) {\n\n valid = false;\n\n }\n\n }\n\n }\n\n if (valid) {\n\n basisTransition[basisIndex1][basisIndex2] = basisTransition[basisIndex2][basisIndex1] = getIndexOfBasis(basis1);\n\n } else {\n\n basisTransition[basisIndex1][basisIndex2] = basisTransition[basisIndex2][basisIndex1] = -1;\n\n }\n\n }\n\n return basisTransition[basisIndex1][basisIndex2];\n\n }\n\n\n\n public void solve(Scanner sc, PrintWriter pw) throws IOException {\n\n for (int i = 0; i < S; i++) {\n\n Arrays.fill(basisTransition[i], -2);\n\n }\n\n basisToIndex = new HashMap<>();\n\n indexToBasis = new ArrayList<>();\n\n int n = sc.nextInt();\n\n int m = sc.nextInt();\n\n xorValues = new int[n];\n\n root = new int[n];\n\n parent = new int[n];\n\n off = new boolean[n];\n\n Arrays.fill(off, true);\n\n treeEdges = new List[n];\n\n additionalEdges = new ArrayList<>();\n\n treeBasis = new List[n];\n\n treeBasisIndex = new int[n];\n\n getIndexOfBasis(new int[5]);\n\n DisjointSet djs = new DisjointSet(n);\n\n for (int i = 0; i < n; i++) {\n\n treeEdges[i] = new ArrayList<>();\n\n treeBasis[i] = new ArrayList<>();\n\n }\n\n inputEdges = new int[m][3];\n\n for (int i = 0; i < m; i++) {\n\n for (int j = 0; j < 3; j++) {\n\n inputEdges[i][j] = sc.nextInt();\n\n }\n\n }\n\n for (int i = 0; i < m; i++) {\n\n inputEdges[i][0]--;\n\n inputEdges[i][1]--;\n\n if (inputEdges[i][0] == 0 || inputEdges[i][1] == 0) {\n\n djs.union(inputEdges[i][0], inputEdges[i][1]);\n\n treeEdges[inputEdges[i][0]].add(new Pair(inputEdges[i][1], inputEdges[i][2]));\n\n treeEdges[inputEdges[i][1]].add(new Pair(inputEdges[i][0], inputEdges[i][2]));\n\n }\n\n }\n\n for (int i = 0; i < m; i++) {\n\n if (inputEdges[i][0] != 0 && inputEdges[i][1] != 0) {\n\n if (djs.union(inputEdges[i][0], inputEdges[i][1])) {\n\n treeEdges[inputEdges[i][0]].add(new Pair(inputEdges[i][1], inputEdges[i][2]));\n\n treeEdges[inputEdges[i][1]].add(new Pair(inputEdges[i][0], inputEdges[i][2]));\n\n } else {\n\n additionalEdges.add(new Triple(inputEdges[i]));\n\n }\n\n }\n\n }\n\n for (Pair p: treeEdges[0]) {\n\n off[p.a] = false;\n\n dfs(p.a, 0, p.a, p.b);\n\n }\n\n List pairedTrees = new ArrayList<>();\n\n\n\n for (Triple tri: additionalEdges) {\n\n int a = tri.a;\n\n int b = tri.b;\n\n if (root[a] != root[b]) {\n\n if (a != root[a] || b != root[b]) throw new RuntimeException();\n\n pairedTrees.add(tri);\n\n \/\/ across\n\n } else {\n\n int cycle = tri.c ^ xorValues[a] ^ xorValues[b];\n\n treeBasis[root[a]].add(cycle);\n\n }\n\n }\n\n List> choicesForTree = new ArrayList<>();\n\n for (int i = 1; i < n; i++) if (root[i] == i) {\n\n int[] basis = new int[5];\n\n for (int cycle: treeBasis[i]) {\n\n if (!insertVector(basis, cycle)) {\n\n off[i] = true;\n\n }\n\n }\n\n if (!off[i]) {\n\n treeBasisIndex[i] = getIndexOfBasis(basis);\n\n }\n\n }\n\n for (Triple p: pairedTrees) {\n\n if (off[p.a] || off[p.b]) {\n\n off[p.a] = off[p.b] = true;\n\n continue;\n\n }\n\n off[p.a] = true;\n\n off[p.b] = true;\n\n int nr;\n\n if ((nr = merge(treeBasisIndex[p.a], treeBasisIndex[p.b])) != -1) {\n\n List choices = new ArrayList<>();\n\n int[] basis = Arrays.copyOf(indexToBasis.get(nr).array, 5);\n\n choices.add(nr);\n\n choices.add(nr);\n\n if (insertVector(basis, p.c ^ xorValues[p.a] ^ xorValues[p.b])) {\n\n choices.add(getIndexOfBasis(basis));\n\n }\n\n choicesForTree.add(choices);\n\n }\n\n }\n\n for (int i = 1; i < n; i++) if (root[i] == i && !off[i]) {\n\n List choice = new ArrayList<>();\n\n choice.add(treeBasisIndex[i]);\n\n choicesForTree.add(choice);\n\n }\n\n dpVal = new int[2][S]; \/\/ \\sum_{i=0}^5 {5 \\choose i}_2\n\n dpVal[0][0] = 1;\n\n int cur = 0, next = 1;\n\n for (List choices: choicesForTree) {\n\n System.arraycopy(dpVal[cur], 0, dpVal[next], 0, S);\n\n for (int choice: choices) {\n\n for (int i = 0; i < S; i++) if (dpVal[cur][i] > 0) {\n\n int nr;\n\n if ((nr = merge(i, choice)) != -1) {\n\n dpVal[next][nr] = add(dpVal[next][nr], dpVal[cur][i]);\n\n }\n\n }\n\n }\n\n cur ^= 1;\n\n next ^= 1;\n\n }\n\n int total = 0;\n\n for (int i = 0; i < S; i++) total = add(total, dpVal[cur][i]);\n\n pw.println(total);\n\n }\n\n }\n\n static long TIME_START, TIME_END;\n\n public static void main(String[] args) throws IOException {\n\n Scanner sc = new Scanner(System.in);\n\n\/\/ Scanner sc = new Scanner(new FileInputStream(\"input\"));\n\n PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));\n\n\/\/ PrintWriter pw = new PrintWriter(new FileOutputStream(\"input\"));\n\n\n\n Runtime runtime = Runtime.getRuntime();\n\n long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();\n\n TIME_START = System.currentTimeMillis();\n\n Task t = new Task();\n\n t.solve(sc, pw);\n\n TIME_END = System.currentTimeMillis();\n\n long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();\n\n pw.close();\n\n System.err.println(\"Memory increased: \" + (usedMemoryAfter - usedMemoryBefore) \/ 1000000);\n\n System.err.println(\"Time used: \" + (TIME_END - TIME_START) + \".\");\n\n }\n\n static class Scanner {\n\n StringTokenizer st;\n\n BufferedReader br;\n\n public Scanner(InputStream s) {\n\n br = new BufferedReader(new InputStreamReader(s));\n\n }\n\n public Scanner(FileReader s) throws FileNotFoundException {\n\n br = new BufferedReader(s);\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 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 public String nextLine() throws IOException {\n\n return br.readLine();\n\n }\n\n public double nextDouble() throws IOException {\n\n return Double.parseDouble(next());\n\n }\n\n public boolean ready() throws IOException {\n\n return br.ready();\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 0) {\n long a = fastReader.nextLong();\n long m = fastReader.nextLong();\n long gcd = gcd(a,m);\n out.println(solve(m\/gcd));\n }\n out.close();\n }\n\n private static long solve(long x) {\n long temp = x;\n for(long i = 2; i*i <=x ; i++){\n if(x% i == 0){\n temp -=(temp\/i);\n while(x % i == 0){\n x\/=i;\n }\n\n }\n }\n if(x > 1){\n temp -=(temp\/x);\n }\n return temp;\n }\n\n\n public static class Pair{\n int val;\n int index;\n\n public Pair(int val, int index) {\n this.val = val;\n this.index = index;\n }\n\n @Override\n public String toString() {\n return \"Pair{\" +\n \"val=\" + val +\n \", index=\" + index +\n '}';\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 static int[][] direction = new int[][]{{-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0, -1}};\n\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 static char maxc(char a, char b){\n if(a > b){\n return a;\n }\n return b;\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":"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.*;\nimport java.io.*;\npublic class NewYearAndNaming{\n public static void main(String[] args){\n Scanner scn = new Scanner(System.in);\n int n = scn.nextInt();\n int m = scn.nextInt();\n\n String[] pre = new String[n];\n String[] suff = new String[m];\n\n for(int i=0;i0){\n int year = scn.nextInt();\n int preidx = (year-1)%n;\n int suffidx = (year-1)%m;\n\n String name = pre[preidx] + suff[suffidx];\n System.out.println(name);\n t--;\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":"\/\/\/\/package com.company;\n\nimport com.sun.source.tree.ArrayAccessTree;\n\n\n\nimport javax.swing.*;\n\nimport java.beans.IntrospectionException;\n\nimport java.math.BigInteger;\n\nimport java.util.*;\n\nimport java.io.*;\n\n\n\n\n\npublic class Main {\n\n\n\n\n\n static class pair implements Comparable {\n\n long a = 0;\n\n long b = 0;\n\n \/\/ int cnt;\n\n\n\n pair(long b, long a) {\n\n this.a = b;\n\n this.b = a;\n\n \/\/ cnt = x;\n\n }\n\n\n\n @Override\n\n public int compareTo(pair o) {\n\n\n\n if(this.a != o.a)\n\n return (int) (this.a - o.a);\n\n else\n\n return (int) (this.b - o.b);\n\n }\n\n\/\/ public boolean equals(Object o) {\n\n\/\/ if (o instanceof pair) {\n\n\/\/ pair p = (pair) o;\n\n\/\/ return p.a == a && p.b == b;\n\n\/\/ }\n\n\/\/ return false;\n\n\/\/ }\n\n\/\/\n\n\/\/ public int hashCode() {\n\n\/\/ return (Long.valueOf(a).hashCode()) * 31 + (Long.valueOf(b).hashCode());\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.hasMoreTokens()) {\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().trim();\n\n } catch (Exception e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n\n\n static class FastWriter {\n\n private final BufferedWriter bw;\n\n\n\n public FastWriter() {\n\n this.bw = new BufferedWriter(new OutputStreamWriter(System.out));\n\n }\n\n\n\n public void prlong(Object object) throws IOException {\n\n\n\n bw.append(\"\" + object);\n\n }\n\n\n\n public void prlongln(Object object) throws IOException {\n\n prlong(object);\n\n bw.append(\"\\n\");\n\n }\n\n\n\n public void close() throws IOException {\n\n bw.close();\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 return gcd(b % a, a);\n\n }\n\n\n\n\n\n\n\n \/\/HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS\n\n\n\n\/\/ HashSet set = new HashSet<>();\n\n\/\/ for(int i = 0; i < s.length(); i++){\n\n\/\/ int b = 0;\n\n\/\/ long h = 1;\n\n\/\/ for(int j=i; j= 0; i--) {\n\n invfact[i] = (invfact[i + 1] * (i + 1)) % p;\n\n }\n\n }\n\n\n\n private long nCr(int n, int r) {\n\n if (r > n || n < 0 || r < 0) return 0;\n\n return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p;\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\n\n static void sort(long[] a ) {\n\n ArrayList l = new ArrayList<>();\n\n for(long i: a) {\n\n l.add(i);\n\n }\n\n Collections.sort(l);\n\n for(int i =0;ians=new ArrayList<>();\n\n\/\/ for(int i =0;i 0) {\n\n\n\n\n\n\n\nlong x =in.nextLong();\n\nlong ans =x;\n\n\n\nfor(long i =1;i*i 0 && temp.charAt(len) !=\n\n temp.charAt(i))\n\n {\n\n len = lps[len - 1];\n\n }\n\n if (temp.charAt(i) == temp.charAt(len))\n\n {\n\n len++;\n\n }\n\n lps[i] = len;\n\n }\n\n\n\n\/\/ return temp.substring(0, lps[n - 1]);\n\n }\n\n\n\n static String reverse(String input)\n\n {\n\n char[] a = input.toCharArray();\n\n int l, r = a.length - 1;\n\n\n\n for(l = 0; l < r; l++, r--)\n\n {\n\n char temp = a[l];\n\n a[l] = a[r];\n\n a[r] = temp;\n\n }\n\n return String.valueOf(a);\n\n }\n\n}\n\n\n\n\n\n\n\n\n\n\/*\n\n *\n\n *\u3000\u3000\u250f\u2513\u3000\u3000\u3000\u250f\u2513+ +\n\n *\u3000\u250f\u251b\u253b\u2501\u2501\u2501\u251b\u253b\u2513 + +\n\n *\u3000\u2503\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u2503\n\n *\u3000\u2503\u3000\u3000\u3000\u2501\u3000\u3000\u3000\u2503 ++ + + +\n\n * \u2588\u2588\u2588\u2588\u2501\u2588\u2588\u2588\u2588+\n\n * \u25e5\u2588\u2588\u25e4\u3000\u25e5\u2588\u2588\u25e4 +\n\n *\u3000\u2503\u3000\u3000\u3000\u253b\u3000\u3000\u3000\u2503\n\n *\u3000\u2503\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u2503 + +\n\n *\u3000\u2517\u2501\u2513\u3000\u3000\u3000\u250f\u2501\u251b\n\n *\u3000\u3000\u3000\u2503\u3000\u3000\u2503 JACKS PET FROM ANOTHER WORLD\n\n *\u3000\u3000\u3000\u2503\u3000\u3000\u2503\n\n *\u3000\u3000\u3000\u2503\u3000 \u3000 \u2517\u2501\u2501\u2501\u2513\n\n *\u3000\u3000\u3000\u2503 \u3000\u3000\u3000\u3000\u3000\u3000 \u2523\u2513-------\n\n *\u3000\u3000 \u2503 \u3000\u3000\u3000\u3000\u3000 \u3000\u250f\u251b-------\n\n *\u3000 \u2517\u2513\u2513\u250f\u2501\u2533\u2513\u250f\u251b + + + +\n\n *\u3000\u3000\u3000\u3000\u2503\u252b\u252b\u3000\u2503\u252b\u252b\n\n *\u3000\u3000\u3000\u3000\u2517\u253b\u251b\u3000\u2517\u253b\u251b+ + + +\n\n *\/\n\n\n\n\/\/RULES\n\n\/\/TAKE INPUT AS LONG IN CASE OF SUM OR MULITPLICATION OR CHECK THE CONTSRaint of the array\n\n\/\/Always use stringbuilder of out.println for strinof out.println for string or high level output\n\n\n\n\n\n\/\/ IMPORTANT TRs1 TO USE BRUTE FORCE TECHNIQUE TO SOLVE THE PROs1 OTHER CERTAIN LIMIT IS GIVENIT IS GIVEN\n\n\n\n\/\/Read minute details if coming wrong for no idea questions","language":"java"} +{"contest_id":"1299","problem_id":"A","statement":"A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)\u2212yf(x,y)=(x|y)\u2212y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)\u22126=15\u22126=9f(11,6)=(11|6)\u22126=15\u22126=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,\u2026,an][a1,a2,\u2026,an] is defined as f(f(\u2026f(f(a1,a2),a3),\u2026an\u22121),an)f(f(\u2026f(f(a1,a2),a3),\u2026an\u22121),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105).The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u22641090\u2264ai\u2264109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4\n4 0 11 6\nOutputCopy11 6 4 0InputCopy1\n13\nOutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.","tags":["brute force","greedy","math"],"code":"import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.StringTokenizer;\n\npublic class P1299A {\n\n public static void main(String[] args) {\n\n FastScanner s = new FastScanner();\n int n = s.nextInt();\n int[] arr = s.readArray(n);\n for (int i = 31; i >= 0; i--) {\n int count = 0;\n for (int j : arr) {\n if ((j & (1 << i)) > 0) {\n count++;\n }\n }\n if (count == 1) {\n for (int j = 0; j < n; j++) {\n if ((arr[j] & (1 << i)) > 0) {\n int temp = arr[j];\n arr[j] = arr[0];\n arr[0] = temp;\n }\n }\n break;\n }\n }\n StringBuilder ans = new StringBuilder();\n for (int i = 0; i < n; i++) {\n ans.append(arr[i]);\n if (i != n - 1) {\n ans.append(\" \");\n }\n }\n System.out.println(ans);\n\n }\n\n static class FastScanner {\n BufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n StringTokenizer st=new StringTokenizer(\"\");\n String next() {\n while (!st.hasMoreTokens())\n try {\n st=new StringTokenizer(br.readLine());\n } catch (IOException e) {\n e.printStackTrace();\n }\n return st.nextToken();\n }\n\n int nextInt() {\n return Integer.parseInt(next());\n }\n int[] readArray(int n) {\n int[] a=new int[n];\n for (int i=0; iappend+1) {\n\n\t\t\tautoC=append+1;\n\n\t\t}\n\n\t\t\n\n\t\tfor(int c=0;c<26;c++) {\n\n\t\t\tint nxt=children[i][c];\n\n\t\t\tif(nxt!=0) {\n\n\t\t\t\tdfs2(nxt, ans[i]+1, autoC+smaller[nxt]-smaller[i]);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tpublic static void main(String[] args) throws IOException {\n\n\t\tMScanner sc=new MScanner(System.in);\n\n\t\tPrintWriter pw=new PrintWriter(System.out);\n\n\t\tint n=sc.nextInt();\n\n\t\tchildren=new int[n+1][26];\n\n\t\tfor(int i=1;i<=n;i++) {\n\n\t\t\tint par=sc.nextInt();char c=sc.nextChar();\n\n\t\t\tchildren[par][c-'a']=i;\n\n\t\t}\n\n\t\tS=new boolean[n+1];\n\n\t\tint k=sc.nextInt();\n\n\t\tint[]ks=new int[k];\n\n\t\tfor(int i=0;i=0;p--)\n\n\t\t {\n\n\t\t ans[n-1-p]=arr[p];\n\n\t\t }\n\n\t\t for(int j=0;j al=new ArrayList<>();\n\n int l=0,r=n-1,k=0;\n\n while(l= 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 }\n\n return buf[curChar++];\n\n }\n\n\n\n public int readInt() {\n\n int c = read();\n\n while (isSpaceChar(c)) {\n\n c = read();\n\n }\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 }\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 int[] nextIntArray(int arraySize) {\n\n int[] array = new int[arraySize];\n\n\n\n for (int i = 0; i < arraySize; i++) {\n\n array[i] = readInt();\n\n }\n\n\n\n return array;\n\n }\n\n\n\n public String readString() {\n\n int c = read();\n\n while (isSpaceChar(c)) {\n\n c = read();\n\n }\n\n StringBuilder res = new StringBuilder();\n\n do {\n\n if (Character.isValidCodePoint(c)) {\n\n res.appendCodePoint(c);\n\n }\n\n c = read();\n\n } while (!isSpaceChar(c));\n\n return res.toString();\n\n }\n\n\n\n public boolean isNewLine(int c) {\n\n return c == '\\n';\n\n }\n\n\n\n public String nextLine() {\n\n int c = read();\n\n\n\n StringBuilder result = new StringBuilder();\n\n\n\n do {\n\n result.appendCodePoint(c);\n\n\n\n c = read();\n\n } while (!isNewLine(c));\n\n\n\n return result.toString();\n\n }\n\n\n\n public long nextLong() {\n\n int c = read();\n\n\n\n while (isSpaceChar(c)) {\n\n c = read();\n\n }\n\n\n\n int sign = 1;\n\n\n\n if (c == '-') {\n\n sign = -1;\n\n\n\n c = read();\n\n }\n\n\n\n long result = 0;\n\n\n\n do {\n\n if (c < '0' || c > '9') {\n\n throw new InputMismatchException();\n\n }\n\n\n\n result *= 10;\n\n result += c & 15;\n\n\n\n c = read();\n\n } while (!isSpaceChar(c));\n\n\n\n return result * sign;\n\n }\n\n\n\n public long[] nextLongArray(int arraySize) {\n\n long array[] = new long[arraySize];\n\n\n\n for (int i = 0; i < arraySize; i++) {\n\n array[i] = nextLong();\n\n }\n\n\n\n return array;\n\n }\n\n\n\n public double nextDouble() {\n\n double ret = 0, div = 1;\n\n byte c = (byte) read();\n\n\n\n while (c <= ' ') {\n\n c = (byte) read();\n\n }\n\n\n\n boolean neg = (c == '-');\n\n\n\n if (neg) {\n\n c = (byte) read();\n\n }\n\n\n\n do {\n\n ret = ret * 10 + c - '0';\n\n } while ((c = (byte) read()) >= '0' && c <= '9');\n\n\n\n if (c == '.') {\n\n while ((c = (byte) 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 }\n\n\n\n return ret;\n\n }\n\n\n\n public boolean isSpaceChar(int c) {\n\n if (filter != null) {\n\n return filter.isSpaceChar(c);\n\n }\n\n return isWhitespace(c);\n\n }\n\n\n\n public static boolean isWhitespace(int c) {\n\n return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n\n }\n\n\n\n public interface SpaceCharFilter {\n\n public boolean isSpaceChar(int ch);\n\n\n\n }\n\n }\n\n\n\n static class CP {\n\n\n\n static boolean isPrime(long n) {\n\n if (n <= 1)\n\n return false;\n\n if (n == 2 || n == 3)\n\n return true;\n\n if (n % 2 == 0 || n % 3 == 0)\n\n return false;\n\n for (int i = 5; (long) i * i <= n; 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\n\n static String addChar(String s, int n, String ch) {\n\n String res =s+String.join(\"\", Collections.nCopies(n, ch));\n\n return res;\n\n }\n\n\n\n static int ifnotPrime(int[] prime, int x) {\n\n\n\n return (prime[x \/ 64] & (1 << ((x >> 1) & 31)));\n\n }\n\n\n\n static void makeComposite(int[] prime, int x) {\n\n\n\n prime[x \/ 64] |= (1 << ((x >> 1) & 31));\n\n }\n\n\n\n static ArrayList bitWiseSieve(int n) {\n\n ArrayList al = new ArrayList<>();\n\n int prime[] = new int[n \/ 64 + 1];\n\n\n\n\n\n for (int i = 3; i * i <= n; i += 2) {\n\n\n\n if (ifnotPrime(prime, i) == 0)\n\n for (int j = i * i, k = i << 1;\n\n j < n; j += k)\n\n makeComposite(prime, j);\n\n }\n\n\n\n al.add(2);\n\n\n\n for (int i = 3; i <= n; i += 2)\n\n if (ifnotPrime(prime, i) == 0)\n\n al.add(i);\n\n\n\n return al;\n\n }\n\n\n\n public static long[] sort(long arr[]){\n\n List list = new ArrayList<>();\n\n for(long n : arr){list.add(n);}\n\n Collections.sort(list);\n\n for(int i=0;i sieve(long size) {\n\n\n\n ArrayList pr = new ArrayList();\n\n boolean prime[] = new boolean[(int) size];\n\n for (int i = 2; i < prime.length; i++) prime[i] = true;\n\n for (int i = 2; i * i < prime.length; i++) {\n\n if (prime[i]) {\n\n for (int j = i * i; j < prime.length; j += i) {\n\n prime[j] = false;\n\n }\n\n }\n\n }\n\n for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i);\n\n return pr;\n\n }\n\n\n\n static ArrayList segmented_sieve(int l, int r, ArrayList primes) {\n\n ArrayList al=new ArrayList<>();\n\n if (l == 1) ++l;\n\n int max = r - l + 1;\n\n int arr[] = new int[max];\n\n for (int p : primes) {\n\n if (p * p <= r) {\n\n int i = (l \/ p) * p;\n\n if (i < l) i += p;\n\n for (; i <= r; i += p) {\n\n if (i != p) {\n\n arr[i - l] = 1;\n\n }\n\n }\n\n }\n\n }\n\n for (int i = 0; i < max; ++i) {\n\n if (arr[i] == 0) {\n\n al.add(l+i);\n\n }\n\n }\n\n return al;\n\n }\n\n\n\n static boolean isfPrime(long n, int iteration) {\n\n\n\n if (n == 0 || n == 1)\n\n return false;\n\n\n\n if (n == 2)\n\n return true;\n\n\n\n if (n % 2 == 0)\n\n return false;\n\n\n\n Random rand = new Random();\n\n for (int i = 0; i < iteration; i++) {\n\n long r = Math.abs(rand.nextLong());\n\n long a = r % (n - 1) + 1;\n\n if (modPow(a, n - 1, n) != 1)\n\n return false;\n\n }\n\n return true;\n\n }\n\n\n\n static long modPow(long a, long b, long c) {\n\n long res = 1;\n\n for (int i = 0; i < b; i++) {\n\n res *= a;\n\n res %= c;\n\n }\n\n return res % c;\n\n }\n\n\n\n private static long binPower(long a, long l, long mod) {\n\n\n\n long res = 0;\n\n\n\n while (l > 0) {\n\n if ((l & 1) == 1) {\n\n res = mulmod(res, a, mod);\n\n ;\n\n l >>= 1;\n\n }\n\n a = mulmod(a, a, mod);\n\n }\n\n return res;\n\n }\n\n\n\n private static long mulmod(long a, long b, long c) {\n\n\n\n long x = 0, y = a % c;\n\n while (b > 0) {\n\n if (b % 2 == 1) {\n\n x = (x + y) % c;\n\n }\n\n y = (y * 2L) % c;\n\n b \/= 2;\n\n }\n\n return x % c;\n\n\n\n }\n\n\n\n static long binary_Expo(long a, long b) {\n\n long res = 1;\n\n while (b != 0) {\n\n if ((b & 1) == 1) {\n\n res *= a;\n\n --b;\n\n }\n\n a *= a;\n\n b \/= 2;\n\n }\n\n return res;\n\n }\n\n\n\n static long Modular_Expo(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) % 1000000007 ;\n\n --b;\n\n }\n\n a = (a * a) % 1000000007;\n\n b \/= 2;\n\n }\n\n return res%1000000007;\n\n }\n\n\n\n static int i_gcd(int a, int b) {\n\n while (true) {\n\n if (b == 0)\n\n return a;\n\n int c = a;\n\n a = b;\n\n b = c % b;\n\n }\n\n }\n\n\n\n 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\n\n static long ceil_div(long a, long b) {\n\n return (a + b - 1) \/ b;\n\n }\n\n\n\n static int getIthBitFromInt(int bits, int i) {\n\n return (bits >> (i - 1)) & 1;\n\n }\n\n\n\n private static TreeMap primeFactorize(long n) {\n\n TreeMap pf = new TreeMap<>(Collections.reverseOrder());\n\n long cnt = 0;\n\n long total = 1;\n\n for (long i = 2; (long) i * i <= n; ++i) {\n\n if (n % i == 0) {\n\n cnt = 0;\n\n while (n % i == 0) {\n\n ++cnt;\n\n n \/= i;\n\n }\n\n pf.put(cnt, i);\n\n \/\/total*=(cnt+1);\n\n }\n\n }\n\n if (n > 1) {\n\n pf.put(1L, n);\n\n \/\/total*=2;\n\n }\n\n return pf;\n\n }\n\n\n\n static long upper_Bound(long a[], long x) {\n\n long l = -1, r = a.length;\n\n while (l + 1 < r) {\n\n long m = (l + r) >>> 1;\n\n if (a[(int) m] <= x)\n\n l = m;\n\n else\n\n r = m;\n\n }\n\n return l + 1;\n\n }\n\n\n\n static int lower_Bound(ArrayList a,int x) {\n\n int l = 0, r = a.size()-1,ans=-1,mid=0;\n\n while(l<=r)\n\n {\n\n mid=(l+r)>>1;\n\n if(a.get(mid)<=x)\n\n {\n\n ans=mid;\n\n l=mid+1;\n\n }\n\n else\n\n {\n\n r=mid-1;\n\n }\n\n }\n\n return ans;\n\n }\n\n\n\n static int lower_Bound(int a[],int x) {\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[(int) m] >= x)\n\n r = m;\n\n else\n\n l = m;\n\n }\n\n return r;\n\n }\n\n\n\n static int upperBound(int a[], int x) {\/\/ x is the key or target value\n\n int l=-1,r=a.length;\n\n while(l+1>>1;\n\n if(a[m]<=x) l=m;\n\n else r=m;\n\n }\n\n return l+1;\n\n }\n\n\n\n static int bsh(int a[],int t) {\n\n int ans =-1;\n\n int i = 0, j = a.length - 1;\n\n while (i <= j) {\n\n int mid = i + (j - i) \/ 2;\n\n if (a[mid] > t) {\n\n ans = mid;\n\n \/\/System.out.print(\"uppr \"+a[ans]);\n\n j=mid-1;\n\n }\n\n else{\n\n \/\/System.out.print(\"less \"+a[mid]);\n\n i=mid+1;\n\n }\n\n }\n\n return ans;\n\n }\n\n\n\n static int bsl(int a[],int t) {\n\n int ans =-1;\n\n int i = 0, j = a.length-1;\n\n while (i <= j) {\n\n int mid = i + (j - i) \/ 2;\n\n if (a[mid] <= t) {\n\n ans = mid;\n\n i=mid+1;\n\n } else if (a[mid] > t) {\n\n j = mid - 1;\n\n }\n\n }\n\n return ans;\n\n }\n\n\n\n static int upper_Bound(ArrayList a,int x) \/\/closest to the right\n\n {\n\n int l = 0, r = a.size()-1,ans=-1,mid=0;\n\n while(l<=r)\n\n {\n\n mid=(l+r)>>1;\n\n if(a.get(mid)>x)\n\n {\n\n ans=mid;\n\n r=mid-1;\n\n }\n\n else\n\n {\n\n l=mid+1;\n\n }\n\n }\n\n return ans;\n\n }\n\n\n\n static boolean isSquarefactor(int x, int factor, int target) {\n\n int s = (int) Math.round(Math.sqrt(x));\n\n return factor * s * s == target;\n\n }\n\n\n\n static boolean isSquare(int x) {\n\n int s = (int) Math.round(Math.sqrt(x));\n\n return x * x == s;\n\n }\n\n\n\n static void sort(int a[]) \/\/ heap sort\n\n {\n\n PriorityQueue q = new PriorityQueue<>();\n\n for (int i = 0; i < a.length; i++)\n\n q.add(a[i]);\n\n for (int i = 0; i < a.length; i++)\n\n a[i] = q.poll();\n\n }\n\n\n\n static void shuffle(int[] in) {\n\n for (int i = 0; i < in.length; i++) {\n\n int idx = (int) (Math.random() * in.length);\n\n fast_swap(in, idx, i);\n\n }\n\n }\n\n\n\n static boolean isPalindrome(String s)\n\n {\n\n StringBuilder sb=new StringBuilder(s);\n\n sb.reverse();\n\n if(s.equals(sb.toString()))\n\n {\n\n return true;\n\n }\n\n return false;\n\n }\n\n\n\n static int[] computeLps(String pat) {\n\n int len = 0, i = 1, m = pat.length();\n\n int lps[] = new int[m];\n\n lps[0] = 0;\n\n while (i < m) {\n\n if (pat.charAt(i) == pat.charAt(len)) {\n\n ++len;\n\n lps[i] = len;\n\n ++i;\n\n } else {\n\n if (len != 0) {\n\n len = lps[len - 1];\n\n } else {\n\n lps[i] = len;\n\n ++i;\n\n }\n\n }\n\n }\n\n return lps;\n\n }\n\n\n\n static void kmp(String s, String pat,int[] prf,int[] st) {\n\n int n = s.length(), m = pat.length();\n\n int lps[] = computeLps(pat);\n\n int i = 0, j = 0;\n\n while (i < n) {\n\n if (s.charAt(i) == pat.charAt(j)) {\n\n i++;\n\n j++;\n\n if (j == m) {\n\n ++prf[(i-j)+m];\n\n ++st[(i-j)+1];\n\n j=lps[j - 1];\n\n }\n\n\n\n } else {\n\n if (j != 0) {\n\n j = lps[j - 1];\n\n } else {\n\n i++;\n\n }\n\n }\n\n }\n\n }\n\n\n\n static void reverse_ruffle_sort(int a[]) {\n\n shuffle(a);\n\n Arrays.sort(a);\n\n for (int l = 0, r = a.length - 1; l < r; ++l, --r)\n\n fast_swap(a, l, r);\n\n\n\n }\n\n\n\n static void ruffle_sort(int a[]) {\n\n shuffle(a);\n\n Arrays.sort(a);\n\n }\n\n\n\n static int getMax(int arr[], int n) {\n\n int mx = arr[0];\n\n for (int i = 1; i < n; i++)\n\n if (arr[i] > mx)\n\n mx = arr[i];\n\n return mx;\n\n }\n\n\n\n static ArrayList primeFactors(long n) {\n\n ArrayList al = new ArrayList<>();\n\n al.add(1L);\n\n while (n % 2 == 0) {\n\n if(!al.contains(2L))\n\n {\n\n al.add(2L);\n\n }\n\n n \/= 2L;\n\n }\n\n\n\n for (int i = 3; (long) i * i <= n; i += 2) {\n\n while ((n % i == 0)) {\n\n if(!al.contains((long)i))\n\n {\n\n al.add((long) i);\n\n }\n\n n \/= i;\n\n }\n\n }\n\n\n\n if (n > 2) {\n\n if(!al.contains(n))\n\n {\n\n al.add(n);\n\n }\n\n }\n\n return al;\n\n }\n\n\n\n static int[] z_function(String s) {\n\n int n = s.length(), z[] = new int[n];\n\n\n\n for (int i = 1, l = 0, r = 0; i < n; ++i) {\n\n if (i <= r)\n\n z[i] = Math.min(z[i - l], r - i + 1);\n\n\n\n while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))\n\n ++z[i];\n\n\n\n if (i + z[i] - 1 > r) {\n\n l = i;\n\n r = i + z[i] - 1;\n\n }\n\n }\n\n return z;\n\n }\n\n\n\n static void swap(int a[], int idx1, int idx2) {\n\n a[idx1] += a[idx2];\n\n a[idx2] = a[idx1] - a[idx2];\n\n a[idx1] -= a[idx2];\n\n }\n\n\n\n static void fast_swap(int[] a, int idx1, int idx2) {\n\n if (a[idx1] == a[idx2])\n\n return;\n\n\n\n a[idx1] ^= a[idx2];\n\n a[idx2] ^= a[idx1];\n\n a[idx1] ^= a[idx2];\n\n }\n\n\n\n public static void fast_sort(long[] array) {\n\n ArrayList copy = new ArrayList<>();\n\n for (long i : array)\n\n copy.add(i);\n\n Collections.sort(copy);\n\n for (int i = 0; i < array.length; i++)\n\n array[i] = copy.get(i);\n\n }\n\n\n\n static int divCount(int n) {\n\n boolean hash[] = new boolean[n + 1];\n\n Arrays.fill(hash, true);\n\n for (int p = 2; p * p < n; p++)\n\n if (hash[p] == true)\n\n for (int i = p * 2; i < n; i += p)\n\n hash[i] = false;\n\n\n\n int total = 1;\n\n for (int p = 2; p <= n; p++) {\n\n if (hash[p]) {\n\n int count = 0;\n\n if (n % p == 0) {\n\n while (n % p == 0) {\n\n n = n \/ p;\n\n count++;\n\n }\n\n total = total * (count + 1);\n\n }\n\n }\n\n }\n\n return total;\n\n }\n\n\n\n static long binomialCoeff(long n,long k)\n\n {\n\n long res = 1;\n\n\n\n \/\/ Since C(n, k) = C(n, n-k)\n\n if (k > n - k)\n\n k = n - k;\n\n\n\n \/\/ Calculate value of\n\n \/\/ [n * (n-1) *---* (n-k+1)] \/ [k * (k-1) *----* 1]\n\n for (int i = 0; i < k; ++i) {\n\n res = (res*(n - i));\n\n res \/= (i + 1);\n\n }\n\n return res;\n\n }\n\n\n\n static long c(long fact[],long n,long k)\n\n {\n\n if(k>n) return 0;\n\n long res=fact[(int)n];\n\n res= (int) ((res * Modular_Expo(fact[(int)k], mod - 2))%mod);\n\n res= (int) ((res * Modular_Expo(fact[(int)n - (int)k], mod - 2))%mod);\n\n return res%mod;\n\n }\n\n\n\n public static ArrayList getFactors(long x) {\n\n\n\n ArrayList facts=new ArrayList<>();\n\n for(long i=2;i*i<=x;++i)\n\n {\n\n if(x%i==0)\n\n {\n\n facts.add(i);\n\n if(i!=x\/i)\n\n {\n\n facts.add(x\/i);\n\n }\n\n }\n\n }\n\n return facts;\n\n }\n\n\n\n public static HashMap sortMap(HashMap map) {\n\n\n\n List> list=new LinkedList<>(map.entrySet());\n\n\n\n Collections.sort(list,(o1,o2)->o2.getValue()-o1.getValue());\n\n\n\n HashMap temp=new LinkedHashMap<>();\n\n\n\n for(Map.Entry i:list)\n\n {\n\n temp.put(i.getKey(),i.getValue());\n\n }\n\n return temp;\n\n }\n\n\n\n public static long lcm(long l,long l2) {\n\n\n\n long val=CP.gcd(l,l2);\n\n return (l*l2)\/val;\n\n\n\n }\n\n\n\n }\n\n\n\n\n\n static void py() {\n\n System.out.println(\"YES\");\n\n }\n\n\n\n static void pn() {\n\n System.out.println(\"NO\");\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(int[] array) {\n\n for (int i = 0; i < array.length; i++) {\n\n if (i != 0) {\n\n writer.print(' ');\n\n }\n\n writer.print(array[i]);\n\n }\n\n }\n\n\n\n public void printLine(int[] array) {\n\n print(array);\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 printLine(long i) {\n\n writer.println(i);\n\n }\n\n\n\n public void printLine(int i) {\n\n writer.println(i);\n\n }\n\n public void printLine(char c)\n\n {\n\n writer.println(c);\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}\n\n\n\n\n\n\n\n\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.*;\n\nimport java.io.*;\n\nimport java.lang.*;\n\nimport java.math.*;\n\nimport java.io.BufferedReader;\n\nimport java.io.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.io.PrintWriter;\n\nimport java.util.ArrayList;\n\nimport java.util.Arrays;\n\nimport java.util.StringTokenizer;\n\nimport java.math.BigInteger;\n\n\n\nimport static java.lang.Math.max;\n\n\n\npublic class HelloWorld {\n\n\n\n public static void main(String[] args) throws IOException {\n\n Scanner input=new Scanner(System.in);\n\n \/\/static FastReader input=new FastReader();\n\n \/\/static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));\n\n int t=input.nextInt();\n\n while(t>0) {\n\n int n,i,m,j,k,f;\n\n long count=0,a,b,x,y,s1,s2,s3,s4,s;\n\n a=input.nextInt();\n\n b=input.nextInt();\n\n x=input.nextInt();\n\n y=input.nextInt();\n\n x++;\n\n y++;\n\n \/\/ArrayListara= new ArrayList<>();\n\n \/\/long ara[]=new long[i];\n\n \/\/Collections.sort(ara1);\n\n s1=(x-1)*b;\n\n s2=a*(y-1);\n\n s3=(a-x)*b;\n\n s4=a*(b-y);\n\n s=max(s4,max(s3,max(s2,s1)));\n\n System.out.println(s);\n\n \/\/System.out.println(s1+\" \"+s2+\" \"+s3+\" \"+s4);\n\n t--;\n\n }\n\n input.close();\n\n System.out.close();\n\n }\n\n\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 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 int[] readIntArray(int n)\n\n {\n\n int a[]=new int[n];\n\n for(int i=0;i=0)\n\n\t\t\tTH+=MIN[(int)x];\n\n \n\n\t\t\treturn TH<=0;\n\n\t\t}\n\n\n\n\t\t\t\tpublic static void main(String[] args) throws Exception \n\n\t\t\t\t {\t\t\n\n\t\t\t\t \t\t\t\n\n\t\t\t\t\tint tt=1;\n\n\t\t\t\t\t\n\n\t\t\t\t\n\n\t\t\/\/\tSystem.out.println(check(0));\n\n\t\t\/\/\t\t\ttt=scan.nextInt();\n\n\t\t\t\/\/\tscan=new FastScanner(\"clumsy.in\");\n\n\t\t\t\t\/\/out=new PrintWriter(\"clumsy.out\");\n\n\n\n\t\t\t\touter:while(tt-->0)\n\n\t\t\t\t\t{\n\nlong H=scan.nextLong();\n\nlong TH=H;\n\n\t\t\t\t\t\t n=scan.nextInt();\n\n\t\t\t\t\t\t long arr[]=new long[n];\n\n\t\t\t\t\t\t MIN=new long[n];\n\n\t\t\t\t\t\t PS=new long[n];\n\n\t\t\t\t\t\t for(int i=0;i=0)\n\n\t\t\t\t\t\t {\n\n\t\t\t\t\t\t \tout.println(-1);\n\n\t\t\t\t\t\t \tout.close();\n\n\t\t\t\t\t\t \treturn;\n\n\t\t\t\t\t\t }\n\n\t\t\t\t\t\t long l=1,r=(long)1e18,ans=(long)1e18+5;\n\n\/\/out.println(PS[n-1]);\n\n\/\/out.println(H)\n\n\t\t\t\t\t\/\/out.println(check(4301,H));\n\n\t\t\t\t\t\tfor(int i=0;i '9'); c = getChar()) {\n\n\t\t\t\t\t\t\t\t if (c == '-') neg = true;\n\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t long res = 0;\n\n\t\t\t\t\t\t\t\t for (; c >= '0' && c <= '9'; c = getChar()) {\n\n\t\t\t\t\t\t\t\t res = (res << 3) + (res << 1) + c - '0';\n\n\t\t\t\t\t\t\t\t cnt *= 10;\n\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t return neg ? -res : res;\n\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t \n\n\t\t\t\t\t\t\t\t public double nextDouble() {\n\n\t\t\t\t\t\t\t\t double cur = nextLong();\n\n\t\t\t\t\t\t\t\t return c != '.' ? cur : cur + nextLong() \/ cnt;\n\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t \n\n\t\t\t\t\t\t\t\t public double[] nextDoubles(int N) {\n\n\t\t\t\t\t\t\t\t double[] res = new double[N];\n\n\t\t\t\t\t\t\t\t for (int i = 0; i < N; i++) {\n\n\t\t\t\t\t\t\t\t res[i] = nextDouble();\n\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t return res;\n\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t \n\n\t\t\t\t\t\t\t\t public String next() {\n\n\t\t\t\t\t\t\t\t StringBuilder res = new StringBuilder();\n\n\t\t\t\t\t\t\t\t while (c <= 32) c = getChar();\n\n\t\t\t\t\t\t\t\t while (c > 32) {\n\n\t\t\t\t\t\t\t\t res.append(c);\n\n\t\t\t\t\t\t\t\t c = getChar();\n\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t return res.toString();\n\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t \n\n\t\t\t\t\t\t\t\t public String nextLine() {\n\n\t\t\t\t\t\t\t\t StringBuilder res = new StringBuilder();\n\n\t\t\t\t\t\t\t\t while (c <= 32) c = getChar();\n\n\t\t\t\t\t\t\t\t while (c != '\\n') {\n\n\t\t\t\t\t\t\t\t res.append(c);\n\n\t\t\t\t\t\t\t\t c = getChar();\n\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t return res.toString();\n\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t \n\n\t\t\t\t\t\t\t\t public boolean hasNext() {\n\n\t\t\t\t\t\t\t\t if (c > 32) return true;\n\n\t\t\t\t\t\t\t\t while (true) {\n\n\t\t\t\t\t\t\t\t c = getChar();\n\n\t\t\t\t\t\t\t\t if (c == NC) return false;\n\n\t\t\t\t\t\t\t\t else if (c > 32) return true;\n\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t\t\t\t\t\t static class Pair implements Comparable{\n\n\t\t\t\t\t\t\t\t\t\t public long x, y,z;\n\n\t\t\t\t\t\t\t\t\t\t public Pair(long x1, long y1,long z1) {\n\n\t\t\t\t\t\t\t\t\t\t x=x1;\n\n\t\t\t\t\t\t\t\t\t\t y=y1;\n\n\t\t\t\t\t\t\t\t\t\t z=z1;\n\n\t\t\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t\t\t public Pair(long x1, long y1) {\n\n\t\t\t\t\t\t\t\t\t\t x=x1;\n\n\t\t\t\t\t\t\t\t\t\t y=y1;\n\n\t\t\t\t\t\t\t\t\t\t \n\n\t\t\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t\t\t \n\n\t\t\t\t\t\t\t\t\t\t @Override\n\n\t\t\t\t\t\t\t\t\t\t public int hashCode() {\n\n\t\t\t\t\t\t\t\t\t\t return (int)(x + 31 * y);\n\n\t\t\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t\t\t public String toString() {\n\n\t\t\t\t\t\t\t\t\t\t return x + \" \" + y+\" \"+z;\n\n\t\t\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t\t\t @Override\n\n\t\t\t\t\t\t\t\t\t\t public boolean equals(Object o){\n\n\t\t\t\t\t\t\t\t\t\t if (o == this) return true;\n\n\t\t\t\t\t\t\t\t\t\t if (o.getClass() != getClass()) return false;\n\n\t\t\t\t\t\t\t\t\t\t Pair t = (Pair)o;\n\n\t\t\t\t\t\t\t\t\t\t return t.x == x && t.y == y&&t.z==z;\n\n\t\t\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t\t\t public int compareTo(Pair o)\n\n\t\t\t\t\t\t\t\t\t\t {\n\n\t\t\t\t\t\t\t\t\t\t \t\n\n\t\t\t\t\t\t\t\t\t\treturn (int)(o.x-x);\n\n\t\t\t\t\t\t\t\t\t\t \n\n\t\t\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t\t\t \n\n\t\t\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t \n\n\t\t\t\t\t\t\t\t\t\t \n\n\n\n\t\t\t\t\t\t\t\t\t\t \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.util.*;\n\nimport java.io.*;\n\npublic class Main {\n\n\t\tstatic long mod = 1000000007;\n\n\t\tstatic PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));\n\n\t\tpublic static void main(String[] args) throws IOException {\n\n\t\t\tFastReader sc = new FastReader();\n\n\t\t\t\t\tint n = sc.nextInt();\n\n\t\t\t\t\tchar arr[] = sc.next().toCharArray();\n\n\t\t\t\t\tint fst = 0;\n\n\t\t\t\t\tint scnd = 0;\n\n\t\t\t\t\tfor( int i = 0 ;i < n; i++) {\n\n\t\t\t\t\t\tif( arr[i] == '(') {\n\n\t\t\t\t\t\t\tfst++;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telse {\n\n\t\t\t\t\t\t\tscnd++;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif( fst!= scnd) {\n\n\t\t\t\t\t\tout.println(-1);\n\n\t\t\t\t\t}\n\n\t\t\t\t\telse {\n\n\t\t\t\t\t\tfst = 0;\n\n\t\t\t\t\t\tscnd = 0;\n\n\t\t\t\t\t\tint cost = 0;\n\n\t\t\t\t\t\tfor( int i =0 ;i< n;i++) {\n\n\t\t\t\t\t\t\tif( arr[i] == '(') {\n\n\t\t\t\t\t\t\t\tfst++;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\telse {\n\n\t\t\t\t\t\t\t\tscnd++;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif( scnd > fst) {\n\n\t\t\t\t\t\t\t\tint len = 1;\n\n\t\t\t\t\t\t\t\tint count = 1;\n\n\t\t\t\t\t\t\t\twhile( i < n-1 && arr[i+1] == ')') {\n\n\t\t\t\t\t\t\t\t\ti++;\n\n\t\t\t\t\t\t\t\t\tlen++;\n\n\t\t\t\t\t\t\t\t\tcount++;\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\twhile( count!= 0) {\n\n\t\t\t\t\t\t\t\t\ti++;\n\n\t\t\t\t\t\t\t\t\tlen++;\n\n\t\t\t\t\t\t\t\t\tif( arr[i] == ')') {\n\n\t\t\t\t\t\t\t\t\t\tcount++;\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\telse {\n\n\t\t\t\t\t\t\t\t\t\tcount--;\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tcost+=len;\n\n\t\t\t\t\t\t\t\tfst = scnd;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tout.println(cost);\n\n\t\t\t\t\t}\n\n\t\t\t\tout.flush();\n\n\t\t}\n\n\n\n\t\tpublic static int[] nextLargerElement(int[] arr, int n)\t{ \n\n\t\t\tStack stack = new Stack<>();\n\n\t\t\tint rtrn[] = new int[n];\n\n\t\t\trtrn[n-1] = -1;\n\n\t stack.push( n-1);\n\n\t for( int i = n-2 ;i >= 0 ; i--){\n\n\t int temp = arr[i];\n\n\t int lol = -1;\n\n\t while( !stack.isEmpty() && arr[stack.peek()] <= temp){\n\n\t \tif(arr[stack.peek()] == temp ) {\n\n\t \t\tlol = stack.peek();\n\n\t \t}\n\n\t stack.pop();\n\n\t }\n\n\t if( stack.isEmpty()){\n\n\t \tif( lol != -1) {\n\n\t \t\trtrn[i] = lol;\n\n\t \t}\n\n\t \telse {\n\n\t \t\trtrn[i] = -1;\n\n\t \t}\n\n\t }\n\n\t else{\n\n\t \trtrn[i] = stack.peek();\n\n\t }\n\n\t stack.push( i);\n\n\t }\n\n\t return rtrn;\n\n\t\t}\n\n\t\t\n\n\t\tstatic int gcd(int a, int b)\n\n\t\t{\n\n\t\t\tif (a == 0)\n\n\t\t\t\treturn b;\n\n\t\t\treturn gcd(b % a, a);\n\n\t\t}\n\n\t\t\n\n\t\t\t \n\n\t\t static int lcm(int a, int b)\n\n\t\t {\n\n\t\t\t return (a \/ gcd(a, b)) * b;\n\n\t\t }\n\n\t \n\n\t\t static HashMap primefactor( long n){\n\n\t\t\t HashMap hm = new HashMap<>();\n\n\t\t\t long temp = 0;\n\n\t\t\t while( n%2 == 0) {\n\n\t\t\t\t temp++;\n\n\t\t\t\t n\/=2;\n\n\t\t\t }\t\n\n\t\t\t if( temp!= 0) {\n\n\t\t\t\t hm.put( 2L, temp);\n\n\t\t\t }\n\n\t\t\t long c = (long)Math.sqrt(n);\n\n\t\t\t for( long i = 3 ; i <= c ; i+=2) {\n\n\t\t\t\t temp = 0;\n\n\t\t\t\t while( n% i == 0) {\n\n\t\t\t\t\t temp++;\n\n\t\t\t\t\t n\/=i;\n\n\t\t\t\t }\n\n\t\t\t\t if( temp!= 0) {\n\n\t\t\t\t\t hm.put( i, temp);\n\n\t\t\t\t }\n\n\t \t\t }\n\n\t \t\t if( n!= 1) {\n\n\t \t\t\t hm.put( n , 1L);\n\n\t \t\t }\n\n\t \t\t return hm;\t\n\n\t\t }\n\n\t \n\n\t\t static class FastReader {\n\n\t\t\t BufferedReader br;\n\n\t\t\t StringTokenizer st;\n\n\t\t \n\n\t\t\t public FastReader()\n\n\t\t\t {\n\n\t\t\t\t br = new BufferedReader(new InputStreamReader(System.in));\n\n\t\t\t }\n\n\t\t \n\n\t\t\t String next()\n\n\t\t\t {\n\n\t\t\t\t while (st == null || !st.hasMoreElements()) {\n\n\t\t\t\t\t try {\n\n\t\t\t\t\t\t st = new StringTokenizer(br.readLine());\n\n\t\t\t\t\t }\n\n\t\t\t\t\t catch (IOException e) {\n\n\t\t\t\t\t\t e.printStackTrace();\n\n\t\t\t\t\t }\n\n\t\t\t\t }\n\n\t\t\t\t return st.nextToken();\n\n\t\t\t }\n\n\t\t \n\n\t\t\t int nextInt() { return Integer.parseInt(next()); }\n\n\t\t\t \n\n\t\t\t long nextLong() { return Long.parseLong(next()); }\n\n\t\t\t \n\n\t\t\t double nextDouble()\n\n\t\t\t {\n\n\t\t\t\t return Double.parseDouble(next());\n\n\t\t\t }\t\n\n\t\t \n\n\t\t\t String nextLine()\n\n\t\t\t {\n\n\t\t\t\t String str = \"\";\n\n\t\t\t\t try {\n\n\t\t\t\t\t str = br.readLine();\n\n\t\t\t\t }\n\n\t\t\t\t catch (IOException e) {\n\n\t\t\t\t\t e.printStackTrace();\n\n\t\t\t\t }\n\n\t\t\t\t return str;\n\n\t\t\t }\n\n\t\t }\t\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 = Reader.nextInt();\n\n int h = Reader.nextInt();\n\n int l = Reader.nextInt();\n\n int r = Reader.nextInt();\n\n int [] arr = new int[n];\n\n int i = 0;\n\n while ( i < n){\n\n arr[i] = Reader.nextInt();\n\n i++;\n\n }\n\n output.write(answer(arr,n,h,l,r)+\"\\n\");\n\n t--;\n\n }\n\n output.flush();\n\n }\n\n\n\n private static int answer(int [] arr,int n,int h,int l,int r){\n\n int [][] dp = new int[n][h];\n\n boolean [][] dp2 = new boolean[n][h];\n\n int i = 0;\n\n int j = 0;\n\n while ( j < h){\n\n if ( j == arr[i] || (j == arr[i]-1)) {\n\n dp2[0][j] = true;\n\n if ( l <= j && j <= r){\n\n dp[0][j] = 1;\n\n }\n\n }\n\n j++;\n\n }\n\n i = 1;\n\n while ( i < n){\n\n j = 0;\n\n while ( j < h){\n\n if ( dp2[i-1][j]){\n\n int next = ( j + arr[i])%h;\n\n int next2 = (j+(arr[i]-1))%h;\n\n dp2[i][next] = true;\n\n dp2[i][next2] = true;\n\n if ( l <= next && r >= next){\n\n dp[i][next] = (int)max(dp[i][next],1+dp[i-1][j]);\n\n }\n\n else{\n\n dp[i][next] = (int)max(dp[i][next],dp[i-1][j]);\n\n }\n\n if ( l <= next2 && r >= next2){\n\n dp[i][next2] = (int)max(dp[i][next2],1+dp[i-1][j]);\n\n }\n\n else{\n\n dp[i][next2] = (int)max(dp[i][next2],dp[i-1][j]);\n\n }\n\n }\n\n j++;\n\n }\n\n i++;\n\n }\n\n j = 0;\n\n int ans = 0;\n\n while ( j < h){\n\n if (dp[n-1][j] > ans){\n\n ans = dp[n-1][j];\n\n }\n\n j++;\n\n }\n\n return ans;\n\n }\n\n private static boolean knapsack01(ArrayList arr,int size){\n\n boolean [][] dp = new boolean[arr.size()][size+1];\n\n int i = 0;\n\n int j = 0;\n\n while ( i < arr.size() ){\n\n dp[i][0] = true;\n\n i++;\n\n }\n\n i = 0;\n\n while ( j <= size){\n\n if ( j == arr.get(0)){\n\n dp[0][j] = true;\n\n }\n\n j++;\n\n }\n\n i = 1;\n\n while ( i < arr.size()){\n\n j = 1;\n\n while ( j <= size){\n\n dp[i][j] = dp[i-1][j];\n\n if ( j >= arr.get(i)){\n\n dp[i][j] = (dp[i][j] || dp[i-1][j-arr.get(i)]);\n\n }\n\n j++;\n\n }\n\n i++;\n\n }\n\n return dp[arr.size()-1][size];\n\n }\n\n\n\n public static void primeFactorisation(long n,HashMap map){\n\n long i = 2;\n\n while ( n%i == 0){\n\n if ( map.containsKey(i)){\n\n map.put(i,map.get(i)+1);\n\n }\n\n else{\n\n map.put(i,1);\n\n }\n\n n\/=i;\n\n }\n\n i = 3;\n\n long last = (long)Math.pow(n,0.5);\n\n while ( i <= last){\n\n while ( n%i == 0){\n\n if ( map.containsKey(i)){\n\n map.put(i,map.get(i)+1);\n\n }\n\n else{\n\n map.put(i,1);\n\n }\n\n n\/=i;\n\n }\n\n i++;\n\n }\n\n if ( n > 2){\n\n map.put(n,1);\n\n }\n\n }\n\n public static boolean prime(int n){\n\n int i = 2;\n\n int r = (int)Math.pow(n,0.5);\n\n boolean ans = true;\n\n while ( i<=r){\n\n if ( n%i == 0){\n\n ans = false;\n\n break;\n\n }\n\n i++;\n\n }\n\n return ans;\n\n }\n\n public static long log2(long N)\n\n {\n\n long result = (long)(Math.log(N) \/ Math.log(2));\n\n return result;\n\n }\n\n private static int bs(int low,int high,int [] array,long find){\n\n if ( low <= high ){\n\n int mid = low + (high-low)\/2;\n\n if ( array[mid] > find){\n\n high = mid -1;\n\n return bs(low,high,array,find);\n\n }\n\n else if ( array[mid] < find){\n\n low = mid+1;\n\n return bs(low,high,array,find);\n\n }\n\n return mid;\n\n }\n\n return -1;\n\n }\n\n\n\n private static long max(long a, long b) {\n\n return Math.max(a,b);\n\n }\n\n\n\n private static long min(long a,long b){\n\n return Math.min(a,b);\n\n }\n\n\n\n public static long modularExponentiation(long a,long b,long mod){\n\n if ( b == 1){\n\n return a;\n\n }\n\n else{\n\n long ans = modularExponentiation(a,b\/2,mod)%mod;\n\n if ( b%2 == 1){\n\n return (a*((ans*ans)%mod))%mod;\n\n }\n\n\n\n return ((ans*ans)%mod);\n\n }\n\n }\n\n\n\n public static long sum(long n){\n\n return (n*(n+1))\/2;\n\n }\n\n public static long abs(long a){\n\n return a < 0 ? (-1*a) : a;\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 else{\n\n return gcd(b%a,a);\n\n }\n\n }\n\n\n\n\n\n}\n\n\n\n\n\n\n\nclass DComparator implements Comparator{\n\n @Override\n\n public int compare(Integer o1, Integer o2) {\n\n if ( o2 > o1){\n\n return 1;\n\n }\n\n else if ( o2 < o1){\n\n return -1;\n\n }\n\n else{\n\n return 0;\n\n }\n\n }\n\n}\n\n\n\nclass NodeComparator implements Comparator{\n\n @Override\n\n public int compare(Node o1,Node o2){\n\n if ( o2.count < o1.count){\n\n return 1;\n\n }\n\n else{\n\n return -1;\n\n }\n\n }\n\n}\n\n\n\nclass Node{\n\n int value;\n\n int count;\n\n Node( int V,int C ){\n\n value = V;\n\n count = C;\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\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 static String next() throws IOException {\n\n while ( ! tokenizer.hasMoreTokens() ) {\n\n\n\n tokenizer = new StringTokenizer(\n\n reader.readLine() );\n\n }\n\n return tokenizer.nextToken();\n\n }\n\n\n\n static int nextInt() throws IOException {\n\n return Integer.parseInt( next() );\n\n }\n\n\n\n static double nextDouble() throws IOException {\n\n return Double.parseDouble( next() );\n\n }\n\n\n\n static long nextLong() throws IOException{\n\n return Long.parseLong(next());\n\n }\n\n}\n\n\n\nclass SegTree{\n\n int [] min;\n\n int [] max;\n\n\n\n SegTree(int s){\n\n min = new int[s];\n\n max = new int[s];\n\n }\n\n\n\n public void build(int [] arr, int v,int l,int r){\n\n if ( l == r){\n\n min[v] = arr[l];\n\n max[v] = arr[r];\n\n }\n\n else{\n\n int mid = l + (r-l)\/2;\n\n build(arr,2*v+1,l,mid);\n\n build(arr,2*v+2,mid+1,r);\n\n min[v] = min[2*v+1];\n\n max[v] = max[2*v+1];\n\n if ( min[v]> min[2*v+2]){\n\n min[v] = min[2*v+2];\n\n }\n\n if ( max[v] < max[2*v+2]){\n\n max[v] = max[2*v+2];\n\n }\n\n }\n\n }\n\n\n\n public int findMin(int v,int l,int r,int x,int y){\n\n if ( x > r || y < l){\n\n return Integer.MAX_VALUE;\n\n }\n\n else if ( x <= l && r <= y){\n\n return min[v];\n\n }\n\n else{\n\n int mid = l + (r-l)\/2;\n\n int a = findMin(2*v+1,l,mid,x,y);\n\n int b = findMin(2*v+2,mid+1,r,x,y);\n\n return a < b ? a: b;\n\n }\n\n }\n\n\n\n public int findMax(int v,int l,int r,int x,int y){\n\n if ( x > r || y < l){\n\n return Integer.MIN_VALUE;\n\n }\n\n else if ( x <= l && r <= y){\n\n return max[v];\n\n }\n\n else{\n\n int mid = l + (r-l)\/2;\n\n int a = findMax(2*v+1,l,mid,x,y);\n\n int b = findMax(2*v+2,mid+1,r,x,y);\n\n return a < b ? b: a;\n\n }\n\n }\n\n\n\n\n\n}","language":"java"} +{"contest_id":"1322","problem_id":"B","statement":"B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one\u00a0\u2014 xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)\u2295(a1+a3)\u2295\u2026\u2295(a1+an)\u2295(a2+a3)\u2295\u2026\u2295(a2+an)\u2026\u2295(an\u22121+an)(a1+a2)\u2295(a1+a3)\u2295\u2026\u2295(a1+an)\u2295(a2+a3)\u2295\u2026\u2295(a2+an)\u2026\u2295(an\u22121+an)Here x\u2295yx\u2295y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https:\/\/en.wikipedia.org\/wiki\/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2\u2264n\u22644000002\u2264n\u2264400000)\u00a0\u2014 the number of integers in the array.The second line contains integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641071\u2264ai\u2264107).OutputPrint a single integer\u00a0\u2014 xor of all pairwise sums of integers in the given array.ExamplesInputCopy2\n1 2\nOutputCopy3InputCopy3\n1 2 3\nOutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112\u22951002\u22951012=01020112\u22951002\u22951012=0102, thus the answer is 2.\u2295\u2295 is the bitwise xor operation. To define x\u2295yx\u2295y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012\u229500112=0110201012\u229500112=01102.","tags":["binary search","bitmasks","constructive algorithms","data structures","math","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.PrintStream;\nimport java.util.Arrays;\nimport java.io.BufferedWriter;\nimport java.io.Writer;\nimport java.io.OutputStreamWriter;\nimport java.util.InputMismatchException;\nimport java.util.Random;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n\/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n *\n * @author Rustam Musin (t.me\/musin_acm)\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 BPodarok solver = new BPodarok();\n solver.solve(1, in, out);\n out.close();\n }\n\n static class BPodarok {\n Random rnd = new Random(239);\n\n public void solve(int testNumber, InputReader in, OutputWriter out) {\n if (false) {\n test3();\n }\n int n = in.readInt();\n int[] a = in.readIntArray(n);\n\/\/ out.print(naive(a));\n out.print(newSolve(a));\n }\n\n int newSolve(int[] a) {\n int res = 0;\n for (int b = 0; b < 30; b++) {\n if (newSolve(a, b) % 2 == 1) {\n res |= 1 << b;\n }\n }\n return res;\n }\n\n long newSolve(int[] a, int bit) {\n int[] b = new int[a.length];\n for (int i = 0; i < a.length; i++) {\n b[i] = a[i] % (1 << (bit + 1));\n }\n Arrays.sort(b);\n int L1 = 1 << bit;\n int R1 = (L1 << 1) - 1;\n int L2 = (L1 << 1) | L1;\n int R2 = (L1 << 1) | R1;\n long count = 0;\n for (int x : b) {\n count += getCount(b, L1 - x, R1 - x);\n count += getCount(b, L2 - x, R2 - x);\n if (inside(L1 - x, R1 - x, x)) {\n count--;\n }\n if (inside(L2 - x, R2 - x, x)) {\n count--;\n }\n }\n return count >> 1;\n }\n\n boolean inside(int l, int r, int x) {\n return l <= x && x <= r;\n }\n\n int getCount(int[] a, int l, int r) {\n return getCount(a, r) - getCount(a, l - 1);\n }\n\n int getCount(int[] a, int x) {\n int l = -1;\n int r = a.length;\n while (r - l > 1) {\n int m = l + r >> 1;\n if (a[m] <= x) {\n l = m;\n } else {\n r = m;\n }\n }\n return l;\n }\n\n int naive(int[] a) {\n int res = 0;\n for (int i = 0; i < a.length; i++) {\n for (int j = i + 1; j < a.length; j++) {\n res ^= a[i] + a[j];\n }\n }\n return res;\n }\n\n void test3() {\n for (int t = 0; ; t++) {\n int n = 10;\n int m = 5;\n int[] a = genArray(n, m);\n int naive = naive(a);\n int sol = newSolve(a);\n if (naive != sol) {\n System.err.println(\"FF\");\n naive = naive(a);\n sol = newSolve(a);\n }\n }\n }\n\n int[] genArray(int n, int m) {\n int[] a = new int[n];\n for (int i = 0; i < n; i++) {\n a[i] = rnd.nextInt(m);\n }\n return a;\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 print(int i) {\n writer.print(i);\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[] readIntArray(int size) {\n int[] array = new int[size];\n for (int i = 0; i < size; i++) {\n array[i] = readInt();\n }\n return array;\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 readInt() {\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 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\n","language":"java"} +{"contest_id":"1287","problem_id":"B","statement":"B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game \"Set\" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature \u2014 color, number, shape, and shading \u2014 the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called \"Hyperset\". In her game, there are nn cards with kk features, each feature has three possible values: \"S\", \"E\", or \"T\". The original \"Set\" game can be viewed as \"Hyperset\" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1\u2264n\u226415001\u2264n\u22641500, 1\u2264k\u2264301\u2264k\u226430)\u00a0\u2014 number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters \"S\", \"E\", \"T\". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer\u00a0\u2014 the number of ways to choose three cards that form a set.ExamplesInputCopy3 3\nSET\nETS\nTSE\nOutputCopy1InputCopy3 4\nSETE\nETSE\nTSES\nOutputCopy0InputCopy5 4\nSETT\nTEST\nEEET\nESTE\nSTES\nOutputCopy2NoteIn the third example test; these two triples of cards are sets: \"SETT\"; \"TEST\"; \"EEET\" \"TEST\"; \"ESTE\", \"STES\" ","tags":["brute force","data structures","implementation"],"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\npublic class Codeforces {\n\t\/\/ static int mod = 998244353;\n\tstatic int mod = 1000000007;\n\n\tpublic static void main(String[] args) {\n\t\tFastReader fastReader = new FastReader();\n\t\tPrintWriter out = new PrintWriter(System.out);\n\t\tint t = 1;\n\n\t\t\/*\n\t\t * n = 1500 , k = 30;\n\t\t * \n\t\t * \n\t\t *\/\n\t\twhile (t-- > 0) {\n\t\t\tint n = fastReader.nextInt();\n\t\t\tint k = fastReader.nextInt();\n\t\t\tHashMap map = new HashMap<>();\n\t\t\tString arr[] = new String[n];\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tString cur = fastReader.nextLine();\n\t\t\t\tarr[i] = cur;\n\t\t\t\tmap.put(cur, map.getOrDefault(cur, 0) + 1);\n\t\t\t}\n\t\t\tlong ans = 0;\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tfor (int j = i + 1; j < n; j++) {\n\t\t\t\t\tchar cur[] = new char[k];\n\t\t\t\t\tfor (int node = 0; node < k; node++) {\n\t\t\t\t\t\tif (arr[i].charAt(node) == arr[j].charAt(node)) {\n\t\t\t\t\t\t\tcur[node] = arr[i].charAt(node);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (arr[i].charAt(node) != 'T' && arr[j].charAt(node) != 'T') {\n\t\t\t\t\t\t\t\tcur[node] = 'T';\n\t\t\t\t\t\t\t} else if (arr[i].charAt(node) != 'E' && arr[j].charAt(node) != 'E') {\n\t\t\t\t\t\t\t\tcur[node] = 'E';\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcur[node] = 'S';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t\tString sr_cur = String.valueOf(cur);\n\t\t\t\t\t\/\/ out.println(sr_cur);\n\t\t\t\t\tif (map.containsKey(sr_cur)) {\n\t\t\t\t\t\tans += map.get(sr_cur);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tans \/= 3;\n\t\t\tout.println(ans);\n\t\t}\n\t\tout.close();\n\t}\n\n\t\/\/ constants\n\tstatic final int IBIG = 1000000007;\n\tstatic final int IMAX = 2147483647;\n\tstatic final long LMAX = 9223372036854775807L;\n\tstatic Random __r = new Random();\n\n\t\/\/ math util\n\tstatic int minof(int a, int b, int c) {\n\t\treturn min(a, min(b, c));\n\t}\n\n\tstatic int minof(int... x) {\n\t\tif (x.length == 1)\n\t\t\treturn x[0];\n\t\tif (x.length == 2)\n\t\t\treturn min(x[0], x[1]);\n\t\tif (x.length == 3)\n\t\t\treturn min(x[0], min(x[1], x[2]));\n\t\tint min = x[0];\n\t\tfor (int i = 1; i < x.length; ++i)\n\t\t\tif (x[i] < min)\n\t\t\t\tmin = x[i];\n\t\treturn min;\n\t}\n\n\tstatic long minof(long a, long b, long c) {\n\t\treturn min(a, min(b, c));\n\t}\n\n\tstatic long minof(long... x) {\n\t\tif (x.length == 1)\n\t\t\treturn x[0];\n\t\tif (x.length == 2)\n\t\t\treturn min(x[0], x[1]);\n\t\tif (x.length == 3)\n\t\t\treturn min(x[0], min(x[1], x[2]));\n\t\tlong min = x[0];\n\t\tfor (int i = 1; i < x.length; ++i)\n\t\t\tif (x[i] < min)\n\t\t\t\tmin = x[i];\n\t\treturn min;\n\t}\n\n\tstatic int maxof(int a, int b, int c) {\n\t\treturn max(a, max(b, c));\n\t}\n\n\tstatic int maxof(int... x) {\n\t\tif (x.length == 1)\n\t\t\treturn x[0];\n\t\tif (x.length == 2)\n\t\t\treturn max(x[0], x[1]);\n\t\tif (x.length == 3)\n\t\t\treturn max(x[0], max(x[1], x[2]));\n\t\tint max = x[0];\n\t\tfor (int i = 1; i < x.length; ++i)\n\t\t\tif (x[i] > max)\n\t\t\t\tmax = x[i];\n\t\treturn max;\n\t}\n\n\tstatic long maxof(long a, long b, long c) {\n\t\treturn max(a, max(b, c));\n\t}\n\n\tstatic long maxof(long... x) {\n\t\tif (x.length == 1)\n\t\t\treturn x[0];\n\t\tif (x.length == 2)\n\t\t\treturn max(x[0], x[1]);\n\t\tif (x.length == 3)\n\t\t\treturn max(x[0], max(x[1], x[2]));\n\t\tlong max = x[0];\n\t\tfor (int i = 1; i < x.length; ++i)\n\t\t\tif (x[i] > max)\n\t\t\t\tmax = x[i];\n\t\treturn max;\n\t}\n\n\tstatic int powi(int a, int b) {\n\t\tif (a == 0)\n\t\t\treturn 0;\n\t\tint ans = 1;\n\t\twhile (b > 0) {\n\t\t\tif ((b & 1) > 0)\n\t\t\t\tans *= a;\n\t\t\ta *= a;\n\t\t\tb >>= 1;\n\t\t}\n\t\treturn ans;\n\t}\n\n\tstatic long powl(long a, int b) {\n\t\tif (a == 0)\n\t\t\treturn 0;\n\t\tlong ans = 1;\n\t\twhile (b > 0) {\n\t\t\tif ((b & 1) > 0)\n\t\t\t\tans *= a;\n\t\t\ta *= a;\n\t\t\tb >>= 1;\n\t\t}\n\t\treturn ans;\n\t}\n\n\tstatic int fli(double d) {\n\t\treturn (int) d;\n\t}\n\n\tstatic int cei(double d) {\n\t\treturn (int) ceil(d);\n\t}\n\n\tstatic long fll(double d) {\n\t\treturn (long) d;\n\t}\n\n\tstatic long cel(double d) {\n\t\treturn (long) ceil(d);\n\t}\n\n\tstatic int gcd(int a, int b) {\n\t\treturn b == 0 ? a : gcd(b, a % b);\n\t}\n\n\tstatic int lcm(int a, int b) {\n\t\treturn (a \/ gcd(a, b)) * b;\n\t}\n\n\tstatic long gcd(long a, long b) {\n\t\treturn b == 0 ? a : gcd(b, a % b);\n\t}\n\n\tstatic long lcm(long a, long b) {\n\t\treturn (a \/ gcd(a, b)) * b;\n\t}\n\n\tstatic int[] exgcd(int a, int b) {\n\t\tif (b == 0)\n\t\t\treturn new int[] { 1, 0 };\n\t\tint[] y = exgcd(b, a % b);\n\t\treturn new int[] { y[1], y[0] - y[1] * (a \/ b) };\n\t}\n\n\tstatic long[] exgcd(long a, long b) {\n\t\tif (b == 0)\n\t\t\treturn new long[] { 1, 0 };\n\t\tlong[] y = exgcd(b, a % b);\n\t\treturn new long[] { y[1], y[0] - y[1] * (a \/ b) };\n\t}\n\n\tstatic int randInt(int min, int max) {\n\t\treturn __r.nextInt(max - min + 1) + min;\n\t}\n\n\tstatic long mix(long x) {\n\t\tx += 0x9e3779b97f4a7c15L;\n\t\tx = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;\n\t\tx = (x ^ (x >> 27)) * 0x94d049bb133111ebL;\n\t\treturn x ^ (x >> 31);\n\t}\n\n\tpublic static boolean[] findPrimes(int limit) {\n\t\tassert limit >= 2;\n\n\t\tfinal boolean[] nonPrimes = new boolean[limit];\n\t\tnonPrimes[0] = true;\n\t\tnonPrimes[1] = true;\n\n\t\tint sqrt = (int) Math.sqrt(limit);\n\t\tfor (int i = 2; i <= sqrt; i++) {\n\t\t\tif (nonPrimes[i])\n\t\t\t\tcontinue;\n\t\t\tfor (int j = i; j < limit; j += i) {\n\t\t\t\tif (!nonPrimes[j] && i != j)\n\t\t\t\t\tnonPrimes[j] = true;\n\t\t\t}\n\t\t}\n\n\t\treturn nonPrimes;\n\t}\n\n\t\/\/ array util\n\tstatic void reverse(int[] a) {\n\t\tfor (int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {\n\t\t\tint swap = a[i];\n\t\t\ta[i] = a[n - i - 1];\n\t\t\ta[n - i - 1] = swap;\n\t\t}\n\t}\n\n\tstatic void reverse(long[] a) {\n\t\tfor (int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {\n\t\t\tlong swap = a[i];\n\t\t\ta[i] = a[n - i - 1];\n\t\t\ta[n - i - 1] = swap;\n\t\t}\n\t}\n\n\tstatic void reverse(double[] a) {\n\t\tfor (int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {\n\t\t\tdouble swap = a[i];\n\t\t\ta[i] = a[n - i - 1];\n\t\t\ta[n - i - 1] = swap;\n\t\t}\n\t}\n\n\tstatic void reverse(char[] a) {\n\t\tfor (int i = 0, n = a.length, half = n \/ 2; i < half; ++i) {\n\t\t\tchar swap = a[i];\n\t\t\ta[i] = a[n - i - 1];\n\t\t\ta[n - i - 1] = swap;\n\t\t}\n\t}\n\n\tstatic void shuffle(int[] a) {\n\t\tint n = a.length - 1;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint ind = randInt(i, n);\n\t\t\tint swap = a[i];\n\t\t\ta[i] = a[ind];\n\t\t\ta[ind] = swap;\n\t\t}\n\t}\n\n\tstatic void shuffle(long[] a) {\n\t\tint n = a.length - 1;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint ind = randInt(i, n);\n\t\t\tlong swap = a[i];\n\t\t\ta[i] = a[ind];\n\t\t\ta[ind] = swap;\n\t\t}\n\t}\n\n\tstatic void shuffle(double[] a) {\n\t\tint n = a.length - 1;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint ind = randInt(i, n);\n\t\t\tdouble swap = a[i];\n\t\t\ta[i] = a[ind];\n\t\t\ta[ind] = swap;\n\t\t}\n\t}\n\n\tstatic void rsort(int[] a) {\n\t\tshuffle(a);\n\t\tsort(a);\n\t}\n\n\tstatic void rsort(long[] a) {\n\t\tshuffle(a);\n\t\tsort(a);\n\t}\n\n\tstatic void rsort(double[] a) {\n\t\tshuffle(a);\n\t\tsort(a);\n\t}\n\n\tstatic int[] copy(int[] a) {\n\t\tint[] ans = new int[a.length];\n\t\tfor (int i = 0; i < a.length; ++i)\n\t\t\tans[i] = a[i];\n\t\treturn ans;\n\t}\n\n\tstatic long[] copy(long[] a) {\n\t\tlong[] ans = new long[a.length];\n\t\tfor (int i = 0; i < a.length; ++i)\n\t\t\tans[i] = a[i];\n\t\treturn ans;\n\t}\n\n\tstatic double[] copy(double[] a) {\n\t\tdouble[] ans = new double[a.length];\n\t\tfor (int i = 0; i < a.length; ++i)\n\t\t\tans[i] = a[i];\n\t\treturn ans;\n\t}\n\n\tstatic char[] copy(char[] a) {\n\t\tchar[] ans = new char[a.length];\n\t\tfor (int i = 0; i < a.length; ++i)\n\t\t\tans[i] = a[i];\n\t\treturn ans;\n\t}\n\n\tstatic class FastReader {\n\n\t\tBufferedReader br;\n\t\tStringTokenizer st;\n\n\t\tpublic FastReader() {\n\t\t\tbr = new BufferedReader(\n\t\t\t\t\tnew InputStreamReader(System.in));\n\t\t}\n\n\t\tString next() {\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\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn st.nextToken();\n\t\t}\n\n\t\tint nextInt() {\n\t\t\treturn Integer.parseInt(next());\n\t\t}\n\n\t\tint[] ria(int n) {\n\t\t\tint[] a = new int[n];\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\ta[i] = Integer.parseInt(next());\n\t\t\treturn a;\n\t\t}\n\n\t\tlong nextLong() {\n\t\t\treturn Long.parseLong(next());\n\t\t}\n\n\t\tlong[] rla(int n) {\n\t\t\tlong[] a = new long[n];\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\ta[i] = Long.parseLong(next());\n\t\t\treturn a;\n\t\t}\n\n\t\tdouble nextDouble() {\n\t\t\treturn Double.parseDouble(next());\n\t\t}\n\n\t\tString nextLine() {\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\te.printStackTrace();\n\t\t\t}\n\t\t\treturn str;\n\t\t}\n\t}\n}\n","language":"java"} +{"contest_id":"1311","problem_id":"E","statement":"E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.The only line of each test case contains two integers nn and dd (2\u2264n,d\u226450002\u2264n,d\u22645000) \u2014 the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (\u2211n\u22645000,\u2211d\u22645000\u2211n\u22645000,\u2211d\u22645000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print \"NO\" (without quotes) in the first line. Otherwise, print \"{YES}\" in the first line. Then print n\u22121n\u22121 integers p2,p3,\u2026,pnp2,p3,\u2026,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3\n5 7\n10 19\n10 18\nOutputCopyYES\n1 2 1 3 \nYES\n1 2 3 3 9 9 2 1 6 \nNO\nNotePictures corresponding to the first and the second test cases of the example:","tags":["brute force","constructive algorithms","trees"],"code":"import java.util.*;\n\nimport java.io.*;\n\nimport static java.lang.Math.*;\n\n\n\npublic class Main implements Runnable\n\n{\n\n boolean multiple = true;\n\n long MOD;\n\n\n\n @SuppressWarnings(\"Duplicates\")\n\n void solve() throws Exception\n\n {\n\n int n = sc.nextInt();\n\n int d = sc.nextInt();\n\n int N = n;\n\n int min = 0;\n\n\n\n for (int layer = 0; N > 0; layer++)\n\n {\n\n min += layer * min(N, 1 << layer);\n\n N -= 1 << layer;\n\n }\n\n\n\n if (min <= d && d <= (n * (n - 1)) \/ 2)\n\n {\n\n System.out.println(\"YES\");\n\n PriorityQueue[] layer = new PriorityQueue[n + 1];\n\n layer[0] = new PriorityQueue<>();\n\n layer[1] = new PriorityQueue<>();\n\n layer[1].add(new Node(null, 1));\n\n for (int i = 2; i <= n; i++)\n\n {\n\n layer[i] = new PriorityQueue<>();\n\n layer[i].add(new Node(layer[i - 1].peek(), i));\n\n }\n\n\n\n int current = n;\n\n int lowest = n;\n\n\n\n for (int sum = (n * (n - 1)) \/ 2; sum > d; sum--)\n\n {\n\n\/\/ System.out.println(current);\n\n Node next = layer[current].poll();\n\n Node newParent = layer[current - 2].poll();\n\n next.parent.children--;\n\n\/\/ System.out.println(newParent.children);\n\n newParent.children++;\n\n next.parent = newParent;\n\n layer[current - 2].add(newParent);\n\n layer[current - 1].add(next);\n\n\n\n if (layer[lowest].isEmpty()) lowest--;\n\n\n\n current--;\n\n if (current == 2 || layer[current - 2].peek().children == 2) current = lowest;\n\n }\n\n\n\n int[] ans = new int[n + 1];\n\n for (PriorityQueue pq : layer)\n\n while (!pq.isEmpty())\n\n {\n\n Node next = pq.poll();\n\n if (next.idx == 1) continue;\n\n ans[next.idx] = next.parent.idx;\n\n }\n\n\n\n for (int i = 2; i <= n; i++)\n\n System.out.print(ans[i] + \" \");\n\n System.out.println();\n\n }\n\n else\n\n System.out.println(\"NO\");\n\n }\n\n\n\n class Node implements Comparable\n\n {\n\n Node parent;\n\n int idx;\n\n int children = 1;\n\n\n\n Node(Node p, int i)\n\n {\n\n parent = p;\n\n idx = i;\n\n }\n\n\n\n @Override\n\n public int compareTo(Node o)\n\n {\n\n return children - o.children;\n\n }\n\n }\n\n\n\n long inv(long a, long b)\n\n {\n\n return 1 < a ? b - inv(b % a, a) * b \/ a : 1;\n\n }\n\n\n\n long gcd(long a, long b)\n\n {\n\n return a == 0 ? b : gcd(b % a, a);\n\n }\n\n\n\n long lcm(long a, long b) { return (a * b) \/ gcd(a , b); }\n\n\n\n class SegNode\n\n {\n\n int max;\n\n int L, R;\n\n SegNode left = null, right = null;\n\n\n\n int query(int queryL, int queryR)\n\n {\n\n if (queryL == L && queryR == R)\n\n return max;\n\n\n\n int leftAns = Integer.MIN_VALUE, rightAns = Integer.MIN_VALUE;\n\n if (left != null && queryL <= left.R)\n\n leftAns = left.query(queryL, min(queryR, left.R));\n\n if (right != null && queryR >= right.L)\n\n rightAns = right.query(max(queryL, right.L), queryR);\n\n\n\n return max(leftAns, rightAns);\n\n }\n\n\n\n SegNode(int[] arr, int l, int r)\n\n {\n\n L = l;\n\n R = r;\n\n max = arr[l];\n\n\n\n if (l == r) return;\n\n\n\n int mid = (l + r) \/ 2;\n\n left = new SegNode(arr, l, mid);\n\n right = new SegNode(arr, mid + 1, r);\n\n max = max(left.max, right.max);\n\n }\n\n }\n\n\n\n void print(long[] arr)\n\n {\n\n for (int i = 0; i < arr.length; i++)\n\n System.out.print(arr[i] + \" \");\n\n System.out.println();\n\n }\n\n\n\n @Override\n\n public void run()\n\n {\n\n try\n\n {\n\n in = new BufferedReader(new InputStreamReader(System.in));\n\n out = new PrintWriter(System.out);\n\n sc = new FastScanner(in);\n\n if (multiple)\n\n {\n\n int q = sc.nextInt();\n\n for (int i = 0; i < q; i++)\n\n solve();\n\n }\n\n else\n\n solve();\n\n }\n\n catch (Throwable uncaught)\n\n {\n\n Main.uncaught = uncaught;\n\n }\n\n finally\n\n {\n\n out.close();\n\n }\n\n }\n\n\n\n public static void main(String[] args) throws Throwable\n\n {\n\n Thread thread = new Thread(null, new Main(), \"\", (1 << 26));\n\n thread.start();\n\n thread.join();\n\n if (Main.uncaught != null) {\n\n throw Main.uncaught;\n\n }\n\n }\n\n\n\n static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out;\n\n}\n\n\n\nclass FastScanner\n\n{\n\n BufferedReader in;\n\n StringTokenizer st;\n\n\n\n public FastScanner(BufferedReader in)\n\n {\n\n this.in = in;\n\n }\n\n\n\n public String nextToken() throws Exception {\n\n while (st == null || !st.hasMoreTokens()) {\n\n st = new StringTokenizer(in.readLine());\n\n }\n\n return st.nextToken();\n\n }\n\n\n\n public int nextInt() throws Exception {\n\n return Integer.parseInt(nextToken());\n\n }\n\n\n\n public long nextLong() throws Exception {\n\n return Long.parseLong(nextToken());\n\n }\n\n\n\n public double nextDouble() throws Exception {\n\n return Double.parseDouble(nextToken());\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":"import java.io.*;\nimport java.lang.reflect.Array;\nimport java.util.*;\nimport java.util.stream.IntStream;\nimport java.util.stream.Stream;\n\npublic class Main {\n\n\n public static void main(String[] args) {\n in = new MyScanner();\n out = new PrintWriter(new BufferedOutputStream(System.out));\n try {\n int t = in.nextInt(); while(t-- > 0) { solve(); out.println();}\n\/\/ solve();\n } finally {\n out.close();\n }\n return;\n }\n\n public static void solve() {\n int n = in.nextInt();\n int m = in.nextInt();\n int[] a = fillArray(n);\n int sum = Arrays.stream(a).sum();\n\n out.print(Math.min(m, sum));\n }\n\n\n\n \/\/-------------- Helper methods-------------------\n public static int[] fillArray(int n) {\n int[] array = new int[n];\n for(int i = 0; i < n; i++) {\n array[i] = in.nextInt();\n }\n return array;\n }\n\n public static char[] fillArray() {\n char[] array = in.next().toCharArray();\n return array;\n }\n\n \/\/-----------PrintWriter for faster output---------------------------------\n\n public static PrintWriter out;\n public static MyScanner in;\n\n \/\/-----------MyScanner class for faster input----------x\u00a7x\n public static class MyScanner {\n BufferedReader br;\n StringTokenizer st;\n\n public MyScanner() {\n br = new BufferedReader(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 }\n\n static void shuffleArray(int[] arr){\n int n = arr.length;\n Random rnd = new Random();\n for(int i=0; ikk\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":"import java.util.*;\n\nimport java.io.*;\n\n\n\npublic class A {\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 ArrayList> ans = new ArrayList<>();\n\n for (int i = 0; i < 2; i++) {\n\n ans.add(new ArrayList<>());\n\n }\n\n for (List cur : map.values()) {\n\n\/\/ List cur = x;\n\n\/\/ cur.sort((a, b) -> a[1] - b[1]);\n\n cur.sort(Comparator.comparingInt(a -> a[1]));\n\n\/\/ List temp = new ArrayList<>();\n\n int prev = 0;\n\n for (int[] y : cur) {\n\n if (y[0] > prev) {\n\n\/\/ temp.add(y);\n\n ans.get(1).add(y);\n\n prev = y[1];\n\n }\n\n }\n\n\/\/ if (temp.size() > ans.size()) {\n\n\/\/ ans = temp;\n\n\/\/ }\n\n if (ans.get(1).size() > ans.get(0).size()) {\n\n Collections.swap(ans, 0, 1);\n\n }\n\n ans.get(1).clear();\n\n }\n\n out.println(ans.get(0).size());\n\n for (int[] x : ans.get(0)) {\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 A().run();\n\n }\n\n\n\n}","language":"java"} +{"contest_id":"1284","problem_id":"D","statement":"D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai\u2264eaisai\u2264eai) and [sbi,ebi][sbi,ebi] (sbi\u2264ebisbi\u2264ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)\u2264min(y,v)max(x,u)\u2264min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1\u2264n\u22641000001\u2264n\u2264100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1\u2264sai,eai,sbi,ebi\u22641091\u2264sai,eai,sbi,ebi\u2264109, sai\u2264eai,sbi\u2264ebisai\u2264eai,sbi\u2264ebi).OutputPrint \"YES\" if Hyunuk will be happy. Print \"NO\" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2\n1 2 3 6\n3 4 7 8\nOutputCopyYES\nInputCopy3\n1 3 2 4\n4 5 6 7\n3 4 5 5\nOutputCopyNO\nInputCopy6\n1 5 2 9\n2 4 5 8\n3 6 7 11\n7 10 12 16\n8 11 13 17\n9 12 14 18\nOutputCopyYES\nNoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.","tags":["binary search","data structures","hashing","sortings"],"code":"import static java.lang.Integer.parseInt;\nimport static java.lang.Long.parseLong;\nimport static java.lang.System.exit;\nimport static java.lang.System.nanoTime;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.util.Random;\nimport java.util.StringTokenizer;\n\npublic class D {\n\n\tstatic void sortBy(int a[], int n, int v[]) {\n\t\tif (n == 0) {\n\t\t\treturn;\n\t\t}\n\t\tfor (int i = 1; i < n; i++) {\n\t\t\tint j = i;\n\t\t\tint ca = a[i];\n\t\t\tint cv = v[ca];\n\t\t\tdo {\n\t\t\t\tint nj = (j - 1) >> 1;\n\t\t\t\tint na = a[nj];\n\t\t\t\tif (cv <= v[na]) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ta[j] = na;\n\t\t\t\tj = nj;\n\t\t\t} while (j != 0);\n\t\t\ta[j] = ca;\n\t\t}\n\t\tint ca = a[0];\n\t\tfor (int i = n - 1; i > 0; i--) {\n\t\t\tint j = 0;\n\t\t\twhile ((j << 1) + 2 + Integer.MIN_VALUE < i + Integer.MIN_VALUE) {\n\t\t\t\tj <<= 1;\n\t\t\t\tj += (v[a[j + 2]] > v[a[j + 1]]) ? 2 : 1;\n\t\t\t}\n\t\t\tif ((j << 1) + 2 == i) {\n\t\t\t\tj = (j << 1) + 1;\n\t\t\t}\n\t\t\tint na = a[i];\n\t\t\ta[i] = ca;\n\t\t\tca = na;\n\t\t\tint cv = v[ca];\n\t\t\twhile (j != 0 && v[a[j]] < cv) {\n\t\t\t\tj = (j - 1) >> 1;\n\t\t\t}\n\t\t\twhile (j != 0) {\n\t\t\t\tna = a[j];\n\t\t\t\ta[j] = ca;\n\t\t\t\tca = na;\n\t\t\t\tj = (j - 1) >> 1;\n\t\t\t}\n\t\t}\n\t\ta[0] = ca;\n\t}\n\n\tstatic void solve() throws Exception {\n\t\tint n = scanInt();\n\t\tint pa[] = new int[2 * n], pb[] = new int[2 * n], idxa[] = new int[2 * n], idxb[] = new int[2 * n];\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tpa[2 * i] = 2 * scanInt();\n\t\t\tpa[2 * i + 1] = 2 * scanInt() + 1;\n\t\t\tpb[2 * i] = 2 * scanInt();\n\t\t\tpb[2 * i + 1] = 2 * scanInt() + 1;\n\t\t\tidxa[2 * i] = idxb[2 * i] = 2 * i;\n\t\t\tidxa[2 * i + 1] = idxb[2 * i + 1] = 2 * i + 1;\n\t\t}\n\t\tsortBy(idxa, 2 * n, pa);\n\t\tsortBy(idxb, 2 * n, pb);\n\t\tRandom rng = new Random(nanoTime());\n\t\tlong v[] = new long[n];\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tv[i] = rng.nextLong() | 1;\n\t\t}\n\t\tlong ans = 0, cur = 0;\n\t\tfor (int i: idxa) {\n\t\t\tif ((i & 1) == 0) {\n\t\t\t\tans += v[i >> 1] * cur;\n\t\t\t\tcur += v[i >> 1];\n\t\t\t} else {\n\t\t\t\tcur -= v[i >> 1];\n\t\t\t}\n\t\t}\n\t\tfor (int i: idxb) {\n\t\t\tif ((i & 1) == 0) {\n\t\t\t\tans -= v[i >> 1] * cur;\n\t\t\t\tcur += v[i >> 1];\n\t\t\t} else {\n\t\t\t\tcur -= v[i >> 1];\n\t\t\t}\n\t\t}\n\t\tout.print(ans == 0 ? \"YES\" : \"NO\");\n\t}\n\n\tstatic int scanInt() throws IOException {\n\t\treturn parseInt(scanString());\n\t}\n\n\tstatic long scanLong() throws IOException {\n\t\treturn parseLong(scanString());\n\t}\n\n\tstatic String scanString() throws IOException {\n\t\twhile (tok == null || !tok.hasMoreTokens()) {\n\t\t\ttok = new StringTokenizer(in.readLine());\n\t\t}\n\t\treturn tok.nextToken();\n\t}\n\n\tstatic BufferedReader in;\n\tstatic PrintWriter out;\n\tstatic StringTokenizer tok;\n\n\tpublic static void main(String[] args) {\n\t\ttry {\n\t\t\tin = new BufferedReader(new InputStreamReader(System.in));\n\t\t\tout = new PrintWriter(System.out);\n\t\t\tsolve();\n\t\t\tin.close();\n\t\t\tout.close();\n\t\t} catch (Throwable e) {\n\t\t\te.printStackTrace();\n\t\t\texit(1);\n\t\t}\n\t}\n}","language":"java"} +{"contest_id":"1287","problem_id":"A","statement":"A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters \"A\" and \"P\": \"A\" corresponds to an angry student \"P\" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt\u00a0\u2014 the number of groups of students (1\u2264t\u22641001\u2264t\u2264100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1\u2264ki\u22641001\u2264ki\u2264100)\u00a0\u2014 the number of students in the group, followed by a string sisi, consisting of kiki letters \"A\" and \"P\", which describes the ii-th group of students.OutputFor every group output single integer\u00a0\u2014 the last moment a student becomes angry.ExamplesInputCopy1\n4\nPPAP\nOutputCopy1\nInputCopy3\n12\nAPPAPPPAPPPP\n3\nAAP\n3\nPPA\nOutputCopy4\n1\n0\nNoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute\u00a0\u2014 AAPAAPPAAPPP after 22 minutes\u00a0\u2014 AAAAAAPAAAPP after 33 minutes\u00a0\u2014 AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.","tags":["greedy","implementation"],"code":"import java.io.*;\nimport java.lang.reflect.Array;\nimport java.util.*;\nimport java.util.stream.IntStream;\nimport java.util.stream.Stream;\n\npublic class Main {\n\n\n public static void main(String[] args) {\n in = new MyScanner();\n out = new PrintWriter(new BufferedOutputStream(System.out));\n try {\n int t = in.nextInt(); while(t-- > 0) { solve(); out.println();}\n\/\/ solve();\n } finally {\n out.close();\n }\n return;\n }\n\n public static void solve() {\n int n = in.nextInt();\n char[] s = fillArray();\n int max = 0;\n int lastAngry = -1;\n for(int i = 0; i < n; i++) {\n if(s[i] == 'A') {\n lastAngry = i;\n continue;\n }\n\n if(lastAngry == -1) {\n continue;\n }\n\n max = Math.max(max, i - lastAngry);\n }\n\n out.print(max);\n }\n\n\n \/\/-------------- Helper methods-------------------\n public static int[] fillArray(int n) {\n int[] array = new int[n];\n for(int i = 0; i < n; i++) {\n array[i] = in.nextInt();\n }\n return array;\n }\n\n public static char[] fillArray() {\n char[] array = in.next().toCharArray();\n return array;\n }\n\n \/\/-----------PrintWriter for faster output---------------------------------\n\n public static PrintWriter out;\n public static MyScanner in;\n\n \/\/-----------MyScanner class for faster input----------x\u00a7x\n public static class MyScanner {\n BufferedReader br;\n StringTokenizer st;\n\n public MyScanner() {\n br = new BufferedReader(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 }\n\n static void shuffleArray(int[] arr){\n int n = arr.length;\n Random rnd = new Random();\n for(int i=0; i 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= 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);\n\n\t \n\n\t }\n\n\t static long lcm(long a , long b) {\n\n\t\t return (a*b)\/gcd(a, b);\n\n\t }\n\n\t static int lcm(int a , int b) {\n\n\t\t return (int)((a*b)\/gcd(a, b));\n\n\t }\n\n\t static long power(long x, long y){\n\n\t\t if(y<0) return 0;\n\n\t\t long m = mod;\n\n\t if (y == 0) return 1; long p = power(x, y \/ 2) % 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; \/\/ factorial\n\n\t \t private long[] z1; \/\/ inverse factorial\n\n\t \t private long[] z2; \/\/ incerse number\n\n\t \t private long mod;\n\n\t \t public Combinations(long N , long mod) {\n\n\t \t\t this.mod = 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 z1[(int)n];\n\n\t \t }\n\n\t \t long ncr(long N, long R)\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 max(int... a ) {\n\n\t \t int max = a[0];\n\n\t \t for(int e:a) max = Math.max(max, e);\n\n\t \t return max;\n\n\t }\n\n\t static long max(long... a ) {\n\n\t \t long max = a[0];\n\n\t \t for(long e:a) max = Math.max(max, e);\n\n\t \t return max;\n\n\t }\n\n\t static int min(int... a ) {\n\n\t \t int min = a[0];\n\n\t \t for(int e:a) min = Math.min(e, min);\n\n\t \t return min;\n\n\t }\n\n\t static long min(long... a ) {\n\n\t \t long min = a[0];\n\n\t \t for(long e:a) min = Math.min(e, min);\n\n\t \t return min;\n\n\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] = gcd(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 gcd(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 MyScanner sc = new MyScanner(); \/\/ only in case of less memory\n\n\t static Reader sc = new Reader();\n\n\t static int TC;\n\n\t static StringBuilder sb = new StringBuilder();\n\n\t static PrintWriter out=new PrintWriter(System.out);\n\n\t public static void main(String args[]) throws IOException {\n\n\n\n\t\t int tc = 1;\n\n\t\t tc = sc.nextInt();\n\n\t\t\n\n\t\t TC = 0;\n\n\t\t for(int i = 1 ; i<=tc ; i++) {\n\n\t\t\t TC++;\n\n\/\/\t\t\t sb.append(\"Case #\" + i + \": \" );\t\/\/ During KickStart && HackerCup\n\n\t\t\t TEST_CASE();\n\n\t\t\t \n\n\t\t }\n\n\t\t System.out.print(sb);\n\n\t }\n\n\t static void TEST_CASE() throws IOException {\n\n\t\tlong n = sc.nextLong() , m = sc.nextLong();\n\n\t\tlong tot = sum(n);\n\n\t\tlong min = min(n , m);\n\n\t\tlong z = (n-m);\n\n\t\tif(z<=m+1) {\n\n\t\t\ttot -= z;\n\n\t\t\tsb.append(tot+\"\\n\");\n\n\t\t\treturn;\n\n\t\t}else {\n\n\t\t\tlong gaps = m+1;\n\n\t\t\tlong ele = z\/(m+1);\n\n\t\t\tlong ext = z%(m+1);\n\n\t\t\t\n\n\t\t\tlong g1 = m+1-ext;\n\n\t\t\tlong eleOfGap1 = ele;\n\n\t\t\tlong g2 = ext;\n\n\t\t\tlong eleOfGap2 = ele+1;\n\n\t\t\tlong sub1 = sum(eleOfGap1) * g1;\n\n\t\t\tlong sub2 = sum(eleOfGap2) * g2;\n\n\t\t\ttot -= sub1;\n\n\t\t\ttot -= sub2;\n\n\t\t\tsb.append(tot+\"\\n\");\n\n\t\t}\n\n\t }\n\n\t static long sum(long n) {\n\n\t\t long sum = 0 ;\n\n\t\t sum += n*(n+1);\n\n\t\t return sum\/2;\n\n\t }\n\n\t}\n\n\n\n\t\n\n\t\n\n\n\n\n\n\n\n\n\n\/*******************************************************************************************************************************************************\/\n\n\n\n\/** \n\n R -> 1 \n\n B -> 1\n\n k -> 2\n\n \n\n \n\n \n\n \n\n *\/\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 0) {\n\n\t\t\tint n = sc.nextInt();\n\n\n\n\t\t\tint[][] arr = new int[n][2];\n\n\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tarr[i][0] = sc.nextInt();\n\n\t\t\t\tarr[i][1] = sc.nextInt();\n\n\n\n\t\t\t}\n\n\n\n\t\t\tArrays.sort(arr, (a, b) -> a[0] == b[0] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0]));\n\n\t\t\tStringBuilder sb = new StringBuilder();\n\n\t\t\tboolean ok = true;\n\n\t\t\tint x = 0, y = 0;\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tif (arr[i][1] < y) {\n\n\t\t\t\t\tok = false;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\n\n\t\t\t\twhile (x < arr[i][0]) {\n\n\t\t\t\t\tsb.append(\"R\");\n\n\t\t\t\t\tx++;\n\n\t\t\t\t}\n\n\t\t\t\twhile (y < arr[i][1]) {\n\n\t\t\t\t\tsb.append(\"U\");\n\n\t\t\t\t\ty++;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\n\t\t\tif (ok) {\n\n\t\t\t\tSystem.out.println(\"YES\");\n\n\t\t\t\tSystem.out.println(sb);\n\n\t\t\t} else {\n\n\t\t\t\tSystem.out.println(\"NO\");\n\n\t\t\t}\n\n\n\n\t\t}\n\n\n\n\t}\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":"\/\/package com.company;\/\/Read minute details if coming wrong for no idea questions\n\n\n\n\n\nimport com.sun.source.tree.ArrayAccessTree;\n\n\n\nimport javax.swing.*;\n\nimport java.beans.IntrospectionException;\n\nimport java.math.BigInteger;\n\nimport java.util.*;\n\nimport java.io.*;\n\n\n\n\n\npublic class Main {\n\n\n\n\n\n static class pair implements Comparable {\n\n long a = 0;\n\n long b = 0;\n\n \/\/ int cnt;\n\n\n\n pair(long b, long a) {\n\n this.a = b;\n\n this.b = a;\n\n \/\/ cnt = x;\n\n }\n\n\n\n @Override\n\n public int compareTo(pair o) {\n\n\n\n if(this.a != o.a)\n\n return (int) (this.a - o.a);\n\n else\n\n return (int) (this.b - o.b);\n\n }\n\n public boolean equals(Object o) {\n\n if (o instanceof pair) {\n\n pair p = (pair) o;\n\n return p.a == a && p.b == b;\n\n }\n\n return false;\n\n }\n\n\n\n public int hashCode() {\n\n return (Long.valueOf(a).hashCode()) * 31 + (Long.valueOf(b).hashCode());\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.hasMoreTokens()) {\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().trim();\n\n } catch (Exception e) {\n\n e.printStackTrace();\n\n }\n\n return str;\n\n }\n\n }\n\n\n\n static class FastWriter {\n\n private final BufferedWriter bw;\n\n\n\n public FastWriter() {\n\n this.bw = new BufferedWriter(new OutputStreamWriter(System.out));\n\n }\n\n\n\n public void prlong(Object object) throws IOException {\n\n\n\n bw.append(\"\" + object);\n\n }\n\n\n\n public void prlongln(Object object) throws IOException {\n\n prlong(object);\n\n bw.append(\"\\n\");\n\n }\n\n\n\n public void close() throws IOException {\n\n bw.close();\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 return gcd(b % a, a);\n\n }\n\n\n\n\n\n\n\n \/\/HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS\n\n\n\n\/\/ HashSet set = new HashSet<>();\n\n\/\/ for(int i = 0; i < s.length(); i++){\n\n\/\/ int b = 0;\n\n\/\/ long h = 1;\n\n\/\/ for(int j=i; j= 0; i--) {\n\n invfact[i] = (invfact[i + 1] * (i + 1)) % p;\n\n }\n\n }\n\n\n\n private long nCr(int n, int r) {\n\n if (r > n || n < 0 || r < 0) return 0;\n\n return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p;\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\n\n static void sort(long[] a ) {\n\n ArrayList l = new ArrayList<>();\n\n for(long i: a) {\n\n l.add(i);\n\n }\n\n Collections.sort(l);\n\n for(int i =0;ians=new ArrayList<>();\n\n\/\/ for(int i =0;i 0) {\n\n\n\n\n\n int n =in.nextInt();\n\n\n\n String s =in.next();\n\n\n\n HashMapmap=new HashMap<>();\n\n int min =100000000;\n\n int a=-1;\n\n int b =-1;\n\n\n\n int x =0;\n\n int y =0;\n\nmap.put(new pair(0,0),-1);\n\n for(int i =0;i>adj, int curr, int par) {\n\n\n\n double len = 0;\n\n\n\n for(int child: adj.get(curr)) {\n\n if(child == par)\n\n continue;\n\n len += dfs(adj, child, curr)+1;\n\n }\n\n \/\/System.out.println(curr+\" \"+len);\n\n if(len == 0) \/\/ leaf node\n\n return 0;\n\n if(par == -1) \/\/ root node\n\n return len\/adj.get(curr).size();\n\n return len\/(adj.get(curr).size()-1);\n\n }\n\n\n\n\n\n\n\n\n\n static long comb(int r, int n)\n\n {\n\n long result;\n\n\n\n result = factorial(n)\/(factorial(r)*factorial(n-r));\n\n\n\n return result;\n\n\n\n }\n\n\n\n static long factorial(int n) {\n\n int c;\n\n long result = 1;\n\n\n\n for (c = 1; c <= n; c++)\n\n result = result*c;\n\n\n\n return result;\n\n }\n\n\n\n static void LongestPalindromicPrefix(String str,int lps[]){\n\n\n\n\/\/ String temp = str + '\/';\n\n\/\/ str = reverse(str);\n\n\/\/ temp += str;\n\n String temp =str;\n\n int n = temp.length();\n\n\n\n\n\n for(int i = 1; i < n; i++)\n\n {\n\n int len = lps[i - 1];\n\n while (len > 0 && temp.charAt(len) !=\n\n temp.charAt(i))\n\n {\n\n len = lps[len - 1];\n\n }\n\n if (temp.charAt(i) == temp.charAt(len))\n\n {\n\n len++;\n\n }\n\n lps[i] = len;\n\n }\n\n\n\n\/\/ return temp.substring(0, lps[n - 1]);\n\n }\n\n\n\n static String reverse(String input)\n\n {\n\n char[] a = input.toCharArray();\n\n int l, r = a.length - 1;\n\n\n\n for(l = 0; l < r; l++, r--)\n\n {\n\n char temp = a[l];\n\n a[l] = a[r];\n\n a[r] = temp;\n\n }\n\n return String.valueOf(a);\n\n }\n\n}\n\n\n\n\n\n\n\n\n\n\/*\n\n *\n\n *\u3000\u3000\u250f\u2513\u3000\u3000\u3000\u250f\u2513+ +\n\n *\u3000\u250f\u251b\u253b\u2501\u2501\u2501\u251b\u253b\u2513 + +\n\n *\u3000\u2503\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u2503\n\n *\u3000\u2503\u3000\u3000\u3000\u2501\u3000\u3000\u3000\u2503 ++ + + +\n\n * \u2588\u2588\u2588\u2588\u2501\u2588\u2588\u2588\u2588+\n\n * \u25e5\u2588\u2588\u25e4\u3000\u25e5\u2588\u2588\u25e4 +\n\n *\u3000\u2503\u3000\u3000\u3000\u253b\u3000\u3000\u3000\u2503\n\n *\u3000\u2503\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u2503 + +\n\n *\u3000\u2517\u2501\u2513\u3000\u3000\u3000\u250f\u2501\u251b\n\n *\u3000\u3000\u3000\u2503\u3000\u3000\u2503 JACKS PET FROM ANOTHER WORLD\n\n *\u3000\u3000\u3000\u2503\u3000\u3000\u2503\n\n *\u3000\u3000\u3000\u2503\u3000 \u3000 \u2517\u2501\u2501\u2501\u2513\n\n *\u3000\u3000\u3000\u2503 \u3000\u3000\u3000\u3000\u3000\u3000 \u2523\u2513-------\n\n *\u3000\u3000 \u2503 \u3000\u3000\u3000\u3000\u3000 \u3000\u250f\u251b-------\n\n *\u3000 \u2517\u2513\u2513\u250f\u2501\u2533\u2513\u250f\u251b + + + +\n\n *\u3000\u3000\u3000\u3000\u2503\u252b\u252b\u3000\u2503\u252b\u252b\n\n *\u3000\u3000\u3000\u3000\u2517\u253b\u251b\u3000\u2517\u253b\u251b+ + + +\n\n *\/\n\n\n\n\/\/RULES\n\n\/\/TAKE INPUT AS LONG IN CASE OF SUM OR MULITPLICATION OR CHECK THE CONTSRaint of the array\n\n\/\/Always use stringbuilder of out.println for strinof out.println for string or high level output\n\n\n\n\n\n\/\/ IMPORTANT TRs1 TO USE BRUTE FORCE TECHNIQUE TO SOLVE THE PROs1 OTHER CERTAIN LIMIT IS GIVENIT IS GIVEN\n\n\n\n\/\/Read minute details if coming wrong for no idea questions","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) {\n\n long q = a \/ m;\n\n long t = m;\n\n m = a % m;\n\n a = t;\n\n t = y;\n\n y = x - q * y;\n\n x = t;\n\n }\n\n if (x < 0)\n\n x += m0;\n\n return x;\n\n }\n\n\n\n private static int[] getLogArr(int n) {\n\n int arr[] = new int[n + 1];\n\n for (int i = 1; i < n + 1; i++) {\n\n arr[i] = (int) (Math.log(i) \/ Math.log(2) + 1e-10);\n\n }\n\n return arr;\n\n }\n\n\n\n private static int log[] = getLogArr(MAXN);\n\n\n\n private static int getLRSpt(int st[][], int L, int R, BinaryOperator binaryOperator) {\n\n int j = log[R - L + 1];\n\n return binaryOperator.apply(st[L][j], st[R - (1 << j) + 1][j]);\n\n }\n\n\n\n private static int[][] getSparseTable(int array[], BinaryOperator binaryOperator) {\n\n int k = log[array.length + 1] + 1;\n\n int st[][] = new int[array.length + 1][k + 1];\n\n\n\n for (int i = 0; i < array.length; i++)\n\n st[i][0] = array[i];\n\n\n\n for (int j = 1; j <= k; j++) {\n\n for (int i = 0; i + (1 << j) <= array.length; i++) {\n\n st[i][j] = binaryOperator.apply(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);\n\n }\n\n }\n\n return st;\n\n }\n\n\n\n private static int[][] getSparseTable(List list, BinaryOperator binaryOperator) {\n\n int n=list.size();\n\n int k = log[n + 1] + 1;\n\n int st[][] = new int[n + 1][k + 1];\n\n\n\n for (int i = 0; i < n; i++)\n\n st[i][0] = list.get(i);\n\n\n\n for (int j = 1; j <= k; j++) {\n\n for (int i = 0; i + (1 << j) <= n; i++) {\n\n st[i][j] = binaryOperator.apply(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);\n\n }\n\n }\n\n return st;\n\n }\n\n\n\n static class Subset {\n\n int parent;\n\n int rank;\n\n\n\n @Override\n\n public String toString() {\n\n return \"\" + parent;\n\n }\n\n }\n\n\n\n static int find(Subset[] subsets, int i) {\n\n if (subsets[i].parent != i)\n\n subsets[i].parent = find(subsets, subsets[i].parent);\n\n return subsets[i].parent;\n\n }\n\n\n\n static void union(Subset[] Subsets, int x, int y) {\n\n int xroot = find(Subsets, x);\n\n int yroot = find(Subsets, y);\n\n\n\n if (Subsets[xroot].rank < Subsets[yroot].rank)\n\n Subsets[xroot].parent = yroot;\n\n else if (Subsets[yroot].rank < Subsets[xroot].rank)\n\n Subsets[yroot].parent = xroot;\n\n else {\n\n Subsets[xroot].parent = yroot;\n\n Subsets[yroot].rank++;\n\n }\n\n }\n\n\n\n\n\n private static int maxx(Integer... a) {\n\n return Collections.max(Arrays.asList(a));\n\n }\n\n\n\n private static int minn(Integer... a) {\n\n return Collections.min(Arrays.asList(a));\n\n }\n\n\n\n\n\n private static long maxx(Long... a) {\n\n return Collections.max(Arrays.asList(a));\n\n }\n\n\n\n private static long minn(Long... a) {\n\n return Collections.min(Arrays.asList(a));\n\n }\n\n\n\n private static class Pair, U extends Comparable> implements Comparable> {\n\n T a;\n\n U b;\n\n\n\n public Pair(T a, U b) {\n\n this.a = a;\n\n this.b = b;\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 Pair pair = (Pair) o;\n\n return a.equals(pair.a) &&\n\n b.equals(pair.b);\n\n }\n\n\n\n @Override\n\n public int hashCode() {\n\n return Objects.hash(a, b);\n\n }\n\n\n\n @Override\n\n public String toString() {\n\n return \"(\" + a +\n\n \",\" + b +\n\n ')';\n\n }\n\n\n\n @Override\n\n public int compareTo(Pair o) {\n\n return (this.a.equals(o.a) ? this.b.equals(o.b) ? 0 : this.b.compareTo(o.b) : this.a.compareTo(o.a));\n\n }\n\n }\n\n\n\n\n\n public static int upperBound(List list, int value) {\n\n int low = 0;\n\n int high = list.size();\n\n while (low < high) {\n\n final int mid = (low + high) \/ 2;\n\n if (value >= list.get(mid)) {\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\n\n private static int[] getLPSArray(String pattern) {\n\n int i, j, n = pattern.length();\n\n int[] lps = new int[pattern.length()];\n\n lps[0] = 0;\n\n for (i = 1, j = 0; i < n; ) {\n\n if (pattern.charAt(i) == pattern.charAt(j)) {\n\n lps[i++] = ++j;\n\n } else if (j > 0) {\n\n j = lps[j - 1];\n\n } else {\n\n lps[i++] = 0;\n\n }\n\n }\n\n return lps;\n\n }\n\n\n\n private static List findPattern(String text, String pattern) {\n\n List matchedIndexes = new ArrayList<>();\n\n if (pattern.length() == 0) {\n\n return matchedIndexes;\n\n }\n\n int[] lps = getLPSArray(pattern);\n\n int i = 0, j = 0, n = text.length(), m = pattern.length();\n\n while (i < n) {\n\n if (text.charAt(i) == pattern.charAt(j)) {\n\n i++;\n\n j++;\n\n }\n\n if (j == m) {\n\n matchedIndexes.add(i - j);\n\n j = lps[j - 1];\n\n }\n\n if (i < n && text.charAt(i) != pattern.charAt(j)) {\n\n if (j > 0) {\n\n j = lps[j - 1];\n\n } else {\n\n i++;\n\n }\n\n }\n\n }\n\n return matchedIndexes;\n\n }\n\n\n\n private static Set getDivisors(long n) {\n\n Set divisors = new HashSet<>();\n\n divisors.add(1L);\n\n divisors.add(n);\n\n for (long i = 2; i <= Math.sqrt(n); i++) {\n\n if (n % i == 0) {\n\n divisors.add(i);\n\n divisors.add(n \/ i);\n\n }\n\n }\n\n return divisors;\n\n }\n\n\n\n private static long getLCM(long a, long b) {\n\n return (Math.max(a, b) \/ gcd(a, b)) * Math.min(a, b);\n\n }\n\n\n\n static long fac[];\n\n static long ifac[];\n\n\n\n private static void preCompute(int n) {\n\n fac = new long[n + 1];\n\n ifac = new long[n + 1];\n\n fac[0] = ifac[0] = fac[1] = ifac[1] = 1;\n\n int i;\n\n for (i = 2; i < n + 1; i++) {\n\n fac[i] = (i * fac[i - 1]) % mod;\n\n ifac[i] = (power(i, mod - 2) * ifac[i - 1]) % mod;\n\n }\n\n }\n\n\n\n private static long C(int n, int r) {\n\n if (n < 0 || r < 0) return 1;\n\n if (r > n) return 1;\n\n return (fac[n] * ((ifac[r] * ifac[n - r]) % mod)) % mod;\n\n }\n\n\n\n static int getSum(int BITree[], int index) {\n\n int sum = 0;\n\n index = index + 1;\n\n while (index > 0) {\n\n sum+=BITree[index];\n\n index -= index & (-index);\n\n }\n\n return sum;\n\n }\n\n\n\n public static void updateBIT(int BITree[], int index, int val) {\n\n index = index + 1;\n\n while (index <= BITree.length - 1) {\n\n BITree[index] += val;\n\n index += index & (-index);\n\n }\n\n }\n\n\n\n static int[] constructBITree(int n) {\n\n int BITree[] = new int[n + 1];\n\n for (int i = 1; i <= n; i++)\n\n BITree[i] = 0;\n\n return BITree;\n\n }\n\n\n\n\n\n private static int upperBound(int a[], int l, int r, int x) {\n\n if (l > r) return -1;\n\n if (l == r) {\n\n if (a[l] <= x) {\n\n return -1;\n\n } else {\n\n return a[l];\n\n }\n\n }\n\n int m = (l + r) \/ 2;\n\n if (a[m] <= x) {\n\n return upperBound(a, m + 1, r, x);\n\n } else {\n\n return upperBound(a, l, m, x);\n\n }\n\n }\n\n\n\n\n\n private static void mul(long A[][], long B[][]) {\n\n int i, j, k, n = A.length;\n\n long C[][] = new long[n][n];\n\n for (i = 0; i < n; i++) {\n\n for (j = 0; j < n; j++) {\n\n for (k = 0; k < n; k++) {\n\n C[i][j] = (C[i][j] + (A[i][k] * B[k][j]) % mod) % mod;\n\n }\n\n }\n\n }\n\n for (i = 0; i < n; i++) {\n\n for (j = 0; j < n; j++) {\n\n A[i][j] = C[i][j];\n\n }\n\n }\n\n }\n\n\n\n private static void power(long A[][], long base[][], long n) {\n\n if (n < 2) {\n\n return;\n\n }\n\n power(A, base, n \/ 2);\n\n mul(A, A);\n\n if (n % 2 == 1) {\n\n mul(A, base);\n\n }\n\n }\n\n\n\n static void reverse(int a[], int l, int r) {\n\n while (l < r) {\n\n int t = a[l];\n\n a[l] = a[r];\n\n a[r] = t;\n\n l++;\n\n r--;\n\n }\n\n }\n\n static void reverse(long a[], int l, int r) {\n\n while (l < r) {\n\n long t = a[l];\n\n a[l] = a[r];\n\n a[r] = t;\n\n l++;\n\n r--;\n\n }\n\n }\n\n\n\n public void rotate(int[] nums, int k) {\n\n k = k % nums.length;\n\n reverse(nums, 0, nums.length - k - 1);\n\n reverse(nums, nums.length - k, nums.length - 1);\n\n reverse(nums, 0, nums.length - 1);\n\n }\n\n\n\n private static boolean isSorted(int a[]) {\n\n for (int i = 0; i < a.length - 1; i++) {\n\n if (a[i] > a[i + 1]) return false;\n\n }\n\n return true;\n\n }\n\n\n\n\n\n public static int[] getNGE(int arr[]) {\n\n Stack s = new Stack<>();\n\n int n = arr.length;\n\n int nge[] = new int[n];\n\n s.push(0);\n\n for (int i = 1; i < n; i++) {\n\n while (!s.isEmpty() && arr[s.peek()] <= arr[i]) {\n\n nge[s.peek()] = i;\n\n s.pop();\n\n }\n\n s.push(i);\n\n }\n\n while (!s.isEmpty()) {\n\n nge[s.peek()] = n;\n\n s.pop();\n\n }\n\n return nge;\n\n }\n\n\n\n public static int[] getPSE(int arr[]) {\n\n Stack s = new Stack<>();\n\n int n = arr.length;\n\n int pse[] = new int[n];\n\n s.push(n-1);\n\n for (int i = n-2; i >= 0; i--) {\n\n while (!s.isEmpty() && arr[s.peek()] > arr[i]) {\n\n pse[s.peek()] = i;\n\n s.pop();\n\n }\n\n s.push(i);\n\n }\n\n while (!s.isEmpty()) {\n\n pse[s.peek()] = -1;\n\n s.pop();\n\n }\n\n\n\n return pse;\n\n }\n\n\n\n public static int[] getNSE(int arr[]) {\n\n Stack s = new Stack<>();\n\n int n = arr.length;\n\n int nse[] = new int[n];\n\n s.push(0);\n\n for (int i = 1; i < n; i++) {\n\n while (!s.isEmpty() && arr[s.peek()] > arr[i]) {\n\n nse[s.peek()] = i;\n\n s.pop();\n\n }\n\n s.push(i);\n\n }\n\n while (!s.isEmpty()) {\n\n nse[s.peek()] = n;\n\n s.pop();\n\n }\n\n\n\n return nse;\n\n }\n\n\n\n public int maximumScore(int[] nums, int k) {\n\n int pse[]=getPSE(nums);\n\n int nse[]=getNSE(nums);\n\n int ans=0;\n\n for(int i=0;ik){\n\n ans=Math.max(ans,(n-p-1)*nums[i]);\n\n }\n\n }\n\n return ans;\n\n }\n\n\n\n public int validSubarraySize(int[] nums, int threshold) {\n\n int nse[]=getNSE(nums);\n\n int pse[]=getPSE(nums);\n\n for(int i=0;ithreshold\/len) {\n\n return len;\n\n }\n\n }\n\n return -1;\n\n }\n\n\n\n private static boolean isPal(String s){\n\n for(int i=0,j=s.length()-1;ia[1]==b[1]?a[2]-b[2]:a[1]-b[1]);\n\n int ind[]=new int[n];\n\n for(int l=4;l<2*n;l*=2){\n\n int rank=0,prev=su[0][1];\n\n su[0][1]=0;\n\n ind[su[0][0]]=0;\n\n for(int i=1;ia[1]==b[1]?a[2]-b[2]:a[1]-b[1]);\n\n }\n\n int suf[]=new int[n];\n\n for(int i=0;i getPrimeFactors(long n){\n\n SetpfSet=new HashSet<>();\n\n for(long i=2;i*i<=n;i++){\n\n while(n%i==0){\n\n pfSet.add(i);\n\n n\/=i;\n\n }\n\n }\n\n if(n>1){\n\n pfSet.add(n);\n\n }\n\n return pfSet;\n\n }\n\n\n\n\n\n\n\n public static void main(String[] args) throws Exception {\n\n\n\n long START_TIME = System.currentTimeMillis();\n\n\n\n try (FastReader in = new FastReader();\n\n FastWriter out = new FastWriter()) {\n\n int n, t, i, j, f, k, m, ti, tidx, gm, g, l,r,q;\n\n for (t = in.nextInt(), tidx = 1; tidx <= t; tidx++)\n\n {\n\n long x = 0, y = 0, z = 0, sum = 0, bhc = 0, ans = 0;\n\n \/\/out.print(String.format(\"Case #%d: \", tidx));\n\n x=in.nextLong();\n\n y=in.nextLong();\n\n z=gcd(x,y);\n\n y\/=z;\n\n Setpf=getPrimeFactors(y);\n\n for(long p:pf){\n\n y=(y\/p)*(p-1);\n\n }\n\n out.println(y);\n\n }\n\n \/*if (args.length > 0 && \"ex_time\".equals(args[0])) {\n\n out.print(\"\\nTime taken: \");\n\n out.println(System.currentTimeMillis() - START_TIME);\n\n }*\/\n\n out.commit();\n\n }\n\n\n\n\n\n }\n\n\n\n public static class FastReader implements Closeable {\n\n private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n private StringTokenizer st;\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 (Exception 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 @Override\n\n public void close() throws IOException {\n\n br.close();\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[] nextIntArr(int n) {\n\n int[] arr = new int[n];\n\n for (int i = 0; i < n; i++) {\n\n arr[i] = nextInt();\n\n }\n\n return arr;\n\n }\n\n\n\n Integer[] nextIntegerArr(int n) {\n\n Integer[] arr = new Integer[n];\n\n for (int i = 0; i < n; i++) {\n\n arr[i] = nextInt();\n\n }\n\n return arr;\n\n }\n\n\n\n double[] nextDoubleArr(int n) {\n\n double[] arr = new double[n];\n\n for (int i = 0; i < n; i++) {\n\n arr[i] = nextDouble();\n\n }\n\n return arr;\n\n }\n\n\n\n long[] nextLongArr(int n) {\n\n long[] arr = new long[n];\n\n for (int i = 0; i < n; i++) {\n\n arr[i] = nextLong();\n\n }\n\n return arr;\n\n }\n\n\n\n List nextLongList(int n) {\n\n List retList = new ArrayList<>();\n\n for (int i = 0; i < n; i++) {\n\n retList.add(nextLong());\n\n }\n\n return retList;\n\n }\n\n\n\n String[] nextStrArr(int n) {\n\n String[] arr = new String[n];\n\n for (int i = 0; i < n; i++) {\n\n arr[i] = next();\n\n }\n\n return arr;\n\n }\n\n\n\n\n\n int[][] nextIntArr2(int n, int m) {\n\n int[][] arr = new int[n][m];\n\n for (int i = 0; i < n; i++) {\n\n arr[i] = nextIntArr(m);\n\n }\n\n return arr;\n\n }\n\n\n\n long[][] nextLongArr2(int n, int m) {\n\n long[][] arr = new long[n][m];\n\n for (int i = 0; i < n; i++) {\n\n arr[i] = nextLongArr(m);\n\n }\n\n return arr;\n\n }\n\n\n\n }\n\n\n\n\n\n public static class FastWriter implements Closeable {\n\n BufferedWriter bw;\n\n StringBuilder sb = new StringBuilder();\n\n List list = new ArrayList<>();\n\n Set set = new HashSet<>();\n\n\n\n public FastWriter() {\n\n bw = new BufferedWriter(new OutputStreamWriter(System.out));\n\n }\n\n\n\n void commit() throws IOException {\n\n bw.write(sb.toString());\n\n bw.flush();\n\n sb = new StringBuilder();\n\n }\n\n\n\n public void print(T obj) throws IOException {\n\n sb.append(obj.toString());\n\n \/\/commit();\n\n }\n\n\n\n public void println() throws IOException {\n\n print(\"\\n\");\n\n }\n\n\n\n public void println(T obj) throws IOException {\n\n print(obj.toString() + \"\\n\");\n\n }\n\n\n\n void printArrLn(T[] arr) throws IOException {\n\n for (int i = 0; i < arr.length - 1; i++) {\n\n print(arr[i] + \" \");\n\n }\n\n println(arr[arr.length - 1]);\n\n }\n\n\n\n void printArr2(T[][] arr) throws IOException {\n\n for (int j = 0; j < arr.length; j++) {\n\n for (int i = 0; i < arr[j].length - 1; i++) {\n\n print(arr[j][i] + \" \");\n\n }\n\n println(arr[j][arr[j].length - 1]);\n\n }\n\n }\n\n\n\n void printColl(Collection coll) throws IOException {\n\n List stringList = coll.stream().map(e -> \"\"+e).collect(Collectors.toList());\n\n println(String.join(\" \", stringList));\n\n }\n\n\n\n void printCharN(char c, int n) throws IOException {\n\n for (int i = 0; i < n; i++) {\n\n print(c);\n\n }\n\n }\n\n\n\n void printIntArr(int []arr) throws IOException {\n\n for (int i = 0; i < arr.length - 1; i++) {\n\n print(arr[i] + \" \");\n\n }\n\n println(arr[arr.length - 1]);\n\n }\n\n\n\n void printIntArr2(int[][] arr) throws IOException {\n\n for (int j = 0; j < arr.length; j++) {\n\n for (int i = 0; i < arr[j].length - 1; i++) {\n\n print(arr[j][i] + \" \");\n\n }\n\n println(arr[j][arr[j].length - 1]);\n\n }\n\n }\n\n\n\n @Override\n\n public void close() throws IOException {\n\n bw.close();\n\n }\n\n\n\n }\n\n\n\n}\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":"import java.io.*;\nimport java.sql.Array;\nimport java.util.*;\n\npublic class Main {\n public static void main(String[] args) {\n var fastScanner = new FastScanner();\n int n = fastScanner.nextInt();\n for (int i=0; i();\n list.add(0);\n for (int j=0; j= 0; i--) {\n\n freq[i] += freq[i + 1];\n\n }\n\n\n\n int[] res = new int[26];\n\n for (int i = 0; i < n; i++) {\n\n res[s[i] - 'a'] += freq[i];\n\n }\n\n\n\n for (int i = 0; i < 26; i++) {\n\n out.print(res[i] + \" \");\n\n }\n\n out.println();\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":"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.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.util.StringTokenizer;\n\nimport java.util.List;\n\nimport java.util.ArrayList;\n\npublic class Solution {\n\n static Reader input = new Reader();\n\n static int n;\n\n static List[] adjacents;\n\n static int[] parent, height, deep;\n\n static int start = 0, end = 0, v = 0;\n\n public static void main(String[] args) throws IOException {\n\n n = input.nextInt();\n\n adjacents = new List[n];\n\n for(int i = 0; i < n; ++i) adjacents[i] = new ArrayList();\n\n int u, v;\n\n for(int i = 1; i < n; ++i) {\n\n u = input.nextInt()-1;\n\n v = input.nextInt()-1;\n\n adjacents[u].add(v);\n\n adjacents[v].add(u);\n\n }\n\n parent = new int[n];\n\n height = new int[n];\n\n deep = new int[n];\n\n dfs(0, -1);\n\n dfs(0);\n\n List path = new ArrayList();\n\n setPath(start, end, -1, path);\n\n boolean[] inPath = new boolean[n];\n\n for(int node : path) inPath[node] = true;\n\n int[] t = null;\n\n for(int node : path) {\n\n int[] temp = test(node, -1, inPath);\n\n if(temp[0] == start || temp[0] == end) continue;\n\n if(t == null || temp[1] > t[1]) {\n\n t = temp;\n\n }\n\n }\n\n StringBuilder output = new StringBuilder();\n\n int x = t[1] + path.size()-1;\n\n output.append(x);\n\n output.append(\"\\n\");\n\n output.append(start+1);\n\n output.append(\" \");\n\n output.append(end+1);\n\n output.append(\" \");\n\n output.append(t[0]+1);\n\n System.out.print(output);\n\n }\n\n static int[] test(int node, int p, boolean[] inPath) {\n\n int[] result = new int[]{node, 0};\n\n for(int adjacent : adjacents[node]) {\n\n if(adjacent != p && !inPath[adjacent]) {\n\n int[] temp = test(adjacent, node, inPath);\n\n if(temp[1] > result[1]) {\n\n result = temp;\n\n }\n\n }\n\n }\n\n if(p != -1) {\n\n ++result[1];\n\n }\n\n return result;\n\n }\n\n static boolean setPath(int node, int dist, int p, List path) {\n\n if(node == dist) {\n\n path.add(node);\n\n return true;\n\n }\n\n for(int adjacent : adjacents[node]) {\n\n if(adjacent != p) {\n\n if(setPath(adjacent, dist, node, path)) {\n\n path.add(node);\n\n return true;\n\n }\n\n }\n\n }\n\n return false;\n\n }\n\n static void dfs(int node) {\n\n int max1 = -1, max2 = -1;\n\n for(int adjacent : adjacents[node]) {\n\n if(adjacent != parent[node]) {\n\n if(max1 == -1 || height[adjacent] > height[max1]) {\n\n max2 = max1;\n\n max1 = adjacent;\n\n } else if(max2 == -1 || height[adjacent] > height[max2]) {\n\n max2 = adjacent;\n\n }\n\n dfs(adjacent);\n\n }\n\n }\n\n if(max1 != -1 && max2 != -1) {\n\n if(height[max1]+height[max2]+1 > v) {\n\n v = height[max1]+height[max2]+1;\n\n start = deep[max1];\n\n end = deep[max2];\n\n }\n\n } else if(max1 != -1) {\n\n if(height[max1]+1 > v) {\n\n v = height[max1]+1;\n\n start = deep[max1];\n\n end = node;\n\n }\n\n } else if(max2 != -1) {\n\n if(height[max2]+1 > v) {\n\n v = height[max2]+1;\n\n start = deep[max2]+1;\n\n end = node;\n\n }\n\n }\n\n }\n\n static void dfs(int node, int p) {\n\n parent[node] = p;\n\n int h = 0;\n\n int d = node;\n\n for(int adjacent : adjacents[node]) {\n\n if(adjacent != p) {\n\n dfs(adjacent, node);\n\n if(height[adjacent] > h) {\n\n h = height[adjacent];\n\n d = deep[adjacent];\n\n }\n\n }\n\n }\n\n height[node] = h+1;\n\n deep[node] = d;\n\n }\n\n static class Reader {\n\n BufferedReader bufferedReader;\n\n StringTokenizer string;\n\n public Reader() {\n\n InputStreamReader inr = new InputStreamReader(System.in);\n\n bufferedReader = new BufferedReader(inr);\n\n }\n\n public String next() throws IOException {\n\n while(string == null || ! string.hasMoreElements()) {\n\n string = new StringTokenizer(bufferedReader.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 public double nextDouble() throws IOException {\n\n return Double.parseDouble(next());\n\n }\n\n public String nextLine() throws IOException {\n\n return bufferedReader.readLine();\n\n }\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":"\/*\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 Scanner{\n\n\t\t \n\n\t\t\tBufferedReader br;\n\n\t\t\tStringTokenizer st;\n\n\t\t\tpublic Scanner() {\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 Scanner sc = new Scanner();\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 for(int i = 1 ; i<=tc ; i++) {\n\n\n\n\/\/\t\t\t sb.append(\"Case #\" + i + \": \" );\t\/\/ During KickStart && HackerCup\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 \n\n\t static void TEST_CASE() {\n\n\t\t String str = sc.next();\n\n\t\t int n = str.length();\n\n\t\t int[] dp[] = new int[n+1][26];\n\n\t\t for(int i = 1 ; i<=n ;i ++) {\n\n\t\t\t char cc = str.charAt(i-1);\n\n\t\t\t dp[i][cc-'a']++;\n\n\t\t\t for(int j = 0 ; j<26 ; j++) dp[i][j] += dp[i-1][j];\n\n\t\t }\n\n\t\t int q = sc.nextInt();\n\n\t\t while(q-- > 0) {\n\n\t\t\t int l = sc.nextInt() , r = sc.nextInt();\n\n\t\t\t int c = 0;\n\n\t\t\t for(int i =0 ; i<26 ; i++) {\n\n\t\t\t\t if(dp[r][i]-dp[l-1][i] > 0) c++;\n\n\t\t\t }\n\n\t\t\t if(c>2 || l == r || str.charAt(l-1) != str.charAt(r-1)) {\n\n\t\t\t\t sb.append(\"YES\\n\");\n\n\t\t\t }else {\n\n\t\t\t\t sb.append(\"NO\\n\");\n\n\t\t\t }\n\n\t\t }\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\t\n\n\tabb - > bab - > bba\n\n\t\n\n\tabc - > cba\n\n\tabcba -> abbca -> aabbc\t || a -> a , a -> b , a -> c \n\n \tabbb -> bb\n\n \t\n\n \tdbccbba\n\n *\/\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","language":"java"} +{"contest_id":"1295","problem_id":"A","statement":"A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2\u2264n\u22641052\u2264n\u2264105) \u2014 the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2\n3\n4\nOutputCopy7\n11\n","tags":["greedy"],"code":"import java.util.*;\n\npublic class A {\n\n public static void main(String[] args) {\n\n Scanner in = new Scanner(System.in);\n\n int n = in.nextInt();\n\n for(int i = 0 ; i < n ; i++){\n\n String tar = \"\";\n\n int q = in.nextInt();\n\n while (q!=0){\n\n if(q%2==0){\n\n tar+=\"1\";\n\n q-=2;\n\n }else{\n\n tar+=\"7\";\n\n q-=3;\n\n }\n\n }\n\n System.out.println(tar);\n\n }\n\n }\n\n\n\n\n\n}\n\n","language":"java"} +{"contest_id":"1296","problem_id":"E2","statement":"E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1\u2264res\u2264n1\u2264res\u2264n) \u2014 the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1\u2264ci\u2264res1\u2264ci\u2264res and cici means the color of the ii-th character.ExamplesInputCopy9\nabacbecfd\nOutputCopy2\n1 1 2 1 2 1 2 1 2 \nInputCopy8\naaabbcbb\nOutputCopy2\n1 2 1 2 1 2 1 1\nInputCopy7\nabcdedc\nOutputCopy3\n1 1 1 1 1 2 3 \nInputCopy5\nabcde\nOutputCopy1\n1 1 1 1 1 \n","tags":["data structures","dp"],"code":"import java.io.*;\n\nimport java.util.*;\n\n\n\npublic class Task {\n\n\n\n public static void main(String[] args) throws Exception {\n\n\n\n new Task().go();\n\n }\n\n\n\n PrintWriter out;\n\n Reader in;\n\n BufferedReader br;\n\n\n\n Task() throws IOException {\n\n\n\n try {\n\n\n\n \/\/br = new BufferedReader( new FileReader(\"input.txt\") );\n\n \/\/in = new Reader(\"input.txt\");\n\n in = new Reader(\"input.txt\");\n\n out = new PrintWriter( new BufferedWriter(new FileWriter(\"output.txt\")) );\n\n }\n\n catch (Exception e) {\n\n\n\n \/\/br = new BufferedReader( new InputStreamReader( System.in ) );\n\n in = new Reader();\n\n out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );\n\n }\n\n }\n\n\n\n void go() throws Exception {\n\n\n\n \/\/int t = in.nextInt();\n\n int t = 1;\n\n while (t > 0) {\n\n solve();\n\n t--;\n\n }\n\n\n\n out.flush();\n\n out.close();\n\n }\n\n\n\n\n\n int inf = 2000000000;\n\n int mod = 1000000007;\n\n double eps = 0.000000001;\n\n\n\n int n;\n\n int m;\n\n\n\n ArrayList[] g;\n\n\n\n void solve() throws IOException {\n\n int n = in.nextInt();\n\n String s = in.next();\n\n int[] a = new int[n];\n\n int cnt = 1;\n\n int[] d = new int[26];\n\n for (int i = 0; i < n; i++) {\n\n int ch = s.charAt(i) - 'a';\n\n d[ch] = 1;\n\n for (int j = ch + 1; j < 26; j++)\n\n d[ch] = Math.max(d[ch], d[j] + 1);\n\n cnt = Math.max(cnt, d[ch]);\n\n a[i] = d[ch];\n\n }\n\n out.println(cnt);\n\n for (int i = 0; i < n; i++)\n\n out.print(a[i] + \" \");\n\n }\n\n\n\n\n\n class Pair implements Comparable {\n\n\n\n int a;\n\n 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 public int compareTo(Pair p) {\n\n if (a != p.a)\n\n return Integer.compare(a, p.a);\n\n else\n\n return Integer.compare(-b, -p.b);\n\n }\n\n }\n\n\n\n class Item {\n\n\n\n int a;\n\n int b;\n\n int c;\n\n\n\n Item(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 }\n\n\n\n\n\n class Reader {\n\n\n\n BufferedReader br;\n\n StringTokenizer tok;\n\n\n\n Reader(String file) throws IOException {\n\n br = new BufferedReader( new FileReader(file) );\n\n }\n\n\n\n Reader() throws IOException {\n\n br = new BufferedReader( new InputStreamReader(System.in) );\n\n }\n\n\n\n String next() throws IOException {\n\n\n\n while (tok == null || !tok.hasMoreElements())\n\n tok = new StringTokenizer(br.readLine());\n\n return tok.nextToken();\n\n }\n\n\n\n int nextInt() throws NumberFormatException, IOException {\n\n return Integer.valueOf(next());\n\n }\n\n\n\n long nextLong() throws NumberFormatException, IOException {\n\n return Long.valueOf(next());\n\n }\n\n\n\n double nextDouble() throws NumberFormatException, IOException {\n\n return Double.valueOf(next());\n\n }\n\n\n\n\n\n String nextLine() throws IOException {\n\n return br.readLine();\n\n }\n\n\n\n }\n\n\n\n static class InputReader\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 InputReader()\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 InputReader(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\n\n}","language":"java"} +{"contest_id":"1310","problem_id":"A","statement":"A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A\/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn\u00a0\u2014 the number of news categories (1\u2264n\u22642000001\u2264n\u2264200000).The second line of input consists of nn integers aiai\u00a0\u2014 the number of publications of ii-th category selected by the batch algorithm (1\u2264ai\u22641091\u2264ai\u2264109).The third line of input consists of nn integers titi\u00a0\u2014 time it takes for targeted algorithm to find one new publication of category ii (1\u2264ti\u2264105)1\u2264ti\u2264105).OutputPrint one integer\u00a0\u2014 the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5\n3 7 9 7 8\n5 2 5 7 5\nOutputCopy6\nInputCopy5\n1 2 3 4 5\n1 1 1 1 1\nOutputCopy0\nNoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.","tags":["data structures","greedy","sortings"],"code":"import java.io.*;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\n\/**\n * @author Nikita Gorokhov \n *\/\npublic class A1310 {\n\n \/\/ 420 remainder: use long everywhere\n\n private final static boolean MULTIPLE_TESTS = false;\n\n private FastReader reader;\n private FastWriter writer;\n\n private void solve() {\n int n = reader.readInt();\n int[] a = reader.readIntArray(n);\n int[] t = reader.readIntArray(n);\n\n var sorted = IntStream.range(0, n)\n .mapToObj(i -> Tuple.Tuple2.of(a[i], t[i]))\n .sorted()\n .collect(Collectors.toList());\n\n TreeMap multiset = new TreeMap<>();\n long sumInSet = 0;\n long ans = 0;\n int last = -1;\n for (int i = 0; i < n; i++) {\n var cur = sorted.get(i);\n\n if (cur.first != last) {\n while (!multiset.isEmpty() && last < cur.first) {\n var max = multiset.lastEntry();\n var newVal = max.getValue() - 1;\n sumInSet -= max.getKey();\n if (newVal == 0) {\n multiset.remove(max.getKey());\n } else {\n multiset.put(max.getKey(), max.getValue() - 1);\n }\n ans += sumInSet;\n last++;\n }\n\n last = cur.first;\n }\n\n multiset.put(cur.second, multiset.getOrDefault(cur.second, 0) + 1);\n sumInSet += cur.second;\n }\n\n while (!multiset.isEmpty()) {\n var max = multiset.lastEntry();\n var newVal = max.getValue() - 1;\n sumInSet -= max.getKey();\n if (newVal == 0) {\n multiset.remove(max.getKey());\n } else {\n multiset.put(max.getKey(), max.getValue() - 1);\n }\n ans += sumInSet;\n last++;\n }\n\n writer.print(ans);\n }\n\n private void run() throws Exception {\n reader = new FastReader();\n writer = new FastWriter();\n\n int t = MULTIPLE_TESTS ? reader.readInt() : 1;\n\n for (int testNum = 0; testNum < t; testNum++) {\n solve();\n }\n\n writer.close();\n reader.close();\n }\n\n public static void main(String[] args) throws Exception {\n new A1310().run();\n }\n\n private final static boolean ONLINE_JUDGE = System.getProperty(\"ONLINE_JUDGE\") != null;\n\n private static class FastWriter implements AutoCloseable {\n @SuppressWarnings(value=\"all\")\n private final static Optional OUTPUT_FILENAME = Optional.empty();\n\n private final PrintWriter out;\n\n public FastWriter() throws FileNotFoundException {\n this.out = OUTPUT_FILENAME.isEmpty() ? new PrintWriter(System.out) : new PrintWriter(new File(OUTPUT_FILENAME.get()));\n }\n\n public void print(int value) {\n out.print(value);\n }\n\n public void print(long value) {\n out.print(value);\n }\n\n public void print(double value) {\n out.print(value);\n }\n\n public void print(T value) {\n out.print(value);\n }\n\n public void println(int value) {\n out.println(value);\n }\n\n public void println(long value) {\n out.println(value);\n }\n\n public void println(double value) {\n out.println(value);\n }\n\n public void println(T value) {\n out.println(value);\n }\n\n public void printArray(T[] array) {\n for (int i = 0; i < array.length; i++) {\n out.print(array[i]);\n if (i + 1 < array.length) {\n out.print(' ');\n }\n }\n out.println();\n }\n\n public void printArray(int[] array) {\n for (int i = 0; i < array.length; i++) {\n out.print(array[i]);\n if (i + 1 < array.length) {\n out.print(' ');\n }\n }\n out.println();\n }\n\n public void printArray(long[] array) {\n for (int i = 0; i < array.length; i++) {\n out.print(array[i]);\n if (i + 1 < array.length) {\n out.print(' ');\n }\n }\n out.println();\n }\n\n public void printArray(double[] array) {\n for (int i = 0; i < array.length; i++) {\n out.print(array[i]);\n if (i + 1 < array.length) {\n out.print(' ');\n }\n }\n out.println();\n }\n\n @Override\n public void close() {\n out.close();\n }\n }\n\n private static class FastReader implements AutoCloseable {\n private final static String INPUT_FILENAME = \"input.txt\";\n\n private final InputStream inputStream;\n private final byte[] buffer = new byte[1024];\n\n private int bufferLen = 0;\n private int bufferPtr = 0;\n\n public FastReader() throws FileNotFoundException {\n this.inputStream = ONLINE_JUDGE ? System.in : new FileInputStream(INPUT_FILENAME);\n }\n\n public int[] readIntArray(int size) {\n int[] array = new int[size];\n for (int i = 0; i < size; i++) {\n array[i] = readInt();\n }\n return array;\n }\n\n public long[] readLongArray(int size) {\n long[] array = new long[size];\n for (int i = 0; i < size; i++) {\n array[i] = readLong();\n }\n return array;\n }\n\n public double[] readDoubleArray(int size) {\n double[] array = new double[size];\n for (int i = 0; i < size; i++) {\n array[i] = readLong();\n }\n return array;\n }\n\n public double readDouble() {\n return Double.parseDouble(readToken());\n }\n\n public String readToken() {\n int b = skip();\n StringBuilder sb = new StringBuilder();\n while (!(isSpaceChar(b))) {\n sb.appendCodePoint(b);\n b = readByte();\n }\n return sb.toString();\n }\n\n public int readInt() {\n int num = 0, b;\n boolean minus = false;\n\n while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));\n\n if (b == '-') {\n minus = true;\n b = readByte();\n }\n\n while (true) {\n if (b >= '0' && b <= '9') {\n num = num * 10 + (b - '0');\n } else {\n return minus ? -num : num;\n }\n b = readByte();\n }\n }\n\n public long readLong() {\n long num = 0;\n int b;\n boolean minus = false;\n\n while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));\n\n if (b == '-') {\n minus = true;\n b = readByte();\n }\n\n while (true) {\n if (b >= '0' && b <= '9') {\n num = num * 10 + (b - '0');\n } else {\n return minus ? -num : num;\n }\n b = readByte();\n }\n }\n\n public int readByte() {\n if (bufferLen == -1) {\n throw new InputMismatchException();\n }\n if (bufferPtr >= bufferLen) {\n bufferPtr = 0;\n try {\n bufferLen = inputStream.read(buffer);\n } catch (IOException e) {\n throw new InputMismatchException();\n }\n if (bufferLen <= 0) {\n return -1;\n }\n }\n return buffer[bufferPtr++];\n }\n\n public char readChar() {\n return (char) skip();\n }\n\n private int skip() {\n int b;\n while ((b = readByte()) != -1 && isSpaceChar(b));\n return b;\n }\n\n private static boolean isSpaceChar(int c) {\n return !(c >= 33 && c <= 126);\n }\n\n @Override\n public void close() throws Exception {\n inputStream.close();\n bufferPtr = bufferLen;\n }\n }\n\n private static class Tuple {\n public static Tuple2 of(A first, B second) {\n return new Tuple2<>(first, second);\n }\n\n public static , B extends Comparable> Tuple2 of(A first, B second) {\n return new ComparableTuple2<>(first, second);\n }\n\n public static Tuple3 of(A first, B second, C third) {\n return new Tuple3<>(first, second, third);\n }\n\n public static , B extends Comparable, C extends Comparable> Tuple3 of(A first, B second, C third) {\n return new ComparableTuple3<>(first, second, third);\n }\n\n private static class Tuple2 extends Tuple {\n public final A first;\n public final B second;\n\n private Tuple2(A first, B second) {\n this.first = first;\n this.second = second;\n }\n\n @Override\n public String toString() {\n return \"(\" + first + \", \" + second + \")\";\n }\n }\n\n private static class Tuple3 extends Tuple2 {\n public final C third;\n\n private Tuple3(A first, B second, C third) {\n super(first, second);\n this.third = third;\n }\n\n @Override\n public String toString() {\n return \"(\" + first + \", \" + second + \", \" + third + \")\";\n }\n }\n\n private static class ComparableTuple2, B extends Comparable> extends Tuple2 implements Comparable> {\n private ComparableTuple2(A first, B second) {\n super(first, second);\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public int compareTo(ComparableTuple2 that) {\n var res = first.compareTo((A) that.first);\n return res == 0 ? second.compareTo((B) that.second) : res;\n }\n }\n\n private static class ComparableTuple3, B extends Comparable, C extends Comparable>\n extends Tuple3 implements Comparable> {\n\n private ComparableTuple3(A first, B second, C third) {\n super(first, second, third);\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public int compareTo(ComparableTuple3 that) {\n var firstR = first.compareTo((A) that.first);\n if (firstR == 0) {\n var secondR = second.compareTo((B) that.second);\n if (secondR == 0) {\n return third.compareTo((C) that.third);\n }\n return secondR;\n }\n return firstR;\n }\n }\n }\n\n private static class Utils {\n private static final Random random = new Random(System.nanoTime());\n\n public static > void sort(T[] array) {\n shuffle(array);\n Arrays.sort(array);\n }\n\n public static void sort(int[] array) {\n shuffle(array);\n Arrays.sort(array);\n }\n\n public static void sort(long[] array) {\n shuffle(array);\n Arrays.sort(array);\n }\n\n public static void sort(double[] array) {\n shuffle(array);\n Arrays.sort(array);\n }\n\n public static void sort(T[] array, Comparator comparator) {\n shuffle(array);\n Arrays.sort(array, comparator);\n }\n\n public static void shuffle(T[] array) {\n for (int i = array.length - 1; i > 0; i--) {\n int index = random.nextInt(i + 1);\n T a = array[index];\n array[index] = array[i];\n array[i] = a;\n }\n }\n\n public static void shuffle(int[] array) {\n for (int i = array.length - 1; i > 0; i--) {\n int index = random.nextInt(i + 1);\n int a = array[index];\n array[index] = array[i];\n array[i] = a;\n }\n }\n\n public static void shuffle(long[] array) {\n for (int i = array.length - 1; i > 0; i--) {\n int index = random.nextInt(i + 1);\n long a = array[index];\n array[index] = array[i];\n array[i] = a;\n }\n }\n\n public static void shuffle(double[] array) {\n for (int i = array.length - 1; i > 0; i--) {\n int index = random.nextInt(i + 1);\n double a = array[index];\n array[index] = array[i];\n array[i] = a;\n }\n }\n\n public static > void sort(List list) {\n Collections.shuffle(list);\n Collections.sort(list);\n }\n\n public static void sort(List list, Comparator comparator) {\n Collections.shuffle(list);\n list.sort(comparator);\n }\n\n public static int randomInt(int fromIncluded, int toExcluded) {\n return fromIncluded + random.nextInt(toExcluded - fromIncluded);\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\nimport java.io.*;\n\n\n\npublic class A {\n\n\tstatic 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 main(String[] args) throws IOException {\n\n\t\tScanner sc = new Scanner(System.in);\n\n\t\tStringBuilder str = new StringBuilder();\n\n\t\tint t = sc.nextInt();\n\n\t\tfor (int xx = 1; xx <= t; xx++) {\n\n\t\t\tint n = sc.nextInt();\n\n\t\t\tint[] arr = new int[n];\n\n\t\t\tfor (int i = 0; i < n; i++)\n\n\t\t\t\tarr[i] = sc.nextInt();\n\n\t\t\tboolean ok = false;\n\n\t\t\tHashMap map = new HashMap<>();\n\n\t\t\tfor (int i = 0; i < n; i++) {\n\n\t\t\t\tif (map.containsKey(arr[i])) {\n\n\t\t\t\t\tif (i - map.get(arr[i]) > 1)\n\n\t\t\t\t\t\tok = true;\n\n\t\t\t\t} else\n\n\t\t\t\t\tmap.put(arr[i], i);\n\n\t\t\t}\n\n\t\t\tif (ok)\n\n\t\t\t\tstr.append(\"YES\" + \"\\n\");\n\n\t\t\telse\n\n\t\t\t\tstr.append(\"NO\" + \"\\n\");\n\n\t\t}\n\n\t\tSystem.out.println(str);\n\n\t\tsc.close();\n\n\t}\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.*;\n\nimport java.math.BigInteger;\n\nimport java.util.*;\n\n\n\npublic class Main {\n\n static int MOD = 1000000007;\n\n\n\n \/\/ After writing solution, quick scan for:\n\n \/\/ array out of bounds\n\n \/\/ special cases e.g. n=1?\n\n \/\/ npe, particularly in maps\n\n \/\/\n\n \/\/ Big numbers arithmetic bugs:\n\n \/\/ int overflow\n\n \/\/ sorting, or taking max, after MOD\n\n void solve() throws IOException {\n\n int n = ri();\n\n int[] a = ril(n);\n\n Node root = new Node();\n\n for (int ai : a) {\n\n Node curr = root;\n\n for (int b = 29; b >= 0; b--) {\n\n int bit = ((1 << b) & ai) > 0 ? 1 : 0;\n\n if (bit == 0) {\n\n if (curr.zero == null) curr.zero = new Node();\n\n curr = curr.zero;\n\n } else {\n\n if (curr.one == null) curr.one = new Node();\n\n curr = curr.one;\n\n }\n\n }\n\n }\n\n\n\n dfs(root, 29, 0);\n\n pw.println(ans);\n\n }\n\n \/\/ IMPORTANT\n\n \/\/ DID YOU CHECK THE COMMON MISTAKES ABOVE?\n\n\n\n int ans = Integer.MAX_VALUE;\n\n void dfs(Node curr, int b, int sofar) {\n\n if (b < 0) {\n\n ans = Math.min(ans, sofar);\n\n return;\n\n }\n\n if (curr.zero == null) {\n\n dfs(curr.one, b-1, sofar);\n\n } else if (curr.one == null) {\n\n dfs(curr.zero, b-1, sofar);\n\n } else {\n\n sofar = sofar | (1 << b);\n\n dfs(curr.one, b-1, sofar);\n\n dfs(curr.zero, b-1, sofar);\n\n }\n\n }\n\n\n\n \/\/ Template code below\n\n\n\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n PrintWriter pw = new PrintWriter(System.out);\n\n\n\n public static void main(String[] args) throws IOException {\n\n Main m = new Main();\n\n m.solve();\n\n m.close();\n\n }\n\n\n\n void close() throws IOException {\n\n pw.flush();\n\n pw.close();\n\n br.close();\n\n }\n\n\n\n int ri() throws IOException {\n\n return Integer.parseInt(br.readLine().trim());\n\n }\n\n\n\n long rl() throws IOException {\n\n return Long.parseLong(br.readLine().trim());\n\n }\n\n\n\n int[] ril(int n) throws IOException {\n\n int[] nums = new int[n];\n\n int c = 0;\n\n for (int i = 0; i < n; i++) {\n\n int sign = 1;\n\n c = br.read();\n\n int x = 0;\n\n if (c == '-') {\n\n sign = -1;\n\n c = br.read();\n\n }\n\n while (c >= '0' && c <= '9') {\n\n x = x * 10 + c - '0';\n\n c = br.read();\n\n }\n\n nums[i] = x * sign;\n\n }\n\n while (c != '\\n' && c != -1) c = br.read();\n\n return nums;\n\n }\n\n\n\n long[] rll(int n) throws IOException {\n\n long[] nums = new long[n];\n\n int c = 0;\n\n for (int i = 0; i < n; i++) {\n\n int sign = 1;\n\n c = br.read();\n\n long x = 0;\n\n if (c == '-') {\n\n sign = -1;\n\n c = br.read();\n\n }\n\n while (c >= '0' && c <= '9') {\n\n x = x * 10 + c - '0';\n\n c = br.read();\n\n }\n\n nums[i] = x * sign;\n\n }\n\n while (c != '\\n' && c != -1) c = br.read();\n\n return nums;\n\n }\n\n\n\n int[] rkil() throws IOException {\n\n int sign = 1;\n\n int c = br.read();\n\n int x = 0;\n\n if (c == '-') {\n\n sign = -1;\n\n c = br.read();\n\n }\n\n while (c >= '0' && c <= '9') {\n\n x = x * 10 + c - '0';\n\n c = br.read();\n\n }\n\n return ril(x);\n\n }\n\n\n\n long[] rkll() throws IOException {\n\n int sign = 1;\n\n int c = br.read();\n\n int x = 0;\n\n if (c == '-') {\n\n sign = -1;\n\n c = br.read();\n\n }\n\n while (c >= '0' && c <= '9') {\n\n x = x * 10 + c - '0';\n\n c = br.read();\n\n }\n\n return rll(x);\n\n }\n\n\n\n char[] rs() throws IOException {\n\n return br.readLine().toCharArray();\n\n }\n\n\n\n void sort(int[] A) {\n\n Random r = new Random();\n\n for (int i = A.length-1; i > 0; i--) {\n\n int j = r.nextInt(i+1);\n\n int temp = A[i];\n\n A[i] = A[j];\n\n A[j] = temp;\n\n }\n\n Arrays.sort(A);\n\n }\n\n\n\n void printDouble(double d) {\n\n pw.printf(\"%.16f\", d);\n\n }\n\n}\n\n\n\nclass Node {\n\n Node zero;\n\n Node one;\n\n}","language":"java"} +{"contest_id":"1286","problem_id":"C2","statement":"C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r \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 \u23080.777(n+1)2\u2309\u23080.777(n+1)2\u2309 (\u2308x\u2309\u2308x\u2309 is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1\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 \u23080.777(n+1)2\u2309\u23080.777(n+1)2\u2309 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","hashing","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.IOException;\n\nimport java.io.InputStreamReader;\n\nimport java.io.BufferedOutputStream;\n\nimport java.io.UncheckedIOException;\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 C1MadhouseEasyVersion solver = new C1MadhouseEasyVersion();\n\n solver.solve(1, in, out);\n\n out.close();\n\n }\n\n\n\n static class C1MadhouseEasyVersion {\n\n public void solve(int testNumber, LightScanner in, LightWriter out) {\n\n \/\/ out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP);\n\n out.enableAutoFlush();\n\n int m = in.ints(), n = (m + 1) \/ 2;\n\n char[] p1 = guess(in, out, 1, n);\n\n char[] ans = new char[m];\n\n if (n == 1) {\n\n ans[0] = p1[0];\n\n } else {\n\n char[] p2 = guess(in, out, 1, n - 1);\n\n int[] cnt = new int[26];\n\n for (int i = 0; i < n; i++) cnt[p1[i] - 'a']++;\n\n for (int i = 0; i < n - 1; i++) cnt[p2[i] - 'a']--;\n\n for (int i = 0; i < 26; i++) if (cnt[i] > 0) ans[n - 1] = (char) (i + 'a');\n\n for (int i = 0; i < n \/ 2; i++) {\n\n if (ans[n - i - 1] != p1[n - i - 1]) ArrayUtil.swap(p1, i, n - i - 1);\n\n ans[i] = p1[i];\n\n if (ans[i] != p2[i]) ArrayUtil.swap(p2, i, n - i - 2);\n\n ans[n - i - 2] = p2[n - i - 2];\n\n }\n\n }\n\n\n\n char[] p3 = guess(in, out, 1, m);\n\n for (int i = 0; i < n; i++) {\n\n if (p3[i] != ans[i]) ArrayUtil.swap(p3, i, m - i - 1);\n\n }\n\n\n\n\n\n out.ans('!').ans(String.valueOf(p3)).ln();\n\n }\n\n\n\n private static char[] guess(LightScanner in, LightWriter out, int from, int to) {\n\n int n = to - from + 1;\n\n if (n == 0) return new char[0];\n\n\n\n out.ans('?').ans(from).ans(to).ln();\n\n int n2 = (n + 1) \/ 2;\n\n int[][] cnt = new int[26][n + 1];\n\n for (int i = 0; i < n * (n + 1) \/ 2; i++) {\n\n char[] s = in.string().toCharArray();\n\n if (s.length < n2) continue;\n\n for (char c : s) cnt[c - 'a'][s.length]++;\n\n }\n\n for (int i = n2; i < n; i++) {\n\n for (int j = 0; j < 26; j++) {\n\n cnt[j][i] -= cnt[j][i + 1];\n\n }\n\n }\n\n for (int i = n; i >= n2 + 1; i--) {\n\n for (int j = 0; j < 26; j++) {\n\n cnt[j][i] -= cnt[j][i - 1];\n\n }\n\n }\n\n\n\n char[] ans = new char[n];\n\n for (int i = 0; i < n; i++) {\n\n int ref = Math.max(n - i, i + 1);\n\n for (int j = 0; j < 26; j++) {\n\n if (cnt[j][ref] > 0) {\n\n cnt[j][ref]--;\n\n ans[i] = (char) ('a' + j);\n\n break;\n\n }\n\n }\n\n }\n\n return ans;\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 }\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 void enableAutoFlush() {\n\n autoflush = true;\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(char c) {\n\n if (!breaked) {\n\n print(' ');\n\n }\n\n return print(c);\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(int i) {\n\n return ans(Integer.toString(i));\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 final class ArrayUtil {\n\n private ArrayUtil() {\n\n }\n\n\n\n public static void swap(char[] a, int x, int y) {\n\n char t = a[x];\n\n a[x] = a[y];\n\n a[y] = t;\n\n }\n\n\n\n }\n\n}\n\n\n\n","language":"java"}