contest_id
stringclasses
33 values
problem_id
stringclasses
14 values
statement
stringclasses
181 values
tags
sequencelengths
1
8
code
stringlengths
21
64.5k
language
stringclasses
3 values
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2 1 2 3 6 3 4 7 8 OutputCopyYES InputCopy3 1 3 2 4 4 5 6 7 3 4 5 5 OutputCopyNO InputCopy6 1 5 2 9 2 4 5 8 3 6 7 11 7 10 12 16 8 11 13 17 9 12 14 18 OutputCopyYES NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.
[ "binary search", "data structures", "hashing", "sortings" ]
import java.io.*; import java.util.*; public class Main{ static int[][]in; static int n; static boolean check() { int[][]events=new int[2*n][4]; for(int i=0;i<n;i++) { events[2*i]=new int[] {in[i][0],0,in[i][2],in[i][3]}; events[2*i+1]=new int[] {in[i][1],1,in[i][2],in[i][3]}; } Arrays.sort(events,(x,y)->x[0]==y[0]?x[1]-y[1]:x[0]-y[0]); TreeMap<Integer, Integer>start=new TreeMap<>(),end=new TreeMap<>(); for(int[] e:events) { if(e[1]==0) {//start point if(end.size()!=0) { int minEnd=end.firstKey(); if(e[2]>minEnd)return false; } if(start.size()!=0) { int maxStart=start.lastKey(); if(e[3]<maxStart)return false; } start.put(e[2], start.getOrDefault(e[2], 0)+1); end.put(e[3], end.getOrDefault(e[3], 0)+1); } else {//end point start.put(e[2], start.get(e[2])-1); if(start.get(e[2])==0)start.remove(e[2]); end.put(e[3], end.get(e[3])-1); if(end.get(e[3])==0)end.remove(e[3]); } } return true; } public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); n=sc.nextInt(); in=new int[n][4]; for(int i=0;i<n;i++)in[i]=sc.intArr(4); boolean ans=check(); for(int i=0;i<n;i++) { int[]tmp=new int[] {in[i][0],in[i][1]}; in[i][0]=in[i][2]; in[i][1]=in[i][3]; in[i][2]=tmp[0]; in[i][3]=tmp[1]; } ans&=check(); pw.println(ans?"YES":"NO"); pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void addX(int[]in,int x) { for(int i=0;i<in.length;i++)in[i]+=x; } static void addX(long[]in,int x) { for(int i=0;i<in.length;i++)in[i]+=x; } }
java
1316
E
E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2 1 16 10 3 18 19 13 15 OutputCopy44 InputCopy6 2 3 78 93 9 17 13 78 80 97 30 52 26 17 56 68 60 36 84 55 OutputCopy377 InputCopy3 2 1 500 498 564 100002 3 422332 2 232323 1 OutputCopy422899 NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.
[ "bitmasks", "dp", "greedy", "sortings" ]
import java.io.*; import java.util.*; public class TeamBuilding { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out, false); int N = in.nextInt(), P = in.nextInt(), K = in.nextInt(); int[][] A = new int[N][2]; for (int i = 0; i < N; i++) { A[i] = new int[]{in.nextInt(), i}; } int[][] S = new int[N][P]; for (int i = 0; i < N; i++) { for (int j = 0; j < P; j++) { S[i][j] = in.nextInt(); } } Arrays.sort(A, (a, b) -> b[0] - a[0]); long[][] dp = new long[N + 1][(1 << P)]; dp[0][0] = 0; for (int i = 1; i <= N; i++) { int idx = A[i - 1][1]; for (int mask = 0; mask < (1 << P); mask++) { int count = i - 1 - Integer.bitCount(mask); if (count >= 0 && count < K) dp[i][mask] = dp[i - 1][mask] + A[i - 1][0]; else dp[i][mask] = dp[i - 1][mask]; for (int j = 0; j < P; j++) { if ((mask & (1 << j)) != 0) { dp[i][mask] = Math.max(dp[i][mask], dp[i - 1][mask ^ (1 << j)] + S[idx][j]); } } } } out.println(dp[N][(1 << P) - 1]); out.close(); System.exit(0); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
java
1311
C
C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3 4 2 abca 1 3 10 5 codeforces 2 8 3 2 9 26 10 qwertyuioplkjhgfdsazxcvbnm 20 10 1 2 3 5 10 5 9 4 OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2 NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.
[ "brute force" ]
import java.io.*; import java.util.*; import static java.lang.System.*; public class M { public static void main(String[] args) { FastScanner x = new FastScanner(); int t = x.nextInt(); // out.println(); while (t-- > 0){ Long max = (long) Integer.MIN_VALUE; Long min = (long)Integer.MAX_VALUE; Long res = 0L; boolean boo = true; int n = x.nextInt(); int m = x.nextInt(); String s = x.nextLine(); int[] cnt = new int[n]; int[] ch = new int[26]; while (m-- > 0){ int h = x.nextInt(); scanline(cnt,0,h - 1); } for (int i = n - 1; i > 0 ;i--) { cnt[i - 1] += cnt[i]; } for (int i = 0;i < n;i++){ ch[s.charAt(i) - 'a'] += cnt[i] + 1; } for (Integer c: ch) { out.print(c + " "); } out.println(); } }static void scanline(int cnt[],int l,int r){ cnt[r]++; } static boolean bin(int[] arr,int target){ int l = 0; int r = arr.length - 1; while (l <= r){ int mid = l + (r - l) / 2; if (arr[mid] == target){ return true; } else if (arr[mid] > target) { r = mid - 1; }else{ l = mid + 1; } }return false; } static Long getmax(Long[] arr){ Long max = (long) Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { max = Math.max(max,arr[i]); }return max; } static String getter(String s, int ind,int len){ char a1 = s.charAt(ind); char a2 = s.charAt(len); StringBuilder res = new StringBuilder(); for (int i = 0; i < s.length(); i++) { if (i == ind){ res.append(a2); } else if (i == len) { res.append(a1); }else{ res.append(s.charAt(i)); } } return res.toString(); } static int shift(Integer[] arr,int l,int r,int k){ Integer[] sarr = new Integer[arr.length]; for (int i = 0; i < arr.length; i++) { sarr[i] = arr[i]; } for (int i = 0; i < k; i++) { for (int j = l - 1; j < r - 1; j++) { arr[j + 1] = arr[j]; } out.println(Arrays.toString(arr)); } return arr[arr.length - 1] - arr[0]; } static int lowerbound(Long[] arr,Long target){ // we can find smallest element in the list that equal or bigger than the target if(arr == null || arr.length == 0){ return -1; } int l = 0; int r = arr.length - 1; while (l < r){ int mid = (l + r) / 2; if (arr[mid] < target){ l = mid + 1; }else{ r = mid; } } if (arr[l] >= target){ return l; } return -1; } static int upperbound(Long[] arr,Long target){ // we can find smallest element in the list that bigger than the target if (arr == null || arr.length == 0){ return -1; } int l = 0; int r = arr.length - 1; while (l < r){ int mid = (l + r) / 2; if (arr[mid] <= target){ l = mid + 1; }else { r = mid; } } return arr[l] > target ? l : -1; } public static void rec(int N,String cur) { if (cur.length() == N) { out.println(cur); return; } rec(N, cur + "0"); rec(N, cur + "1"); rec(N,cur + "2"); } public static int intfromstring(String s){ String[] nums = {"zero","one","two","three","four","five","six","seven","eight","nine","ten"}; for (int i = 0; i < nums.length; i++) { if (s.equals(nums[i])){ return i; } }return -1; } public static long NOK(long a,long b){ return lcm(a,b); }static long gcd(long a,long b){ return b == 0 ? a : gcd(b,a % b); }static long lcm(long a,long b){ return a / gcd(a,b) * b; } public static long sum(long a){ return a * (a - 1) / 2; } static boolean odd(int e){ return e % 2 == 1; }static boolean even(int e){ return e % 2 == 0; } static boolean isPrime(long n) { if (n <= 1){ return false;} if (n <= 3){ return true;} if (n % 2 == 0 || n % 3 == 0){ return false;} for (int i = 5; (long) i * i <= n; i = i + 6){ if (n % i == 0 || n % (i + 2) == 0){ return false;}} return true; }static String arrtostring(long res[]){ return Arrays.toString(res).replace(",","").replace("[","").replace("]",""); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextLine() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextLine()); } long nextLong() { return Long.parseLong(nextLine()); } double nextDouble() { return Double.parseDouble(nextLine()); } Integer[] readArray(int n) { Integer[] a=new Integer[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } Long[] readArrayLong(int n) { Long[] a=new Long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } }
java
1303
D
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3 10 3 1 32 1 23 4 16 1 4 1 20 5 2 1 16 1 8 OutputCopy2 -1 0
[ "bitmasks", "greedy" ]
import java.io.*; import java.math.*; import java.util.*; public class test { static class Pair { int x; int y; Pair(int x, int y) { this.x = x; this.y = y; } } static class Compare { void compare(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if (p1.x != p2.x) { return (int) (p1.x - p2.x); } else { return (int) (p1.y - p2.y); } // return Double.compare(a[0], b[0]); } }); // for (int i = 0; i < n; i++) { // System.out.print(arr[i].x + " " + arr[i].y + " "); // } // System.out.println(); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int function(int freq[] , int pos) { int nextIndex = -1; for(int i = pos + 1;i<freq.length;i++) { if(freq[i] != 0) { nextIndex = i; break; } } if(nextIndex == -1) { return nextIndex; } freq[nextIndex]--; for(int i = nextIndex-1 ; i>=pos;i--) { freq[i]++; } freq[pos]++; return nextIndex - pos; } public static void main(String args[]) throws Exception { Scanner sc = new Scanner(); StringBuilder res = new StringBuilder(); int tc = sc.nextInt(); while (tc-- > 0) { long n = sc.nextLong(); int m = sc.nextInt(); long a[] = new long[m]; for(int i=0;i<m;i++) { a[i] = sc.nextLong(); } int freq[] = new int[64]; for(int i=0;i<m;i++) { for(int j=0;j<64;j++) { if(((1L << j) & a[i] )!= 0) { freq[j]++; break; } } } int cnt = 0; for(int i=0;i<64;i++) { int set = ((1L << i) & n )!= 0 ? 1 : 0; if(set == 1) { if(freq[i] != 0) { freq[i]--; int nextFill = freq[i] / 2; freq[i] = freq[i] % 2; freq[Math.min(63, i+1)] += nextFill; } else { int add = function(freq,i); if(add == -1) { cnt = -1; break; } else { cnt += add; } } } else { int nextFill = freq[i] / 2; freq[i] = freq[i] % 2; freq[Math.min(63, i+1)] += nextFill; } } res.append(cnt+"\n"); } System.out.println(res); } }
java
1290
B
B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa 3 1 1 2 4 5 5 OutputCopyYes No Yes InputCopyaabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 OutputCopyNo Yes Yes Yes No No NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.
[ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ]
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class IrreducibleAnagrams { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = 1; for (int i = 0; i < t; i++) { solve(sc, pw); } pw.close(); } //three situations // when len is 1 so that you do not have irre anagram // when leftmost pos and rightmost pos is same, we could see that is we move all the character at rightmost pos to the left, that is a good situation // when left and right pos are same, then we need at least three character, the logic is almost same as above mentioned static void solve(Scanner in, PrintWriter out){ String s = in.next(); char[] cs = s.toCharArray(); int n = cs.length; int qq = in.nextInt(); int[][] qs = new int[qq][]; for (int i = 0; i < qq; i++) { qs[i] = new int[]{in.nextInt() - 1, in.nextInt() - 1}; } int[][] dp = new int[n + 1][26]; for (int i = 0; i < n; i++) { dp[i + 1] = Arrays.copyOf(dp[i], 26); dp[i + 1][cs[i] - 'a']++; } for(int[] q : qs){ int l = q[0], r = q[1]; int[] neo = new int[26]; int cnt = 0; int max = 0; for (int i = 0; i < 26; i++) { neo[i] = dp[r + 1][i] - dp[l][i]; if (neo[i] > 0) cnt++; max = Math.max(max, neo[i]); } if (r - l + 1 == 1){ out.println("YES"); }else if (cs[l] != cs[r]){ out.println("YES"); }else if (cs[l] == cs[r] && cnt > 2){ out.println("YES"); }else{ out.println("NO"); } } } }
java
1313
C1
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "brute force", "data structures", "dp", "greedy" ]
//Some of the methods are copied from GeeksforGeeks Website import java.util.*; import java.lang.*; import java.io.*; public class C_1_Skyscrapers_easy_version { //static Scanner sc=new Scanner(System.in); //static Reader sc=new Reader(); static FastReader sc=new FastReader(System.in); static long mod = (long)(1e9)+ 7; static int max_num=(int)1e5+5; public static void main (String[] args) throws java.lang.Exception { try{ /* Collections.sort(al,(a,b)->a.x-b.x); Collections.sort(al,Collections.reverseOrder()); StringBuilder sb=new StringBuilder(""); sb.append(cur); sb=sb.reverse(); String rev=sb.toString(); long n=sc.nextLong(); String s=sc.next(); char a[]=s.toCharArray(); StringBuilder sb=new StringBuilder(); map.put(a[i],map.getOrDefault(a[i],0)+1); map.putIfAbsent(x,new ArrayList<>()); out.println("Case #"+tt+": "+ans ); */ int t =1;// sc.nextInt(); for(int tt=1;tt<=t;tt++) { int n=sc.nextInt(); long a[]=new long[n]; for(int i=0;i<n;i++) { a[i]=sc.nextLong(); } long max=0; int point=0; long res[]=new long[n]; for(int i=0;i<n;i++) { long c[]=new long[n]; c[i]=a[i]; for(int j=i-1;j>=0;j--) { long cur=a[j]; long min=Math.min(cur,c[j+1]); c[j]=min; } for(int j=i+1;j<n;j++) { long cur=a[j]; long min=Math.min(cur,c[j-1]); c[j]=min; } long sum=sum_array(c); if(sum>max) { max=sum; point=i; res=c; } } // long ans[]=new long[n]; // ans[point]=a[point]; // for(int j=point-1;j>=0;j--) // { // long cur=a[j]; // long min=Math.min(cur,ans[j+1]); // ans[j]=min; // } // for(int j=point+1;j<n;j++) // { // long cur=a[j]; // long min=Math.min(cur,ans[j-1]); // ans[j]=min; // } // print(ans); print(res); } out.flush(); out.close(); } catch(Exception e) {} } /* ...SOLUTION ENDS HERE...........SOLUTION ENDS HERE... */ static void flag(boolean flag) { out.println(flag ? "YES" : "NO"); out.flush(); } /* Map<Long,Long> map=new HashMap<>(); for(int i=0;i<n;i++) { if(!map.containsKey(a[i])) map.put(a[i],1); else map.replace(a[i],map.get(a[i])+1); } Set<Map.Entry<Long,Long>> hmap=map.entrySet(); for(Map.Entry<Long,Long> data : hmap) { } Iterator<Integer> itr = set.iterator(); while(itr.hasNext()) { int val=itr.next(); } */ // static class Pair // { // int x,y; // Pair(int x,int y) // { // this.x=x; // this.y=y; // } // } // Arrays.sort(p, new Comparator<Pair>() // { // @Override // public int compare(Pair o1,Pair o2) // { // if(o1.x>o2.x) return 1; // else if(o1.x==o2.x) // { // if(o1.y>o2.y) return 1; // else return -1; // } // else return -1; // }}); static void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print_int(ArrayList<Integer> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void print_long(ArrayList<Long> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void pn(int x) { out.println(x); out.flush(); } static void pn(long x) { out.println(x); out.flush(); } static void pn(String x) { out.println(x); out.flush(); } static int LowerBound(int a[], int x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } static int UpperBound(int a[], int x) {// x is the key or target value int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } static void DFS(ArrayList<Integer> graph[],boolean[] visited, int u) { visited[u]=true; int v=0; for(int i=0;i<graph[u].size();i++) { v=graph[u].get(i); if(!visited[v]) DFS(graph,visited,v); } } static boolean[] prime(int num) { boolean[] bool = new boolean[num]; for (int i = 0; i< bool.length; i++) { bool[i] = true; } for (int i = 2; i< Math.sqrt(num); i++) { if(bool[i] == true) { for(int j = (i*i); j<num; j = j+i) { bool[j] = false; } } } if(num >= 0) { bool[0] = false; bool[1] = false; } return bool; } static long nCr(long a,long b,long mod) { return (((fact[(int)a] * modInverse(fact[(int)b],mod))%mod * modInverse(fact[(int)(a - b)],mod))%mod + mod)%mod; } static long fact[]=new long[max_num]; static void fact_fill() { fact[0]=1l; for(int i=1;i<max_num;i++) { fact[i]=(fact[i-1]*(long)i); if(fact[i]>=mod) fact[i]%=mod; } } static long modInverse(long a, long m) { return power(a, m - 2, m); } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (long)((p * (long)p) % m); if (y % 2 == 0) return p; else return (long)((x * (long)p) % m); } static long sum_array(int a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static long sum_array(long a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void reverse_array(int a[]) { int n=a.length; int i,t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static void reverse_array(long a[]) { int n=a.length; int i; long t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } static class FastReader{ byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static PrintWriter out=new PrintWriter(System.out); static int int_max=Integer.MAX_VALUE; static int int_min=Integer.MIN_VALUE; static long long_max=Long.MAX_VALUE; static long long_min=Long.MIN_VALUE; } // Thank You !
java
1290
C
C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n)  — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n)  — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi  — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 OutputCopy1 2 3 3 3 3 3 InputCopy8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 OutputCopy1 1 1 1 1 1 4 4 InputCopy5 3 00011 3 1 2 3 1 4 3 3 4 5 OutputCopy1 1 1 1 1 InputCopy19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 OutputCopy0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111.
[ "dfs and similar", "dsu", "graphs" ]
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class A { FastScanner in; PrintWriter out; int[] parent; int[] parentSameColor; int[] sizeWhite; int[] sizeBlack; boolean[] canChangeColor; int[] color; int res; int getRoot(int id) { if (parent[id] != id) { getColor(parent[id]); parentSameColor[id] ^= parentSameColor[parent[id]]; parent[id] = parent[parent[id]]; } return parent[id]; } int getColor(int id) { if (parent[id] != id) { getColor(parent[id]); parentSameColor[id] ^= parentSameColor[parent[id]]; parent[id] = parent[parent[id]]; } return color[parent[id]] ^ parentSameColor[id]; } void fixColor(int v) { v = getRoot(v); canChangeColor[v] = false; } void swapColor(int v) { v = getRoot(v); if (!canChangeColor[v]) { throw new AssertionError(); } res -= sizeBlack[v]; res += sizeWhite[v]; int tmp = sizeBlack[v]; sizeBlack[v] = sizeWhite[v]; sizeWhite[v] = tmp; color[v] = 1 - color[v]; } void solve() { int n = in.nextInt(); int k = in.nextInt(); boolean[] on = new boolean[n]; String s = in.next(); for (int i = 0; i < n; i++) { on[i] = s.charAt(i) == '1'; } List<Integer>[] g = new List[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(); } for (int i = 0; i < k; i++) { int cnt = in.nextInt(); for (int j = 0; j < cnt; j++) { g[in.nextInt() - 1].add(i); } } parent = new int[k]; color =new int[k]; for (int i = 0; i < k; i++) { parent[i] = i; } parentSameColor = new int[k]; sizeBlack = new int[k]; sizeWhite = new int[k]; Arrays.fill(sizeWhite, 1); canChangeColor = new boolean[k]; Arrays.fill(canChangeColor, true); for (int i = 0; i < n; i++) { int curColor = on[i] ? 1 : 0; if (g[i].isEmpty()) { if (curColor != 1) { throw new AssertionError(); } } else if (g[i].size() == 1) { int comp = g[i].get(0); curColor ^= getColor(comp); if (curColor != 1) { swapColor(comp); } fixColor(comp); } else if (g[i].size() == 2) { int v1 = g[i].get(0), v2 = g[i].get(1); curColor ^= getColor(v1); curColor ^= getColor(v2); v1 = getRoot(v1); v2 = getRoot(v2); if (curColor != 1) { if (v1 == v2) { throw new AssertionError(); } if (!canChangeColor[v1] && !canChangeColor[v2]) { throw new AssertionError(); } if (!canChangeColor[v1]) { swapColor(v2); } else if (!canChangeColor[v2]) { swapColor(v1); } else { int v1SwapCost = sizeWhite[v1] - sizeBlack[v1]; int v2SwapCost = sizeWhite[v2] - sizeBlack[v2]; if (v1SwapCost < v2SwapCost) { swapColor(v1); } else { swapColor(v2); } } } if (v1 != v2) { parentSameColor[v1] = getColor(v1) ^ getColor(v2); parent[v1] = v2; // if (parentSameColor[v1] == 0) { sizeBlack[v2] += sizeBlack[v1]; sizeWhite[v2] += sizeWhite[v1]; // } else { // sizeBlack[v2] += sizeWhite[v1]; // sizeWhite[v2] += sizeBlack[v1]; // } canChangeColor[v2] &= canChangeColor[v1]; } } else { throw new AssertionError(); } out.println(res); // System.err.println(i + " " + res + " " + Arrays.toString(parent) + " " + Arrays.toString(sizeWhite) + " " + Arrays.toString(sizeBlack)); } } void run() { try { in = new FastScanner(new File("A.in")); out = new PrintWriter(new File("A.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new A().runIO(); } }
java
1292
C
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−1n−1 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−2n−2 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=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3 1 2 2 3 OutputCopy3 InputCopy5 1 2 1 3 1 4 3 5 OutputCopy10 NoteIn the first example; one can achieve the maximum SS with the following assignment: With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment: With this assignment, all non-zero mex value are listed below: mex(1,3)=1mex(1,3)=1 mex(1,5)=2mex(1,5)=2 mex(2,3)=1mex(2,3)=1 mex(2,5)=2mex(2,5)=2 mex(3,4)=1mex(3,4)=1 mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10.
[ "combinatorics", "dfs and similar", "dp", "greedy", "trees" ]
import java.util.*; import java.io.*; import static java.lang.Math.*; public class test { final static int MOD = 1000000007; final static int intMax = 1000000000; final static int intMin = -1000000000; final static int[] dx = { 0, 0, -1, 1 }; final static int[] dy = { -1, 1, 0, 0 }; static int add(int a, int b) { return (a + b) % MOD; } static int sub(int a, int b) { return (a - b + MOD) % MOD; } static int mult(int a, int b) { return (int)((((long)(a)) * b) % MOD); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[360]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static class Sb_Output implements Closeable, Flushable{ StringBuilder sb; OutputStream os; int BUFFER_SIZE; public Sb_Output(String s) throws Exception { os = new BufferedOutputStream(new FileOutputStream(new File(s))); BUFFER_SIZE = 1 << 16; sb = new StringBuilder(BUFFER_SIZE); } public void print(String s) { sb.append(s); if(sb.length() >= (BUFFER_SIZE>>1)) { flush(); } } public void println(String s) { print(s); print("\n"); } public void println(int i) { println("" + i); } public void println(long i) { println("" + i); } public void flush() { try { os.write(sb.toString().getBytes()); sb = new StringBuilder(BUFFER_SIZE); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static ArrayList<Integer>[] adj; static long results[][]; public static void main(String[] args) throws Exception { Reader in = new Reader(); // Reader in = new Reader("poetry.in"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // BufferedReader br = new BufferedReader(new FileReader("poetry.in")); int n = Integer.parseInt(br.readLine()); adj = new ArrayList[n]; for(int i = 0; i < n; ++i) { adj[i] = new ArrayList<Integer>(); } for(int i = 0; i< n - 1; ++i) { StringTokenizer st = new StringTokenizer(br.readLine()); int u = Integer.parseInt(st.nextToken()) - 1; int v = Integer.parseInt(st.nextToken()) - 1; adj[u].add(v); adj[v].add(u); } sz = new int[n]; cpar = new int[n]; vis = new boolean[n]; results = new long[n][n]; for(int i = 0; i < n; ++i){ Arrays.fill(results[i], -1); } long ret = 0; for(int cnd = 0; cnd < n; ++cnd){ long ans = 0; dfs(cnd, -1); int mx = 0, mxind = 0; for(int i : adj[cnd]) { if(sz[i] > mx) { mx = sz[i]; mxind = i; } } ans += (long) mx * (n - mx); //System.out.println(mx); long max = 0; sz[cnd] = n - mx; for(int i : adj[cnd]) { if(i == mxind) continue; max = max(max, solve(i, cnd, mxind, cnd)); } for(int i : adj[mxind]) { if(i == cnd) continue; max = max(max, solve(i, mxind, cnd, mxind)); //System.out.println(solve(i, mxind, cnd, mxind)); } ret = max(ret, max + ans); } System.out.println(ret); in.close(); //out.close(); } static long solve(int d1, int p1, int d2, int p2) { if(results[d1][d2] != -1) { return results[d1][d2]; } long mx = 0; for(int i : adj[d1]) { if(i == p1 || i == d2) continue; mx = max(mx, solve(i, d1, d2, p2)); } for(int i : adj[d2]) { if(i == p2 || i == d1) continue; mx = max(mx, solve(d1, p1, i, d2)); } //if(d1 == 3 && d2 == 4) System.out.println(mx); //System.out.println(d1 + " " + p1 + " " + d2 + " " + p2 + " " + mx); results[d1][d2] = results[d2][d1] = mx + (long) sz[d1] * sz[d2]; return mx + (long) sz[d1] * sz[d2]; } static class pair{ int x, y, same; pair(int a, int b) { x = a; y = b; same = 0; } } static int[] sz, cpar; static boolean vis[]; static int curans; static void dfs(int n, int p) { sz[n] = 1; for (int v : adj[n]) if (v != p && !vis[v]) { dfs(v, n); sz[n] += sz[v]; } } static int centroid(int n) { dfs(n, -1); int num = sz[n]; int p = -1; do { int nxt = -1; for (int v : adj[n]) if (v != p && !vis[v]) { if (2 * sz[v] > num) nxt = v; } p = n; n = nxt; } while (~n != 0); return p; } static void centroid_decomp(int n, int p) { int c = centroid(n); vis[c] = true; cpar[c] = p; for (int v : adj[c]) if (!vis[v]) { centroid_decomp(v, c); } } }
java
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3 -2 1 OutputCopy3 1 2 InputCopy5 1 1 1 1 OutputCopy1 2 3 4 5 InputCopy4 -1 2 2 OutputCopy-1
[ "math" ]
/* "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." Just have Patience + 1... */ import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = 1; for (int t = 1; t <= test; t++) { solve(); } out.close(); } private static void solve() { int n = sc.nextInt(); int[] differences = new int[n - 1]; for (int i = 0; i < n - 1; i++) { differences[i] = sc.nextInt(); } long[] permutation = new long[n]; for (int i = 1; i < n; i++) { permutation[i] = permutation[i - 1] + differences[i - 1]; } long minVal = 0; for (int i = 0; i < n; i++) { if (permutation[i] < minVal) { minVal = permutation[i]; } } HashSet<Long> set = new HashSet<>(); long add = 1 - minVal; for (int i = 0; i < n; i++) { permutation[i] += add; if (permutation[i] < 1 || permutation[i] > n) { out.println(-1); return; } set.add(permutation[i]); } if (set.size() != n) { out.println(-1); return; } for (int i = 0; i < n; i++) { out.print(permutation[i] + " "); } out.println(); } public static FastReader sc; public static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } } return str.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } return str; } } }
java
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
import java.io.*; import java.text.DecimalFormat; import java.util.*; public class Main { static class Pair { long a,b; public Pair(long a,long b) { this.a=a; this.b=b; } // @Override // public int compareTo(Pair p) { // return Long.compare(l, p.l); // } } static final int INF = 1 << 30; static final long INFL = 1L << 60; static final long NINF = INFL * -1; static final long mod = (long) 1e9 + 7; static final long mod2 = 998244353; static DecimalFormat df = new DecimalFormat("0.00000000000000"); public static final double PI = 3.141592653589793d, eps = 1e-9; public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { static int N=150005; static ArrayList<Integer>[] adj=new ArrayList[N]; static boolean[] vis=new boolean[N]; static ArrayList<Integer> al=new ArrayList<>(); //static int cnt=0; static void dfs(int src,int par) { vis[src]=true; al.add(src); for(int ch:adj[src]) { if(!vis[ch] && ch!=par) { dfs(ch,src); } } } public static void solve(int testNumber, InputReader in, OutputWriter out) { //int t = in.ni(); int t=1; while (t-->0) { int n=in.ni(); int[] deg=new int[n]; int[] from=new int[n]; int[] ans=new int[n-1]; int[] to=new int[n]; for(int i=0;i<n-1;i++) { from[i]=in.ni()-1; to[i]=in.ni()-1; int u=from[i]; int v=to[i]; ++deg[u]; ++deg[v]; } if(n==2) { out.printLine(0); continue; } int f=0,cnt=0; HashSet<Integer> set=new HashSet<>(); for(int i=0;i<n;i++) { if(deg[i]==1) { set.add(i); } } Arrays.fill(ans,-1); for(int i=0;i<n-1;++i) { if(set.contains(from[i]) || set.contains(to[i])) { ans[i]=cnt++; } } for(int i=0;i<n-1;++i) { if(ans[i]==-1) { ans[i]=cnt++; } } for(int i:ans) { out.printLine(i); } } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private char nc() { return (char)skip(); } public int[] na(int arraySize) { int[] array = new int[arraySize]; for (int i = 0; i < arraySize; i++) { array[i] = ni(); } return array; } private int skip() { int b; while ((b = read()) != -1 && isSpaceChar(b)) ; return b; } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = read(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } int[][] nim(int h, int w) { int[][] a = new int[h][w]; for (int i = 0; i < h; i++) { a[i] = na(w); } return a; } long[][] nlm(int h, int w) { long[][] a = new long[h][w]; for (int i = 0; i < h; i++) { a[i] = nla(w); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isNewLine(int c) { return c == '\n'; } public String nextLine() { int c = read(); StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (!isNewLine(c)); return result.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sign = 1; if (c == '-') { sign = -1; c = read(); } long result = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } result *= 10; result += c & 15; c = read(); } while (!isSpaceChar(c)); return result * sign; } public long[] nla(int arraySize) { long array[] = new long[arraySize]; for (int i = 0; i < arraySize; i++) { array[i] = nextLong(); } return array; } public double nextDouble() { double ret = 0, div = 1; byte c = (byte) read(); while (c <= ' ') { c = (byte) read(); } boolean neg = (c == '-'); if (neg) { c = (byte) read(); } do { ret = ret * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') { while ((c = (byte) read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } } public static class CP { static boolean isPrime(long n) { if (n <= 1) return false; if (n == 2 || n == 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; (long) i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true; } public static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } public static long pow(long a, long n, long mod) { // a %= mod; long ret = 1; int x = 63 - Long.numberOfLeadingZeros(n); for (; x >= 0; x--) { ret = ret * ret % mod; if (n << 63 - x < 0) ret = ret * a % mod; } return ret; } public static boolean isComposite(long n) { if (n < 2) return true; if (n == 2 || n == 3) return false; if (n % 2 == 0 || n % 3 == 0) return true; for (long i = 6L; i * i <= n; i += 6) if (n % (i - 1) == 0 || n % (i + 1) == 0) return true; return false; } static int ifnotPrime(int[] prime, int x) { return (prime[x / 64] & (1 << ((x >> 1) & 31))); } static long log2(long n) { return (long)(Math.log10(n) / Math.log10(2L)); } static void makeComposite(int[] prime, int x) { prime[x / 64] |= (1 << ((x >> 1) & 31)); } public static String swap(String a, int i, int j) { char temp; char[] charArray = a.toCharArray(); temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = temp; return String.valueOf(charArray); } static void reverse(long arr[]){ int l = 0, r = arr.length-1; while(l<r){ long temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; l++; r--; } } static void reverse(int arr[]){ int l = 0, r = arr.length-1; while(l<r){ int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; l++; r--; } } public static int[] sieveEratosthenes(int n) { if (n <= 32) { int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int i = 0; i < primes.length; i++) { if (n < primes[i]) { return Arrays.copyOf(primes, i); } } return primes; } int u = n + 32; double lu = Math.log(u); int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)]; ret[0] = 2; int pos = 1; int[] isnp = new int[(n + 1) / 32 / 2 + 1]; int sup = (n + 1) / 32 / 2 + 1; int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int tp : tprimes) { ret[pos++] = tp; int[] ptn = new int[tp]; for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31); for (int j = 0; j < sup; j += tp) { for (int i = 0; i < tp && i + j < sup; i++) { isnp[j + i] |= ptn[i]; } } } // 3,5,7 // 2x+3=n int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14}; int h = n / 2; for (int i = 0; i < sup; i++) { for (int j = ~isnp[i]; j != 0; j &= j - 1) { int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27]; int p = 2 * pp + 3; if (p > n) break; ret[pos++] = p; if ((long) p * p > n) continue; for (int q = (p * p - 3) / 2; q <= h; q += p) isnp[q >> 5] |= 1 << q; } } return Arrays.copyOf(ret, pos); } static long digit(long s) { long brute = 0; while (s > 0) { brute+=s%10; s /= 10; } return brute; } public static int[] primefacts(int n, int[] primes) { int[] ret = new int[15]; int rp = 0; for (int p : primes) { if (p * p > n) break; int i; for (i = 0; n % p == 0; n /= p, i++) ; if (i > 0) ret[rp++] = p; } if (n != 1) ret[rp++] = n; return Arrays.copyOf(ret, rp); } static ArrayList<Integer> bitWiseSieve(int n) { ArrayList<Integer> al = new ArrayList<>(); int prime[] = new int[n / 64 + 1]; for (int i = 3; i * i <= n; i += 2) { if (ifnotPrime(prime, i) == 0) for (int j = i * i, k = i << 1; j < n; j += k) makeComposite(prime, j); } al.add(2); for (int i = 3; i <= n; i += 2) if (ifnotPrime(prime, i) == 0) al.add(i); return al; } public static long[] sort(long arr[]) { List<Long> list = new ArrayList<>(); for (long n : arr) { list.add(n); } Collections.sort(list); for (int i = 0; i < arr.length; i++) { arr[i] = list.get(i); } return arr; } public static long[] revsort(long[] arr) { List<Long> list = new ArrayList<>(); for (long n : arr) { list.add(n); } Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < arr.length; i++) { arr[i] = list.get(i); } return arr; } public static int[] revsort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int n : arr) { list.add(n); } Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < arr.length; i++) { arr[i] = list.get(i); } return arr; } public static ArrayList<Integer> reverse( ArrayList<Integer> data, int left, int right) { // Reverse the sub-array while (left < right) { int temp = data.get(left); data.set(left++, data.get(right)); data.set(right--, temp); } // Return the updated array return data; } static ArrayList<Integer> sieve(long size) { ArrayList<Integer> pr = new ArrayList<Integer>(); boolean prime[] = new boolean[(int) size]; for (int i = 2; i < prime.length; i++) prime[i] = true; for (int i = 2; i * i < prime.length; i++) { if (prime[i]) { for (int j = i * i; j < prime.length; j += i) { prime[j] = false; } } } for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i); return pr; } static boolean[] sieve1(long size) { ArrayList<Integer> pr = new ArrayList<Integer>(); boolean prime[] = new boolean[(int) size]; for (int i = 2; i < prime.length; i++) prime[i] = true; for (int i = 2; i * i < prime.length; i++) { if (prime[i]) { for (int j = i * i; j < prime.length; j += i) { prime[j] = false; } } } //for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i); return prime; } static ArrayList<Integer> segmented_sieve(int l, int r, ArrayList<Integer> primes) { ArrayList<Integer> al = new ArrayList<>(); if (l == 1) ++l; int max = r - l + 1; int arr[] = new int[max]; for (int p : primes) { if (p * p <= r) { int i = (l / p) * p; if (i < l) i += p; for (; i <= r; i += p) { if (i != p) { arr[i - l] = 1; } } } } for (int i = 0; i < max; ++i) { if (arr[i] == 0) { al.add(l + i); } } return al; } static boolean isfPrime(long n, int iteration) { if (n == 0 || n == 1) return false; if (n == 2) return true; if (n % 2 == 0) return false; Random rand = new Random(); for (int i = 0; i < iteration; i++) { long r = Math.abs(rand.nextLong()); long a = r % (n - 1) + 1; if (modPow(a, n - 1, n) != 1) return false; } return true; } static long modPow(long a, long b, long c) { long res = 1; for (int i = 0; i < b; i++) { res *= a; res %= c; } return res % c; } private static long binPower(long a, long l, long mod) { long res = 0; while (l > 0) { if ((l & 1) == 1) { res = mulmod(res, a, mod); l >>= 1; } a = mulmod(a, a, mod); } return res; } private static long mulmod(long a, long b, long c) { long x = 0, y = a % c; while (b > 0) { if (b % 2 == 1) { x = (x + y) % c; } y = (y * 2L) % c; b /= 2; } return x % c; } static long binary_Expo(long a, long b) { long res = 1; while (b != 0) { if ((b & 1) == 1) { res *= a; --b; } a *= a; b /= 2; } return res; } static void swap(int a, int b) { int tp = b; b = a; a = tp; } static long Modular_Expo(long a, long b, long mod) { long res = 1; while (b != 0) { if ((b & 1) == 1) { res = (res * a) % mod; --b; } a = (a * a) % mod; b /= 2; } return res % mod; } static int i_gcd(int a, int b) { while (true) { if (b == 0) return a; int c = a; a = b; b = c % b; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static int gcd(int a,int b) { if (b == 0) return a; return gcd(b, a % b); } static long ceil_div(long a, long b) { return (a + b - 1) / b; } static int getIthBitFromInt(int bits, int i) { return (bits >> (i - 1)) & 1; } static long getIthBitFromLong(long bits, int i) { return (bits >> (i - 1)) & 1; } static boolean isPerfectSquare(long a) { long sq=(long)(Math.floor(Math.sqrt(a))*Math.floor(Math.sqrt(a))); return sq==a; } private static TreeMap<Long, Long> primeFactorize(long n) { TreeMap<Long, Long> pf = new TreeMap<>(Collections.reverseOrder()); long cnt = 0; long total = 1; for (long i = 2; (long) i * i <= n; ++i) { if (n % i == 0) { cnt = 0; while (n % i == 0) { ++cnt; n /= i; } pf.put(cnt, i); //total*=(cnt+1); } } if (n > 1) { pf.put(1L, n); //total*=2; } return pf; } //less than or equal private static int lower_bound(ArrayList<Long> list, long val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(int[] arr, int val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(long[] arr, long val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid]>=val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } // greater than or equal private static int upper_bound(List<Integer> list, int val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(int[] arr, int val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(long[] arr, long val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } // ==================== LIS & LNDS ================================ private static int[] LIS(long arr[], int n) { List<Long> list = new ArrayList<>(); int[] cnt=new int[n]; for (int i = 0; i < n; i++) { int idx = find1(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); cnt[i]=list.size(); } return cnt; } private static int find1(List<Long> list, long val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid)>=val) { ret = mid; j = mid - 1; } else { i = mid + 1; } } return ret; } private static int LNDS(int[] arr, int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find2(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find2(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) <= val) { i = mid + 1; } else { ret = mid; j = mid - 1; } } return ret; } private static long nCr(long n, long r,long mod) { if (n - r > r) r = n - r; long ans = 1L; for (long i = r + 1; i <= n; i++) ans = (ans%mod*i%mod)%mod; for (long i = 2; i <= n - r; i++) ans /= i; return ans%mod; } private static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) if (str.charAt(i++) != str.charAt(j--)) return false; return true; } static ArrayList<StringBuilder> permutations(StringBuilder s) { int n=s.length(); ArrayList<StringBuilder> al=new ArrayList<>(); getpermute(s,al,0,n); return al; } // static String longestPalindrome(String s) // { // int st=0,ans=0,len=0; // // // } static void getpermute(StringBuilder s,ArrayList<StringBuilder> al,int l, int r) { if(l==r) { al.add(s); return; } for(int i=l+1;i<r;++i) { char c=s.charAt(i); s.setCharAt(i,s.charAt(l)); s.setCharAt(l,c); getpermute(s,al,l+1,r); c=s.charAt(i); s.setCharAt(i,s.charAt(l)); s.setCharAt(l,c); } } static void initStringHash(String s,long[] dp,long[] inv,long p) { long pow=1; inv[0]=1; int n=s.length(); dp[0]=((s.charAt(0)-'a')+1); for(int i=1;i<n;++i) { pow=(pow*p)%mod; dp[i]=(dp[i-1]+((s.charAt(i)-'a')+1)*pow)%mod; inv[i]=CP.modinv(pow,mod)%mod; } } static long getStringHash(long[] dp,long[] inv,int l,int r) { long ans=dp[r]; if(l-1>=0) { ans-=dp[l-1]; } ans=(ans*inv[l])%mod; return ans; } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } private static String sortString(String str) { int[] arr = new int[256]; for (char ch : str.toCharArray()) arr[ch]++; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 256; i++) while (arr[i]-- > 0) sb.append((char) i); return sb.toString(); } static boolean isSquarefactor(int x, int factor, int target) { int s = (int) Math.round(Math.sqrt(x)); return factor * s * s == target; } static boolean isSquare(long x) { long s = (long) Math.round(Math.sqrt(x)); return x * x == s; } static int bs(ArrayList<Integer> al, int val) { int l = 0, h = al.size() - 1, mid = 0, ans = -1; while (l <= h) { mid = (l + h) >> 1; if (al.get(mid) == val) { return mid; } else if (al.get(mid) > val) { h = mid - 1; } else { l = mid + 1; } } return ans; } static void sort(int a[]) // heap sort { PriorityQueue<Integer> q = new PriorityQueue<>(); for (int i = 0; i < a.length; i++) q.add(a[i]); for (int i = 0; i < a.length; i++) a[i] = q.poll(); } static void shuffle(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * in.length); fast_swap(in, idx, i); } } public static int[] radixSort2(int[] a) { int n = a.length; int[] c0 = new int[0x101]; int[] c1 = new int[0x101]; int[] c2 = new int[0x101]; int[] c3 = new int[0x101]; for (int v : a) { c0[(v & 0xff) + 1]++; c1[(v >>> 8 & 0xff) + 1]++; c2[(v >>> 16 & 0xff) + 1]++; c3[(v >>> 24 ^ 0x80) + 1]++; } for (int i = 0; i < 0xff; i++) { c0[i + 1] += c0[i]; c1[i + 1] += c1[i]; c2[i + 1] += c2[i]; c3[i + 1] += c3[i]; } int[] t = new int[n]; for (int v : a) t[c0[v & 0xff]++] = v; for (int v : t) a[c1[v >>> 8 & 0xff]++] = v; for (int v : a) t[c2[v >>> 16 & 0xff]++] = v; for (int v : t) a[c3[v >>> 24 ^ 0x80]++] = v; return a; } static int[] computeLps(String pat) { int len = 0, i = 1, m = pat.length(); int lps[] = new int[m]; lps[0] = 0; while (i < m) { if (pat.charAt(i) == pat.charAt(len)) { ++len; lps[i] = len; ++i; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = len; ++i; } } } return lps; } static ArrayList<Integer> kmp(String s, String pat) { ArrayList<Integer> al = new ArrayList<>(); int n = s.length(), m = pat.length(); int lps[] = computeLps(pat); int i = 0, j = 0; while (i < n) { if (s.charAt(i) == pat.charAt(j)) { i++; j++; if (j == m) { al.add(i - j); j = lps[j - 1]; } } else { if (j != 0) { j = lps[j - 1]; } else { i++; } } } return al; } static void reverse_ruffle_sort(int a[]) { shuffle(a); Arrays.sort(a); for (int l = 0, r = a.length - 1; l < r; ++l, --r) fast_swap(a, l, r); } static void ruffle_sort(int a[]) { shuffle(a); Arrays.sort(a); } static int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } static ArrayList<Long> primeFact(long n) { ArrayList<Long> al = new ArrayList<>(); al.add(1L); while (n % 2 == 0) { if (!al.contains(2L)) { al.add(2L); } n /= 2L; } for (long i = 3; (long) i * i <= n; i += 2) { while ((n % i == 0)) { if (!al.contains((long) i)) { al.add((long) i); } n /= i; } } if (n > 2) { if (!al.contains(n)) { al.add(n); } } return al; } public static long totFact(long n) { long cnt = 0, tot = 1; while (n % 2 == 0) { n /= 2; ++cnt; } tot *= (cnt + 1); for (int i = 3; i <= Math.sqrt(n); i += 2) { cnt = 0; while (n % i == 0) { n /= i; ++cnt; } tot *= (cnt + 1); } if (n > 2) { tot *= 2; } return tot; } static int[] z_function(String s) { int n = s.length(), z[] = new int[n]; for (int i = 1, l = 0, r = 0; i < n; ++i) { if (i <= r) z[i] = Math.min(z[i - l], r - i + 1); while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) ++z[i]; if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } return z; } static void fast_swap(int[] a, int idx1, int idx2) { if (a[idx1] == a[idx2]) return; a[idx1] ^= a[idx2]; a[idx2] ^= a[idx1]; a[idx1] ^= a[idx2]; } public static void fast_sort(long[] array) { ArrayList<Long> copy = new ArrayList<>(); for (long i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } static int factorsCount(int n) { boolean hash[] = new boolean[n + 1]; Arrays.fill(hash, true); for (int p = 2; p * p < n; p++) if (hash[p] == true) for (int i = p * 2; i < n; i += p) hash[i] = false; int total = 1; for (int p = 2; p <= n; p++) { if (hash[p]) { int count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total; } static long binomialCoeff(long n, long k) { long res = 1; if (k > n - k) k = n - k; for (int i = 0; i < k; ++i) { res = (res * (n - i)); res /= (i + 1); } return res; } static long nck(long fact[], long inv[], long n, long k) { if (k > n) return 0; long res = fact[(int) n]%mod; res = (int) ((res%mod* inv[(int) k]%mod))%mod; res = (int) ((res%mod*inv[(int) (n - k)]%mod))%mod; return res % mod; } public static long fact(long x) { long fact = 1; for (int i = 2; i <= x; ++i) { fact = fact * i; } return fact; } public static ArrayList<Long> getFact(long x) { ArrayList<Long> facts = new ArrayList<>(); facts.add(1L); for (long i = 2; i * i <= x; ++i) { if (x % i == 0) { facts.add(i); if (i != x / i) { facts.add(x / i); } } } return facts; } static void matrix_ex(long n, long[][] A, long[][] I) { while (n > 0) { if (n % 2 == 0) { Multiply(A, A); n /= 2; } else { Multiply(I, A); n--; } } } static void Multiply(long[][] A, long[][] B) { int n = A.length, m = A[0].length, p = B[0].length; long[][] C = new long[n][p]; for (int i = 0; i < n; i++) { for (int j = 0; j < p; j++) { for (int k = 0; k < m; k++) { C[i][j] += ((A[i][k] % mod) * (B[k][j] % mod)) % mod; C[i][j] = C[i][j] % mod; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < p; j++) { A[i][j] = C[i][j]; } } } public static HashMap<Long, Integer> sortMapDesc(HashMap<Long,Integer> map) { List<Map.Entry<Long, Integer>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue()); HashMap<Long, Integer> temp = new LinkedHashMap<>(); for (Map.Entry<Long, Integer> i : list) { temp.put(i.getKey(), i.getValue()); } return temp; } public static HashMap<Character, Integer> sortMapDescch(HashMap<Character, Integer> map) { List<Map.Entry<Character, Integer>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue()); HashMap<Character, Integer> temp = new LinkedHashMap<>(); for (Map.Entry<Character, Integer> i : list) { temp.put(i.getKey(), i.getValue()); } return temp; } public static HashMap<Long,Long> sortMapAsclng(HashMap<Long,Long> map) { List<Map.Entry<Long,Long>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, (o1, o2) -> (int)(o1.getValue() - o2.getValue())); HashMap<Long,Long> temp = new LinkedHashMap<>(); for (Map.Entry<Long,Long> i : list) { temp.put(i.getKey(), i.getValue()); } return temp; } public static HashMap<Integer, Integer> sortMapAsc(HashMap<Integer, Integer> map) { List<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue()); HashMap<Integer, Integer> temp = new LinkedHashMap<>(); for (Map.Entry<Integer, Integer> i : list) { temp.put(i.getKey(), i.getValue()); } return temp; } public static long lcm(long l, long l2) { long val = gcd(l, l2); return (l * l2) / val; } public static boolean isSubsequence(String s, String t) { int n = s.length(); int m = t.length(); if (m > n) { return false; } int i = 0, j = 0, skip = 0; while (i < n && j < m) { if (s.charAt(i) == t.charAt(j)) { --skip; ++j; } ++skip; ++i; } return j==m; } public static long[][] combination(int l, int r) { long[][] pascal = new long[l + 1][r + 1]; pascal[0][0] = 1; for (int i = 1; i <= l; ++i) { pascal[i][0] = 1; for (int j = 1; j <= r; ++j) { pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j]; } } return pascal; } public static long gcd(long... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = gcd(ret, array[i]); return ret; } public static long lcm(int... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = lcm(ret, array[i]); return ret; } public static int min(int a, int b) { return a < b ? a : b; } public static int min(int... array) { int ret = array[0]; for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]); return ret; } public static long min(long a, long b) { return a < b ? a : b; } public static long min(long... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]); return ret; } public static int max(int a, int b) { return a > b ? a : b; } public static int max(int... array) { int ret = array[0]; for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]); return ret; } public static long max(long a, long b) { return a > b ? a : b; } public static long max(long... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]); return ret; } public static long sum(int... array) { long ret = 0; for (int i : array) ret += i; return ret; } public static long sum(long... array) { long ret = 0; for (long i : array) ret += i; return ret; } public static long[] facts(int n,long m) { long[] fact=new long[n]; fact[0]=1; fact[1]=1; for(int i=2;i<n;i++) { fact[i]=(long)(i*fact[i-1])%m; } return fact; } public static long[] inv(long[] fact,int n,long mod) { long[] inv=new long[n]; inv[n-1]= CP.Modular_Expo(fact[n-1],mod-2,mod)%mod; for(int i=n-2;i>=0;--i) { inv[i]=(inv[i+1]*(i+1))%mod; } return inv; } public static int modinv(long x, long mod) { return (int) (CP.Modular_Expo(x, mod - 2, mod) % mod); } public static int lcs(String s, String t) { int n = s.length(), m = t.length(); int dp[][] = new int[n + 1][m + 1]; for (int i = 0; i <= n; ++i) { for (int j = 0; j <= m; ++j) { if (i == 0 || j == 0) { dp[i][j] = 0; } else if (s.charAt(i - 1) == t.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[n][m]; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void print(long[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(long[] array) { print(array); writer.println(); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } public void printLine(int i) { writer.println(i); } public void printLine(char c) { writer.println(c); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void py() { print("YES"); writer.println(); } public void pn() { print("NO"); writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } void flush() { writer.flush(); } } }
java
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB OutputCopy2 1 3 1 6
[ "binary search", "dp", "greedy", "strings" ]
import java.io.*; import java.util.*; public class cf { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } void readArr(int[] ar, int n) { for (int i = 0; i < n; i++) { ar[i] = nextInt(); } } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static boolean binary_search(long[] a, long k) { long low = 0; long high = a.length - 1; long mid = 0; while (low <= high) { mid = low + (high - low) / 2; if (a[(int) mid] == k) { return true; } else if (a[(int) mid] < k) { low = mid + 1; } else { high = mid - 1; } } return false; } public static int bSearchDiff(long[] a, int low, int high) { int mid = low + ((high - low) / 2); int hight = high; int lowt = low; while (lowt < hight) { mid = lowt + (hight - lowt) / 2; if (a[high] - a[mid] <= 5) { hight = mid; } else { lowt = mid + 1; } } return lowt; } public static long lowerbound(long a[], long ddp) { long low = 0; long high = a.length; long mid = 0; while (low < high) { mid = low + (high - low) / 2; if (a[(int) mid] == ddp) { return mid; } if (a[(int) mid] < ddp) { low = mid + 1; } else { high = mid; } } if (low + 1 < a.length && a[(int) low + 1] <= ddp) { low++; } if (low == a.length && low != 0) { low--; return low; } if (a[(int) low] > ddp && low != 0) { low--; } return low; } public static long lowerbound(long a[], long ddp, long factor) { long low = 0; long high = a.length; long mid = 0; while (low < high) { mid = low + (high - low) / 2; if ((a[(int) mid] + (mid * factor)) == ddp) { return mid; } if ((a[(int) mid] + (mid * factor)) < ddp) { low = mid + 1; } else { high = mid; } } // if(low + 1 < a.length && a[(int)low + 1] <= ddp){ // low++; // } if (low == a.length && low != 0) { low--; return low; } if (a[(int) low] > ddp - (low * factor) && low != 0) { low--; } return low; } public static long lowerbound(List<Long> a, long ddp) { long low = 0; long high = a.size(); long mid = 0; while (low < high) { mid = low + (high - low) / 2; // if (a.get((int) mid) == ddp) { // return mid; // } if (a.get((int) mid) < ddp) { low = mid + 1; } else { high = mid; } } // if(low + 1 < a.length && a[(int)low + 1] <= ddp){ // low++; // } // if (low == a.size() && low != 0) { // low--; // return low; // } // if (a.get((int) low) >= ddp && low != 0) { // low--; // } return low; } public static long lowerboundforpairs(pair a[], double pr) { long low = 0; long high = a.length; long mid = 0; while (low < high) { mid = low + (high - low) / 2; if (a[(int) mid].w <= pr) { low = mid + 1; } else { high = mid; } } // if(low + 1 < a.length && a[(int)low + 1] <= ddp){ // low++; // } // if(low == a.length && low != 0){ // low--; // return low; // } // if(a[(int)low].w > pr && low != 0){ // low--; // } return low; } public static long upperbound(long a[], long ddp) { long low = 0; long high = a.length; long mid = 0; while (low < high) { mid = low + (high - low) / 2; if (a[(int) mid] == ddp) { return mid; } if (a[(int) mid] < ddp) { low = mid + 1; } else { high = mid; } } // if (low == a.length) { // return a.length - 1; // } return low; } public static long upperbound(ArrayList<Long> a, long ddp) { long low = 0; long high = a.size(); long mid = 0; while (low < high) { mid = low + (high - low) / 2; if (a.get((int) mid) <= ddp) { low = mid + 1; } else { high = mid; } } if (low == a.size()) { return a.size() - 1; } // System.out.println(a.get((int) low) + " " + ddp); if (low + 1 < a.size() && a.get((int) low) <= ddp) { low++; } return low; } // public static class pair implements Comparable<pair> { // long w; // long h; // public pair(long w, long h) { // this.w = w; // this.h = h; // } // public int compareTo(pair b) { // if (this.w != b.w) // return (int) (this.w - b.w); // else // return (int) (this.h - b.h); // } // } public static class pairs { char w; int h; public pairs(char w, int h) { this.w = w; this.h = h; } } public static class pairAl { int n; ArrayList<Integer> al; public pairAl(int n, ArrayList<Integer> al) { this.n = n; this.al = al; } } public static class pair { long w; long h; public pair(long w, long h) { this.w = w; this.h = h; } @Override public int hashCode() { return Objects.hash(w, h); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof pair)) { return false; } pair c = (pair) o; return Long.compare(this.w, c.w) == 0 && Long.compare(this.h, h) == 0; } } public static class trinary { long a; long b; long c; public trinary(long a, long b, long c) { this.a = a; this.b = b; this.c = c; } } public static class fourthary { long a; long b; long c; long d; public fourthary(long a, long b, long c, long d) { this.a = a; this.b = b; this.c = c; this.d = d; } } public static pair[] sortpair(pair[] a) { Arrays.sort(a, new Comparator<pair>() { public int compare(pair p1, pair p2) { if (p1.w != p2.w) { return (int) (p1.w - p2.w); } return (int) (p1.h - p2.h); } }); return a; } public static trinary[] sortpair(trinary[] a) { Arrays.sort(a, new Comparator<trinary>() { public int compare(trinary p1, trinary p2) { if (p1.b != p2.b) { return (int) (p1.b - p2.b); } else if (p1.a != p2.a) { return (int) (p1.a - p2.a); } return (int) (p1.c - p2.c); } }); return a; } public static fourthary[] sortpair(fourthary[] a) { Arrays.sort(a, new Comparator<fourthary>() { public int compare(fourthary p1, fourthary p2) { if (p1.b != p2.b) { return (int) (p1.b - p2.b); } else if (p1.a != p2.a) { return (int) (p1.a - p2.a); } return (int) (p1.c - p2.c); } }); return a; } public static void sort(long[] arr) { ArrayList<Long> a = new ArrayList<>(); for (long i : arr) { a.add(i); } Collections.sort(a); for (int i = 0; i < a.size(); i++) { arr[i] = a.get(i); } } public static void sortForObjecttypes(pair[] arr) { ArrayList<pair> a = new ArrayList<>(); for (pair i : arr) { a.add(i); } Collections.sort(a, new Comparator<pair>() { @Override public int compare(pair a, pair b) { return (int) (a.h - b.h); } }); for (int i = 0; i < a.size(); i++) { arr[i] = a.get(i); } } public static boolean ispalindrome(String s) { long i = 0; long j = s.length() - 1; boolean is = false; while (i < j) { if (s.charAt((int) i) == s.charAt((int) j)) { is = true; i++; j--; } else { is = false; return is; } } return is; } public static long power(long base, long pow, long mod) { long result = base; long temp = 1; while (pow > 1) { if (pow % 2 == 0) { result = ((result % mod) * (result % mod)) % mod; pow /= 2; } else { temp = temp * base; pow--; } } result = ((result % mod) * (temp % mod)); // System.out.println(result); return result; } public static long sqrt(long n) { long res = 1; long l = 1, r = (long) 10e9; while (l <= r) { long mid = (l + r) / 2; if (mid * mid <= n) { res = mid; l = mid + 1; } else r = mid - 1; } return res; } public static boolean is[] = new boolean[1000000]; public static int a[] = new int[1000000]; public static Vector<Integer> seiveOfEratosthenes() { Vector<Integer> listA = new Vector<>(); for (int i = 2; i * i <= a.length; i++) { if (a[i] != 1) { for (long j = i * i; j < a.length; j += i) { a[(int) j] = 1; } } } for (int i = 2; i < a.length; i++) { if (a[i] == 0) { is[i] = true; listA.add(i); } } return listA; } // public static Vector<Integer> ans = seiveOfEratosthenes(); public static long sumOfDigits(long n) { long ans = 0; while (n != 0) { ans += n % 10; n /= 10; } return ans; } public static long gcdTotal(long a[]) { long t = a[0]; for (int i = 1; i < a.length; i++) { t = gcd(t, a[i]); } return t; } public static ArrayList<Long> al = new ArrayList<>(); public static void makeArr() { long t = 1; while (t <= 10e17) { al.add(t); t *= 2; } } public static boolean isBalancedBrackets(String s) { if (s.length() == 1) { return false; } Stack<Character> sO = new Stack<>(); int id = 0; while (id < s.length()) { if (s.charAt(id) == '(') { sO.add('('); } if (s.charAt(id) == ')') { if (!sO.isEmpty()) { sO.pop(); } else { return false; } } id++; } if (sO.isEmpty()) { return true; } return false; } public static long kadanesAlgo(long a[], int start, int end) { long maxSoFar = Long.MIN_VALUE; long maxEndingHere = 0; for (int i = start; i < end; i++) { maxEndingHere += a[i]; if (maxSoFar < maxEndingHere) { maxSoFar = maxEndingHere; } if (maxEndingHere < 0) { maxEndingHere = 0; } } return maxSoFar; } public static Vector<Integer> prime = new Vector<>(); public static int components = 0; public static void search(HashMap<Integer, Integer> hm, int max, int start, int high) { if (start == 0) { components++; return; } int t = max; boolean is = false; for (int i = start; i < high; i++) { if (hm.get(t) >= start) { t--; is = true; } else { // System.out.println(start + " " + high + " " + hm.get(t) + " " + hm.get(max)); is = false; break; } } // System.out.println(max + " " + is + " " + t); if (is) { search(hm, t, hm.get(t), start); components++; } else { // System.out.println(t); search(hm, max, hm.get(t), high); } } public static void helper(String s, Stack<Character> left, Stack<Character> right) { int id = 0; while (id < s.length()) { if (s.charAt(id) == '(') { left.add('('); } if (s.charAt(id) == ')') { right.add(')'); if (left.size() > 0) { left.pop(); right.pop(); } } id++; } } public static long helperCounterFactor(long n, int fac, long m) { long max = (long) 10e9; long min = 0; long mid = max + (max - min) / 2; while (min < max) { mid = max + (max - min) / 2; if (n * mid > m) { max = mid; } else { min = mid + 1; } } return min; } public static long helperBS(long a[], long pref[], long d, long c) { long start = 0; long end = d; long mid = 0; long earn = 0; long ct = 0; long ans = 0; while (start < end) { mid = start + (end - start) / 2; earn = 0; ct = (d / (mid + 1)); if (mid >= a.length) { earn = ct * (pref[pref.length - 1]); earn += pref[(int) Math.min(a.length, (d % (mid + 1)))]; } else { earn = ct * pref[(int) mid + 1]; earn += pref[(int) (d % (mid + 1))]; } if (earn >= c) { start = mid + 1; ans = mid; } else { end = mid; } } return ans; } public static void helper(int[][] hel, int max) { for (int i = 0; i < Integer.toBinaryString(max).length(); i++) { for (int j = 1; j <= max; j++) { if (((j >> i) & 1) == 0) { hel[j][i] = hel[j - 1][i] + 1; } else { hel[j][i] = hel[j - 1][i]; } } } } public static int help(String a, String b, int x, int visit[][]) { int id = 0; int cur = 0; int n = a.length(); while (id < n) { if (id == n - 1) { if (a.charAt(id) == 'B' && visit[0][id] == 0) { cur++; } if (b.charAt(id) == 'B' && visit[1][id] == 0) { cur++; } break; } if (x == 0) { visit[x][id] = 1; cur++; if (b.charAt(id) == 'B' && visit[1][id] == 0) { x = 1; } else if (a.charAt(id + 1) == 'B' && visit[0][id + 1] == 0) { x = 0; id++; } else { break; } } else { visit[x][id] = 1; cur++; if (a.charAt(id) == 'B' && visit[0][id] == 0) { x = 0; } else if (b.charAt(id + 1) == 'B' && visit[1][id + 1] == 0) { x = 1; id++; } else { break; } } } return cur; } public static void solve(FastReader sc, PrintWriter w, StringBuilder sb) throws Exception { int a = sc.nextInt(); int b = sc.nextInt(); int p = sc.nextInt(); String s = sc.nextLine(); ArrayList<Integer> al = new ArrayList<>(); char prev = s.charAt(0); al.add(0); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != prev && i + 1 != s.length()) { al.add(i); // System.out.println(i); prev = s.charAt(i); } } for (int i = al.size() - 1; i >= 0; i--) { if (s.charAt(al.get(i)) == 'A') { if (p - a >= 0) { p -= a; } else { if (i + 1 >= al.size()) { sb.append(s.length() + "\n"); } else { sb.append((al.get(i + 1) + 1) + "\n"); } return; } } else { if (p - b >= 0) { p -= b; } else { if (i + 1 >= al.size()) { sb.append(s.length() + "\n"); } else { sb.append((al.get(i + 1) + 1) + "\n"); } return; } } } sb.append(1 + "\n"); } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); PrintWriter w = new PrintWriter(System.out); StringBuilder sb = new StringBuilder(); // prime = seiveOfEratosthenes(); // int max = 200000; // int[][] hel = new int[max + 1][Integer.toBinaryString(max).length()]; // helper(hel, max); long o = sc.nextLong(); // makeArr(); while (o > 0) { solve(sc, w, sb); o--; } System.out.print(sb.toString()); w.close(); } }
java
1325
E
E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3 1 4 6 OutputCopy1InputCopy4 2 3 6 6 OutputCopy2InputCopy3 6 15 10 OutputCopy3InputCopy4 2 3 5 7 OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence.
[ "brute force", "dfs and similar", "graphs", "number theory", "shortest paths" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Random; import java.util.InputMismatchException; import java.util.TreeSet; import java.util.ArrayList; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.util.Iterator; import java.io.BufferedWriter; import java.util.Set; import java.io.IOException; import java.util.List; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin (t.me/musin_acm) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); ENASTOYaShchAYaTeoriyaChiselOtYekhaba solver = new ENASTOYaShchAYaTeoriyaChiselOtYekhaba(); solver.solve(1, in, out); out.close(); } static class ENASTOYaShchAYaTeoriyaChiselOtYekhaba { public void solve(int testNumber, InputReader in, OutputWriter out) { if (false) { new Tester().test(); return; } int n = in.readInt(); int[] a = in.readIntArray(n); int answer = new Solver(a).solve(); out.print(answer); } int[] genPrimes(int n) { boolean[] isPrime = new boolean[n]; Arrays.fill(isPrime, true); int cnt = 0; for (int i = 2; i < n; i++) { if (isPrime[i]) { cnt++; for (int j = i + i; j < n; j += i) { isPrime[j] = false; } } } int[] primes = new int[cnt]; cnt = 0; for (int i = 2; i < n; i++) { if (isPrime[i]) { primes[cnt++] = i; } } return primes; } class Tester { Random rnd = new Random(); int divisorCount(int x) { int c = 0; for (int i = 1; i <= x; i++) { if (x % i == 0) { c++; } } return c; } int[] genArray(int n, int m) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = rnd.nextInt(m) + 1; if (divisorCount(a[i]) > 7) { i--; } } return a; } boolean checkArray(int[] a) { double x = 1; for (int b : a) { x *= b; } return x < 1e18; } void test() { for (int t = 0; ; t++) { int n = rnd.nextInt(20) + 1; int m = 500; int[] a = genArray(n, m); if (!checkArray(a)) { continue; } int solve = new Solver(a).solve(); int naive = new Naive(a).solve(); if (solve != naive) { System.err.println("Found test " + t); System.err.println(a.length); System.err.println(Arrays.toString(a)); solve = new Solver(a).solve(); naive = new Naive(a).solve(); } } } } class Naive { int[] a; public Naive(int[] a) { this.a = a; } boolean isSquare(long x) { long y = Math.round(Math.sqrt(x)); return y * y == x; } int solve() { int ans = Integer.MAX_VALUE; for (int m = 1; m < 1 << a.length; m++) { long x = 1; int bc = 0; for (int i = 0; i < a.length; i++) { if (((m >> i) & 1) == 1) { x *= a[i]; bc++; } } if (isSquare(x)) { ans = Math.min(ans, bc); } } if (ans == Integer.MAX_VALUE) { ans = -1; } return ans; } } class Solver { int[] a; int[] primes; int[] primeToIndex; int n; boolean[] single; List<Integer>[] g; public Solver(int[] a) { this.a = a; } List<Integer> factorize(int x) { List<Integer> res = new ArrayList<>(); for (int prime : primes) { if (prime * prime > x) { break; } if (x % prime == 0) { int power = 0; while (x % prime == 0) { x /= prime; power++; } if (power % 2 == 1) { res.add(prime); } } } if (x > 1) { res.add(x); } return res; } int buildGraph() { g = new List[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(); } single = new boolean[n]; boolean anySameSingle = false; for (int x : a) { List<Integer> f = factorize(x); if (f.isEmpty()) { return 1; } int u = primeToIndex[f.get(0)]; if (f.size() == 1) { if (single[u]) { anySameSingle = true; } else { single[u] = true; } } if (f.size() == 2) { int v = primeToIndex[f.get(1)]; g[u].add(v); g[v].add(u); } } for (int i = 0; i < n; i++) { Set<Integer> s = new TreeSet<>(g[i]); if (s.size() != g[i].size()) { anySameSingle = true; } g[i] = new ArrayList<>(s); } if (anySameSingle) { return 2; } return -1; } int solve() { int mx = ArrayUtils.maxElement(a); if (mx > 1e6) { throw new OutOfMemoryError("OOPS"); } primes = genPrimes(mx + 1); n = primes.length; primeToIndex = new int[mx + 1]; Arrays.fill(primeToIndex, -1); for (int i = 0; i < n; i++) { primeToIndex[primes[i]] = i; } int ans = buildGraph(); if (ans != -1) { return ans; } ans = Integer.MAX_VALUE; BfsTree bfsTree = new BfsTree(); for (int p : primes) { if (p < 1e3) { ans = Math.min(ans, bfsTree.getMinPath(primeToIndex[p])); } } if (ans == Integer.MAX_VALUE) { ans = -1; } return ans; } class BfsTree { int[] q = new int[n]; int[] distance = new int[n]; int[] parent = new int[n]; void init(int start) { Arrays.fill(distance, -1); distance[start] = 0; parent[start] = -1; int qs = 0; q[qs++] = start; for (int qi = 0; qi < qs; qi++) { int v = q[qi]; for (int to : g[v]) { if (distance[to] == -1) { distance[to] = distance[v] + 1; parent[to] = v; q[qs++] = to; } } } } int getMinPath(int start) { init(start); int res = Integer.MAX_VALUE; for (int from = 0; from < n; from++) { for (int to : g[from]) { if (distance[from] != -1 && distance[to] != -1 && parent[from] != to && parent[to] != from) { res = Math.min(res, distance[from] + distance[to] + 1); } } } List<Integer> mins = new ArrayList<>(); for (int i = 0; i < n; i++) { if (single[i] && distance[i] != -1) { mins.add(distance[i]); } } mins.sort(null); if (mins.size() >= 2) { res = Math.min(res, mins.get(0) + mins.get(1) + 2); } return res; } } } } static class ArrayUtils { public static int maxElement(int[] array) { return new IntArray(array).max(); } } static class IntArray extends IntAbstractStream implements IntList { private int[] data; public IntArray(int[] arr) { data = arr; } public int size() { return data.length; } public int get(int at) { return data[at]; } public void removeAt(int index) { throw new UnsupportedOperationException(); } } static interface IntReversableCollection extends IntCollection { } static abstract class IntAbstractStream implements IntStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof IntStream)) { return false; } IntStream c = (IntStream) o; IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } } static interface IntCollection extends IntStream { public int size(); } static interface IntList extends IntReversableCollection { public abstract int get(int index); public abstract void removeAt(int index); default public IntIterator intIterator() { return new IntIterator() { private int at; private boolean removed; public int value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } } static interface IntIterator { public int value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static interface IntStream extends Iterable<Integer>, Comparable<IntStream> { public IntIterator intIterator(); default public Iterator<Integer> iterator() { return new Iterator<Integer>() { private IntIterator it = intIterator(); public boolean hasNext() { return it.isValid(); } public Integer next() { int result = it.value(); it.advance(); return result; } }; } default public int compareTo(IntStream c) { IntIterator it = intIterator(); IntIterator jt = c.intIterator(); while (it.isValid() && jt.isValid()) { int i = it.value(); int j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } default public int max() { int result = Integer.MIN_VALUE; for (IntIterator it = intIterator(); it.isValid(); it.advance()) { int current = it.value(); if (current > result) { result = current; } } return result; } } }
java
1296
E2
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≤n≤2⋅1051≤n≤2⋅105) — 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≤res≤n1≤res≤n) — 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≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9 abacbecfd OutputCopy2 1 1 2 1 2 1 2 1 2 InputCopy8 aaabbcbb OutputCopy2 1 2 1 2 1 2 1 1 InputCopy7 abcdedc OutputCopy3 1 1 1 1 1 2 3 InputCopy5 abcde OutputCopy1 1 1 1 1 1
[ "data structures", "dp" ]
import java.util.*; public class string_coloring_hard { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); char[] s = sc.next().toCharArray(); int[] dp = new int[n]; int[] maxdp = new int[26]; Arrays.fill(dp, 1); Arrays.fill(dp, 0); for(int i=0;i<n;i++) { int k = s[i]-'a'; int max = 0; for(int j=k+1;j<26;j++) { if(maxdp[j]>max) max = maxdp[j]; } dp[i] = max+1; maxdp[k] = dp[i]; } StringBuilder color = new StringBuilder(); int max = 0; for(int i=0;i<n;i++) { color.append(dp[i]+" "); if(dp[i]>max) max = dp[i]; } System.out.println(max); System.out.println(color); } }
java
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0 2 4 20 OutputCopy3InputCopy1 1 2 3 1 0 15 27 26 OutputCopy2InputCopy1 1 2 3 1 0 2 2 1 OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
//package aromassearch; import java.util.*; import java.io.*; public class aromassearch { static long x0, y0, ax, ay, bx, by, xs, ys; public static long dist(long x1, long y1, long x2, long y2) { return Math.abs(x1 - x2) + Math.abs(y1 - y2); } public static int getMax(long t, int val) { long minDist = 0; ArrayList<long[]> nodes = new ArrayList<long[]>(); nodes.add(new long[] {x0, y0}); while(nodes.size() < val) { long[] prev = nodes.get(nodes.size() - 1); long nextX = prev[0] * ax + bx; long nextY = prev[1] * ay + by; nodes.add(new long[] {nextX, nextY}); } minDist = dist(xs, ys, nodes.get(nodes.size() - 1)[0], nodes.get(nodes.size() - 1)[1]); if(minDist < 0) { return 0; } //System.out.println(minDist + " " + t); t -= minDist; int ans = 0; if(t >= 0) { ans ++; } else { return 0; } int pointer = nodes.size() - 2; while(pointer >= 0 && t > 0) { //System.out.println("YES"); long[] next = nodes.get(pointer); long[] cur = nodes.get(pointer + 1); long nextDist = dist(next[0], next[1], cur[0], cur[1]); //System.out.println(nextDist); t -= nextDist; pointer --; if(t >= 0) { ans ++; } } //System.out.println(minDist); t -= dist(x0, y0, nodes.get(nodes.size() - 1)[0], nodes.get(nodes.size() - 1)[1]); //System.out.println(dist(x0, y0, nodes.get(nodes.size() - 1)[0], nodes.get(nodes.size() - 1)[1])); while(t > 0) { long[] prev = nodes.get(nodes.size() - 1); long nextX = prev[0] * ax + bx; long nextY = prev[1] * ay + by; //System.out.println(prev[0] + " " + prev[1]); //System.out.println(nextX + " " + nextY); long nextDist = dist(nextX, nextY, prev[0], prev[1]); //System.out.println(nextDist + " " + t); t -= nextDist; if(t >= 0) { ans ++; } nodes.add(new long[] {nextX, nextY}); } return ans; } public static void main(String[] args) throws IOException { //1292B BufferedReader fin = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(fin.readLine()); x0 = Long.parseLong(st.nextToken()); y0 = Long.parseLong(st.nextToken()); ax = Long.parseLong(st.nextToken()); ay = Long.parseLong(st.nextToken()); bx = Long.parseLong(st.nextToken()); by = Long.parseLong(st.nextToken()); st = new StringTokenizer(fin.readLine()); xs = Long.parseLong(st.nextToken()); ys = Long.parseLong(st.nextToken()); long t = Long.parseLong(st.nextToken()); int ans = 0; long px = x0; long py = y0; int val = 1; long prevX = x0; long prevY = y0; while(true) { ans = Math.max(ans, getMax(t, val)); //System.out.println(px + " " + py + " " + val + " " + ans); val ++; px *= ax; py *= ay; px += bx; py += by; if(px < prevX || py < prevY) { break; } prevX = px; prevY = py; } System.out.println(ans); } }
java
1312
A
A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2 6 3 7 3 OutputCopyYES NO Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO".
[ "geometry", "greedy", "math", "number theory" ]
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.lang.reflect.Array; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import org.w3c.dom.NamedNodeMap; import java.io.*; import java.math.*; import java.util.*; import java.util.Arrays; import java.util.Comparator; import java.util.*; import java.util.Collections; public class div { static PrintWriter output = new PrintWriter(System.out); public static void main(String[] args) throws java.lang.Exception { div.FastReader sc =new FastReader(); int t= sc.nextInt(); for(int e =0;e<t;e++) { int n = sc.nextInt(); int m = sc.nextInt(); if(n%m==0)System.out.println("YES"); else System.out.println("NO"); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readArrayLong(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } public static int[] radixSort2(int[] a) { int n = a.length; int[] c0 = new int[0x101]; int[] c1 = new int[0x101]; int[] c2 = new int[0x101]; int[] c3 = new int[0x101]; for(int v : a) { c0[(v&0xff)+1]++; c1[(v>>>8&0xff)+1]++; c2[(v>>>16&0xff)+1]++; c3[(v>>>24^0x80)+1]++; } for(int i = 0;i < 0xff;i++) { c0[i+1] += c0[i]; c1[i+1] += c1[i]; c2[i+1] += c2[i]; c3[i+1] += c3[i]; } int[] t = new int[n]; for(int v : a)t[c0[v&0xff]++] = v; for(int v : t)a[c1[v>>>8&0xff]++] = v; for(int v : a)t[c2[v>>>16&0xff]++] = v; for(int v : t)a[c3[v>>>24^0x80]++] = v; return a; } static void reverse_sorted(int[] arr) { ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<arr.length;i++) { list.add(arr[i]); } Collections.sort(list , Collections.reverseOrder()); for(int i=0;i<arr.length;i++) { arr[i] = list.get(i); } } static int LowerBound(int a[], int x) { // x is the target value or key int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } static int UpperBound(ArrayList<Integer> list, int x) {// x is the key or target value int l=-1,r=list.size(); while(l+1<r) { int m=(l+r)>>>1; if(list.get(m)<=x) l=m; else r=m; } return l+1; } public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // put data from sorted list to hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } static class Queue_Pair implements Comparable<Queue_Pair> { int first , second; public Queue_Pair(int first, int second) { this.first=first; this.second=second; } public int compareTo(Queue_Pair o) { return Integer.compare(o.first, first); } } static void leftRotate(int arr[], int d, int n) { for (int i = 0; i < d; i++) leftRotatebyOne(arr, n); } static void leftRotatebyOne(int arr[], int n) { int i, temp; temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n-1] = temp; } static boolean isPalindrome(String str) { // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters to compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } static boolean palindrome_array(char arr[], int n) { // Initialise flag to zero. int flag = 0; // Loop till array size n/2. for (int i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) return false; else return true; } static boolean allElementsEqual(long[] arr,int n) { int z=0; for(int i=0;i<n-1;i++) { if(arr[i]==arr[i+1]) { z++; } } if(z==n-1) { return true; } else { return false; } } static boolean allElementsDistinct(int[] arr,int n) { int z=0; for(int i=0;i<n-1;i++) { if(arr[i]!=arr[i+1]) { z++; } } if(z==n-1) { return true; } else { return false; } } public static void reverse(int[] array) { // Length of the array int n = array.length; // Swaping the first half elements with last half // elements for (int i = 0; i < n / 2; i++) { // Storing the first half elements temporarily int temp = array[i]; // Assigning the first half to the last half array[i] = array[n - i - 1]; // Assigning the last half to the first half array[n - i - 1] = temp; } } public static void reverse_Long(long[] array) { // Length of the array int n = array.length; // Swaping the first half elements with last half // elements for (int i = 0; i < n / 2; i++) { // Storing the first half elements temporarily long temp = array[i]; // Assigning the first half to the last half array[i] = array[n - i - 1]; // Assigning the last half to the first half array[n - i - 1] = temp; } } static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } static boolean isReverseSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] < a[i + 1]) { return false; } } return true; } static int[] rearrangeEvenAndOdd(int arr[], int n) { ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i]%2==0) { list.add(arr[i]); } } for(int i=0;i<n;i++) { if(arr[i]%2!=0) { list.add(arr[i]); } } int len = list.size(); int[] array = list.stream().mapToInt(i->i).toArray(); return array; } static long[] rearrangeEvenAndOddLong(long arr[], int n) { ArrayList<Long> list = new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i]%2==0) { list.add(arr[i]); } } for(int i=0;i<n;i++) { if(arr[i]%2!=0) { list.add(arr[i]); } } int len = list.size(); long[] array = list.stream().mapToLong(i->i).toArray(); return array; } static boolean isPrime(long n) { // Check if number is less than // equal to 1 if (n <= 1) return false; // Check if number is 2 else if (n == 2) return true; // Check if n is a multiple of 2 else if (n % 2 == 0) return false; // If not, then just check the odds for (long i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } static long getSum(long n) { long sum = 0; while (n != 0) { sum = sum + n % 10; n = n/10; } return sum; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcdLong(long a, long b) { if (b == 0) return a; return gcdLong(b, a % b); } static void swap(int i, int j) { int temp = i; i = j; j = temp; } static int countDigit(int n) { return (int)Math.floor(Math.log10(n) + 1); } /* Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); q.replace(i, i+1, "4"); StringBuilder q = new StringBuilder(w); List arr1 = new ArrayList(); String.format("%.2f",arr[ee][0]) */ /* */ }
java
1299
C
C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4 7 5 5 7 OutputCopy5.666666667 5.666666667 5.666666667 7.000000000 InputCopy5 7 8 8 10 12 OutputCopy7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 InputCopy10 3 9 5 5 1 7 5 3 8 7 OutputCopy3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.
[ "data structures", "geometry", "greedy" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; import java.io.BufferedOutputStream; import java.io.UncheckedIOException; import java.util.Vector; import java.nio.charset.Charset; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); CWaterBalance solver = new CWaterBalance(); solver.solve(1, in, out); out.close(); } static class CWaterBalance { public void solve(int testNumber, LightScanner in, LightWriter out) { int n = in.ints(); Stack<CWaterBalance.Node> stack = new Stack<>(); for (int i = 0; i < n; i++) { CWaterBalance.Node node = new CWaterBalance.Node(1, in.ints()); while (!stack.isEmpty() && stack.peek().compareTo(node) > 0) { node.merge(stack.pop()); } stack.push(node); } for (CWaterBalance.Node node : stack) { for (int i = 0; i < node.length(); i++) { out.ans(node.value(), 12).ln(); } } } private static class Node implements Comparable<CWaterBalance.Node> { int count; long sum; Node(int count, long sum) { this.count = count; this.sum = sum; } int length() { return count; } double value() { return sum / (double) length(); } public int compareTo(CWaterBalance.Node o) { return Long.compare(sum * o.length(), o.sum * length()); } void merge(CWaterBalance.Node o) { this.count += o.count; this.sum += o.sum; } } } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public int ints() { return Integer.parseInt(string()); } } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset())); } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ans(double x, int n) { if (!breaked) { print(' '); } if (x < 0) { print('-'); x = -x; } x += Math.pow(10, -n) / 2; print(Long.toString((long) x)).print('.'); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; print((char) ('0' + ((int) x))); x -= (int) x; } return this; } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } } }
java
1312
C
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5 4 100 0 0 0 0 1 2 1 3 4 1 4 1 3 2 0 1 3 3 9 0 59049 810 OutputCopyYES YES NO NO YES NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.
[ "bitmasks", "greedy", "implementation", "math", "number theory", "ternary search" ]
//package Practise_problems; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Random; import java.util.StringTokenizer; public class AddingPowers { public static void main(String []args) { FastScanner fs=new FastScanner(); int t=fs.nextInt(); while(t-->0) { int n=fs.nextInt(); int k=fs.nextInt(); long mask=0; boolean flag=true; while(n-->0) { int shift_bit=0; for(long i=fs.nextLong();i>0;i/=k) { if(i%k>0) { if((i%k>1)||(mask&(1L<<shift_bit))!=0) { flag=false; break; } mask|=(1L<<shift_bit); } shift_bit++; } } if(flag) System.out.println("YES"); else System.out.println("NO"); } } private static int[] readArray(int n) { // TODO Auto-generated method stub return null; } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
java
1324
C
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6 LRLRRLL L LLR RRRR LLLLLL R OutputCopy3 2 3 1 7 1 NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.
[ "binary search", "data structures", "dfs and similar", "greedy", "implementation" ]
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader(new File("./src/testcase.txt"))); int t = Integer.parseInt(in.readLine()); for (int i=0; i<t; i++) { String s = in.readLine(); int cur = 0; int max = 1; for (int j=0; j<s.length(); j++) { if (s.charAt(j) == 'L') { cur ++; } else { max = Math.max(max, cur+1); cur = 0; } } max = Math.max(max, cur+1); System.out.println(max); } } }
java
1294
D
D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3 0 1 2 2 0 0 10 OutputCopy1 2 3 3 4 4 7 InputCopy4 3 1 2 1 2 OutputCopy0 0 0 0 NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.
[ "data structures", "greedy", "implementation", "math" ]
import java.io.*; import java.math.*; import java.util.*; // @author : Dinosparton public class test { static class Pair{ long x; long y; Pair(long x,long y){ this.x = x; this.y = y; } } static class Sort implements Comparator<Pair> { @Override public int compare(Pair a, Pair b) { if(a.x!=b.x) { return (int)(a.x - b.x); } else { return (int)(a.y-b.y); } } } static class Compare { void compare(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.x!=p2.x) { return (int)(p1.x - p2.x); } else { return (int)(p1.y - p2.y); } } }); // for (int i = 0; i < n; i++) { // System.out.print(arr[i].x + " " + arr[i].y + " "); // } // System.out.println(); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]) throws Exception { Scanner sc = new Scanner(); StringBuilder res = new StringBuilder(); int tc = 1; while(tc-->0) { int n = sc.nextInt(); int k = sc.nextInt(); int map[] = new int[k]; Set<Integer> set = new HashSet<>(); int cnt = 0; for(int i=0;i<n;i++) { long y = sc.nextLong(); int val = map[(int)(y%k)]*k + (int)(y%k); set.add(val); map[(int)(y%k)]++; while(set.contains(cnt)) { cnt++; } res.append(cnt+"\n"); } } System.out.println(res); } }
java
1301
C
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5 3 1 3 2 3 3 4 0 5 2 OutputCopy4 5 6 0 12 NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
import java.util.*; public class Ayoub { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); StringBuilder finAns = new StringBuilder(); while (--T >= 0) { long n = sc.nextLong(), m = sc.nextLong(); long z = n - m; long g = m + 1; long k = z / g; long ans = ((n * (n + 1)) / 2) - (((k * (k + 1)) / 2) * g) - ((k + 1) * (z % g)); finAns.append(ans + "\n"); } System.out.println(finAns); sc.close(); } }
java
1303
B
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3 5 1 1 8 10 10 1000000 1 1000000 OutputCopy5 8 499999500000 NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.
[ "math" ]
/* ⣿⣿⣿⣿⣿⣿⡷⣯⢿⣿⣷⣻⢯⣿⡽⣻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠸⣿⣿⣆⠹⣿⣿⢾⣟⣯⣿⣿⣿⣿⣿⣿⣽⣻⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣻⣽⡿⣿⣎⠙⣿⣞⣷⡌⢻⣟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣿⣿⡄⠹⣿⣿⡆⠻⣿⣟⣯⡿⣽⡿⣿⣿⣿⣿⣽⡷⣯⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣟⣷⣿⣿⣿⡀⠹⣟⣾⣟⣆⠹⣯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢠⡘⣿⣿⡄⠉⢿⣿⣽⡷⣿⣻⣿⣿⣿⣿⡝⣷⣯⢿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣯⢿⣾⢿⣿⡄⢄⠘⢿⣞⡿⣧⡈⢷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢸⣧⠘⣿⣷⠈⣦⠙⢿⣽⣷⣻⣽⣿⣿⣿⣿⣌⢿⣯⢿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣟⣯⣿⢿⣿⡆⢸⡷⡈⢻⡽⣷⡷⡄⠻⣽⣿⣿⡿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣏⢰⣯⢷⠈⣿⡆⢹⢷⡌⠻⡾⢋⣱⣯⣿⣿⣿⣿⡆⢻⡿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⡎⣿⢾⡿⣿⡆⢸⣽⢻⣄⠹⣷⣟⣿⣄⠹⣟⣿⣿⣟⣿⣿⣿⣿⣿⣿⣽⣿⣿⣿⡇⢸⣯⣟⣧⠘⣷⠈⡯⠛⢀⡐⢾⣟⣷⣻⣿⣿⣿⡿⡌⢿⣻⣿⣿ ⣿⣿⣿⣿⣿⣿⣧⢸⡿⣟⣿⡇⢸⣯⣟⣮⢧⡈⢿⣞⡿⣦⠘⠏⣹⣿⣽⢿⣿⣿⣿⣿⣯⣿⣿⣿⡇⢸⣿⣿⣾⡆⠹⢀⣠⣾⣟⣷⡈⢿⣞⣯⢿⣿⣿⣿⢷⠘⣯⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⡈⣿⢿⣽⡇⠘⠛⠛⠛⠓⠓⠈⠛⠛⠟⠇⢀⢿⣻⣿⣯⢿⣿⣿⣿⣷⢿⣿⣿⠁⣾⣿⣿⣿⣧⡄⠇⣹⣿⣾⣯⣿⡄⠻⣽⣯⢿⣻⣿⣿⡇⢹⣾⣿ ⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⡽⡇⢸⣿⣿⣿⣿⣿⣞⣆⠰⣶⣶⡄⢀⢻⡿⣯⣿⡽⣿⣿⣿⢯⣟⡿⢀⣿⣿⣿⣿⣿⣧⠐⣸⣿⣿⣷⣿⣿⣆⠹⣯⣿⣻⣿⣿⣿⢀⣿⢿ ⣿⣿⣿⣿⣿⣿⣿⣿⠘⣯⡿⡇⢸⣿⣿⣿⣿⣿⣿⣿⣧⡈⢿⣳⠘⡄⠻⣿⢾⣽⣟⡿⣿⢯⣿⡇⢸⣿⣿⣿⣿⣿⣿⡀⢾⣿⣿⣿⣿⣿⣿⣆⠹⣾⣷⣻⣿⡿⡇⢸⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⠇⢸⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠻⡇⢹⣆⠹⣟⣾⣽⣻⣟⣿⣽⠁⣾⣿⣿⣿⣿⣿⣿⣇⣿⣿⠿⠛⠛⠉⠙⠋⢀⠁⢘⣯⣿⣿⣧⠘⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⡈⣿⡃⢼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡙⠌⣿⣆⠘⣿⣞⡿⣞⡿⡞⢠⣿⣿⣿⣿⣿⡿⠛⠉⠁⢀⣀⣠⣤⣤⣶⣶⣶⡆⢻⣽⣞⡿⣷⠈⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⠘⠁⠉⠉⠉⠉⠉⠉⠉⠉⠉⠙⠛⠛⢿⣄⢻⣿⣧⠘⢯⣟⡿⣽⠁⣾⣿⣿⣿⣿⣿⡃⢀⢀⠘⠛⠿⢿⣻⣟⣯⣽⣻⣵⡀⢿⣯⣟⣿⢀⣿ ⣿⣿⣿⣟⣿⣿⣿⣿⣶⣶⡆⢀⣿⣾⣿⣾⣷⣿⣶⠿⠚⠉⢀⢀⣤⣿⣷⣿⣿⣷⡈⢿⣻⢃⣼⣿⣿⣿⣿⣻⣿⣿⣿⡶⣦⣤⣄⣀⡀⠉⠛⠛⠷⣯⣳⠈⣾⡽⣾⢀⣿ ⣿⢿⣿⣿⣻⣿⣿⣿⣿⣿⡿⠐⣿⣿⣿⣿⠿⠋⠁⢀⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣌⣥⣾⡿⣿⣿⣷⣿⣿⢿⣷⣿⣿⣟⣾⣽⣳⢯⣟⣶⣦⣤⡾⣟⣦⠘⣿⢾⡁⢺ ⣿⣻⣿⣿⡷⣿⣿⣿⣿⣿⡗⣦⠸⡿⠋⠁⢀⢀⣠⣴⢿⣿⣽⣻⢽⣾⣟⣷⣿⣟⣿⣿⣿⣳⠿⣵⣧⣼⣿⣿⣿⣿⣿⣾⣿⣿⣿⣿⣿⣽⣳⣯⣿⣿⣿⣽⢀⢷⣻⠄⠘ ⣿⢷⣻⣿⣿⣷⣻⣿⣿⣿⡷⠛⣁⢀⣀⣤⣶⣿⣛⡿⣿⣮⣽⡻⣿⣮⣽⣻⢯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢀⢸⣿⢀⡆ ⠸⣟⣯⣿⣿⣷⢿⣽⣿⣿⣷⣿⣷⣆⠹⣿⣶⣯⠿⣿⣶⣟⣻⢿⣷⣽⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢀⣯⣟⢀⡇ ⣇⠹⣟⣾⣻⣿⣿⢾⡽⣿⣿⣿⣿⣿⣆⢹⣶⣿⣻⣷⣯⣟⣿⣿⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⢀⡿⡇⢸⡇ ⣿⣆⠹⣷⡻⣽⣿⣯⢿⣽⣻⣿⣿⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⢸⣿⠇⣼⡇ ⡙⠾⣆⠹⣿⣦⠛⣿⢯⣷⢿⡽⣿⣿⣿⣿⣆⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠎⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⢀⣿⣾⣣⡿⡇ ⣿⣷⡌⢦⠙⣿⣿⣌⠻⣽⢯⣿⣽⣻⣿⣿⣿⣧⠩⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⢰⢣⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⢀⢀⢿⣞⣷⢿⡇ ⣿⣽⣆⠹⣧⠘⣿⣿⡷⣌⠙⢷⣯⡷⣟⣿⣿⣿⣷⡀⡹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣈⠃⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢀⣴⡧⢀⠸⣿⡽⣿⢀ ⢻⣽⣿⡄⢻⣷⡈⢿⣿⣿⢧⢀⠙⢿⣻⡾⣽⣻⣿⣿⣄⠌⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢁⣰⣾⣟⡿⢀⡄⢿⣟⣿⢀ ⡄⢿⣿⣷⢀⠹⣟⣆⠻⣿⣿⣆⢀⣀⠉⠻⣿⡽⣯⣿⣿⣷⣈⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⢀⣠⠘⣯⣷⣿⡟⢀⢆⠸⣿⡟⢸ ⣷⡈⢿⣿⣇⢱⡘⢿⣷⣬⣙⠿⣧⠘⣆⢀⠈⠻⣷⣟⣾⢿⣿⣆⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⣠⡞⢡⣿⢀⣿⣿⣿⠇⡄⢸⡄⢻⡇⣼ ⣿⣷⡈⢿⣿⡆⢣⡀⠙⢾⣟⣿⣿⣷⡈⠂⠘⣦⡈⠿⣯⣿⢾⣿⣆⠙⠻⠿⠿⠿⠿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⢋⣠⣾⡟⢠⣿⣿⢀⣿⣿⡟⢠⣿⢈⣧⠘⢠⣿ ⣿⣿⣿⣄⠻⣿⡄⢳⡄⢆⡙⠾⣽⣿⣿⣆⡀⢹⡷⣄⠙⢿⣿⡾⣿⣆⢀⡀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⣀⣠⣴⡿⣯⠏⣠⣿⣿⡏⢸⣿⡿⢁⣿⣿⢀⣿⠆⢸⣿ ⣿⣿⣿⣿⣦⡙⣿⣆⢻⡌⢿⣶⢤⣉⣙⣿⣷⡀⠙⠽⠷⠄⠹⣿⣟⣿⣆⢙⣋⣤⣤⣤⣄⣀⢀⢀⢀⢀⣾⣿⣟⡷⣯⡿⢃⣼⣿⣿⣿⠇⣼⡟⣡⣿⣿⣿⢀⡿⢠⠈⣿ ⣿⣿⣿⣿⣿⣷⣮⣿⣿⣿⡌⠁⢤⣤⣤⣤⣬⣭⣴⣶⣶⣶⣆⠈⢻⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣷⣶⣤⣌⣉⡘⠛⠻⠶⣿⣿⣿⣿⡟⣰⣫⣴⣿⣿⣿⣿⠄⣷⣿⣿⣿ */ import java.awt.*; import java.io.*; import java.util.*; import java.util.List; import java.util.StringTokenizer; public class Ex3 { static FastScanner in = new FastScanner(); public static void main(String[] args) { PrintWriter out = new PrintWriter(System.out); int q = in.nextInt(); for (int e = 0; e < q; e++) { long n = in.nextInt(); long g = in.nextInt(); long b = in.nextInt(); long res = (n+1)/2; long res1 = res/g * (b+g); if(res%g==0){ res1-=b; }else{ res1+=res%g; } out.println(Math.max(n,res1)); } out.flush(); } static int[] arr(int n) { int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } return arr; } static private long factorial(long n) { long result = 1; if (n == 1 || n == 0) { return result; } result = n * factorial(n - 1); return result; } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return a * b / gcd(a, b); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { init(); } public FastScanner(String name) { init(name); } public FastScanner(boolean isOnlineJudge) { if (!isOnlineJudge || System.getProperty("ONLINE_JUDGE") != null) { init(); } else { init("input.txt"); } } private void init() { br = new BufferedReader(new InputStreamReader(System.in)); } private void init(String name) { try { br = new BufferedReader(new FileReader(name)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static void mergeSort(int[] arr) { int n = arr.length; if (n == 1) return; int mid = n / 2; int left[] = new int[mid]; int right[] = new int[n - mid]; for (int i = 0; i < mid; i++) { left[i] = arr[i]; } for (int i = mid; i < n; i++) { right[i - mid] = arr[i]; } mergeSort(left); mergeSort(right); merge(arr, left, right); } public static void merge(int arr[], int left[], int right[]) { int lenLeft = left.length; int lenRight = right.length; int i = 0; int j = 0; int idx = 0; while (i < lenLeft && j < lenRight) { if (left[i] < right[j]) { arr[idx] = left[i]; i++; idx++; } else { arr[idx] = right[j]; j++; idx++; } } for (int ll = i; ll < lenLeft; ll++) { arr[idx++] = left[ll]; } for (int rr = j; rr < lenRight; rr++) { arr[idx++] = right[rr]; } } public static void bubbleSort(int[] sort_arr) { int len = sort_arr.length; for (int i = 0; i < len - 1; ++i) { for (int j = 0; j < len - i - 1; ++j) { if (sort_arr[j + 1] < sort_arr[j]) { int swap = sort_arr[j]; sort_arr[j] = sort_arr[j + 1]; sort_arr[j + 1] = swap; } } } } }
java
1325
F
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 ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. 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≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) 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 ⌈n−−√⌉⌈n⌉ 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 1 3 3 4 4 2 2 6 5 6 5 1 OutputCopy1 1 6 4InputCopy6 8 1 3 3 4 4 2 2 6 5 6 5 1 1 4 2 5 OutputCopy2 4 1 5 2 4InputCopy5 4 1 2 1 3 2 4 2 5 OutputCopy1 3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
/*For cycle of length sqrt: compute the height of every vertex using DFS. Look at all the edges. If the vertices differ by a height of (sqrt-1) or more, then they complete a cycle of length at least sqrt. For independent set of size sqrt: Use a priority queue to find the next vertex with the lowest degree. Add it to the set. Remove all its neighbours from the graph, and reduce the degrees of the neighbours of the removed neighbours by 1.*/ import java.io.*; import java.util.*; public class F { private static int height[], parent[], vis[]; private static ArrayDeque<Integer> edge[]; private static void DFS(int u) { vis[u]=1; for(int v:edge[u]) { if(vis[v]==1) continue; parent[v]=u; height[v]=height[u]+1; DFS(v); } } static class Pair implements Comparable<Pair> { int first, second; Pair(int first, int second){this.first=first;this.second=second;} public int compareTo(Pair obj) { if(this.second<obj.second) return -1; if(this.second>obj.second) return 1; return 0; } } public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,N; String s[]=br.readLine().trim().split(" "); N=Integer.parseInt(s[0]); int M=Integer.parseInt(s[1]); edge=new ArrayDeque[N]; for(i=0;i<N;i++) edge[i]=new ArrayDeque<>(); vis=new int[N]; height=new int[N]; parent=new int[N]; int degree[]=new int[N]; for(i=0;i<M;i++) { s=br.readLine().trim().split(" "); int u=Integer.parseInt(s[0])-1; int v=Integer.parseInt(s[1])-1; edge[u].add(v); edge[v].add(u); degree[u]++; degree[v]++; } parent[0]=-1; DFS(0); int sqrt=(int)(Math.ceil(Math.sqrt(N))); int u=-1,v=-1; for(i=0;i<N;i++) { for(int n:edge[i]) { if(height[i]-height[n]+1>=sqrt) { u=i; v=n; } } } int count=0; StringBuilder sb1=new StringBuilder(); StringBuilder sb2=new StringBuilder(); if(u!=-1) { for(i=u;i!=parent[v];i=parent[i]) { count++; sb2.append(i+1).append(" "); } sb1.append(2).append("\n"); sb1.append(count).append("\n"); sb1.append(sb2); } else { PriorityQueue<Pair> heap=new PriorityQueue<>(); for(i=0;i<N;i++) heap.add(new Pair(i,degree[i])); HashSet<Integer> set=new HashSet<>(); boolean done[]=new boolean[N]; while (!heap.isEmpty()) { u=heap.poll().first; if(done[u]) continue;; if(count==sqrt) break; for(int w:edge[u]) { if(done[w]) continue; done[w]=true; for(int x:edge[w]) { degree[x]--; heap.add(new Pair(x, degree[x])); } } count++; set.add(u); done[u]=true; } for(int w:set) sb2.append(w+1).append(" "); sb1.append(1).append("\n"); sb1.append(sb2); } System.out.println(sb1); } }
java
1285
B
B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3 4 1 2 3 4 3 7 4 -1 3 5 -5 5 OutputCopyYES NO NO NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.
[ "dp", "greedy", "implementation" ]
import java.util.*; import java.io.*; public class Main{ static class pair{ long x ;long y ; pair(long x ,long y ) { this.x=x; this.y =y; } } static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next(){ while(st==null || !st.hasMoreTokens()){ try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str=""; try { str=br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void prlong(Object object) throws IOException { bw.append("" + object); } public void prlongln(Object object) throws IOException { prlong(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } //dsu static int[] parent,rank; public static void dsu(int n){ parent = new int[n]; rank = new int[n]; for(int i =0;i<n;i++){ parent[i]=i; rank[i]=1; } } public static int find(int i){ if(i==parent[i] ) return i; return parent[i]=find(parent[i]); } static int f(int arr[],int i ) { if(i==arr[i]) return i ; return arr[i]=f(arr,arr[i]); } public static void merge(int i, int j){ i=find(i); j=find(j); if(rank[i]>=rank[j]){ rank[i]+=rank[j]; parent[j]=i; } else { rank[j]+=rank[i]; parent[i]=j; } } public static int help(boolean[] v){ HashSet<Integer> s = new HashSet<>(); for(int e=1;e<v.length;e++){ int i=find(e); if(v[i]) s.add(i); } // System.out.print(Arrays.toString(parent)); return s.size(); } static int help(int[][] arr, int i, int n, int[] heigh) { if(arr[i][0]==-1&&arr[i][1]==-1) return 0; if(arr[i][0]==-1) { return heigh[arr[i][1]]-1; } else if(arr[i][1]==-1) return heigh[arr[i][0]]-1; else { int op1 =heigh[arr[i][1]]-1+help(arr, arr[i][0], n, heigh); int op2 =heigh[arr[i][0]]-1+help(arr, arr[i][1], n, heigh); return Math.max(op1,op2); } } static int heights(int arr[][], int i , int heig[]) { if(arr[i][0]==-1&&arr[i][1]==-1) return 0; if(heig[i]!=-1) return heig[i]; if(arr[i][0]==-1) return heig[i]=1+heights(arr,arr[i][1],heig); if(arr[i][1]==-1) return heig[i]=1+heights(arr,arr[i][0],heig); else return heig[i]= 1+heights(arr,arr[i][1],heig)+heights(arr,arr[i][0],heig); } public static void main(String[] args) { try { FastReader in = new FastReader(); FastWriter out = new FastWriter(); long testCases =in.nextLong(); fl: while (testCases-- > 0) { long n =in.nextLong(); long arr[]=new long[(int) n]; for(int i =0;i<n;i++) arr[i]=in.nextLong(); HashSet<Long>set=new HashSet<>(); long curr=0; long max =0; for(int i =0;i<n;i++) { set.add(arr[i]); curr=curr+arr[i]; if(curr<=0) { System.out.println("No"); continue fl; } } set.clear(); curr=0; for(int i = (int) (n-1); i>=0; i--) { set.add(arr[i]); curr=curr+arr[i]; if(curr<=0) { System.out.println("No"); continue fl; } } System.out.println("Yes"); } out.close(); } catch (Exception e) { return; } } }
java
1286
B
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3 2 0 0 2 2 0 OutputCopyYES 1 2 1 InputCopy5 0 1 1 3 2 1 3 0 2 0 OutputCopyYES 2 3 2 1 2
[ "constructive algorithms", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
import java.io.*; import java.util.*; public class B { static ArrayList<Integer>[] adj; static ArrayList<Integer> subtree; static int[] ans, c; static boolean solve(int u) { boolean ret = true; for (int v : adj[u]) { ret &= solve(v); } subtree.clear(); dfs2(u, true); Collections.sort(subtree, (x, y) -> ans[x] - ans[y]); if (c[u] > subtree.size()) { return false; } if (c[u] == 0) ans[u] = 1; else { ans[u] = ans[subtree.get(c[u] - 1)] + 1; } for (int x = 0; x < adj.length; x++) if (ans[x] >= ans[u] && x != u) ans[x]++; return ret; } static void dfs2(int u, boolean start) { if (!start) subtree.add(u); for (int v : adj[u]) dfs2(v, false); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(), root = -1; subtree = new ArrayList(); adj = new ArrayList[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayList(); c = new int[n]; ans = new int[n]; for (int i = 0; i < n; i++) { int p = sc.nextInt() - 1; c[i] = sc.nextInt(); if (p != -1) { adj[p].add(i); } else root = i; } if (solve(root)) { out.println("YES"); for (int x : ans) out.print(x + " "); } else out.println("NO"); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } }
java
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3 tab one bat OutputCopy6 tabbat InputCopy4 2 oo ox xo xx OutputCopy6 oxxxxo InputCopy3 5 hello codef orces OutputCopy0 InputCopy9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji OutputCopy20 ababwxyzijjizyxwbaba NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; public class Main { static List<String> list = new ArrayList<>(); static HashSet<String> set = new HashSet<>(); static HashSet<String> hw = new HashSet<>(); public static void main(String[] args) { InputReader s = new InputReader(); int n = s.nextInt(); int k = s.nextInt(); StringBuilder l = new StringBuilder(); while (n-- > 0) { String str = s.next(); StringBuilder sb = new StringBuilder(str); if (sb.toString().equals(sb.reverse().toString())) hw.add(str); list.add(str); set.add(str); } int cnt = 0; for (int i = 0; i < list.size(); i++) { String cur = list.get(i); int len = cur.length(); StringBuilder sb = new StringBuilder(cur); if (!hw.contains(cur) && set.contains(sb.reverse().toString())) { cnt += 2*len; l.append(cur); set.remove(cur); set.remove(sb.reverse().toString()); hw.remove(cur); } } int len = 0; String bh = ""; for (String x : hw) { int nlen = x.length(); if (nlen > len) bh = x; } cnt+=bh.length(); String r = l.toString(); l.reverse().append(bh).append(r); System.out.println(cnt); System.out.println(l.toString()); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } }
java
1316
B
B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6 4 abab 6 qwerty 5 aaaaa 6 alaska 9 lfpbavjsm 1 p OutputCopyabab 1 ertyqw 3 aaaaa 1 aksala 6 avjsmbpfl 5 p 1 NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.
[ "brute force", "constructive algorithms", "implementation", "sortings", "strings" ]
import java.io.*; import java.lang.*; import java.util.*; public class Main { public static int mod = (int) 1e9 + 7; // **** -----> Disjoint Set Union(DSU) Start ********** public static int findPar(int node, int[] parent) { if (parent[node] == node) return node; return parent[node] = findPar(parent[node], parent); } public static boolean union(int u, int v, int[] rank, int[] parent) { u = findPar(u, parent); v = findPar(v, parent); if(u == v) return false; if (rank[u] < rank[v]) parent[u] = v; else if (rank[u] > rank[v]) parent[v] = u; else { parent[u] = v; rank[v]++; } return true; } // **** DSU Ends *********** public static String toBinary(int decimal) {StringBuilder sb = new StringBuilder();while (decimal > 0) {sb.append(decimal % 2);decimal = decimal / 2;}return sb.reverse().toString();} public static boolean isPalindrome(String s) {int i = 0, j = s.length() - 1;while (i < j) {if (s.charAt(i) != s.charAt(j))return false;i++;j--;}return true;} public static boolean isPalindrome(int[] arr) {int i = 0, j = arr.length - 1;while (i < j) {if (arr[i] != arr[j])return false;}return true;} public static int pow(int x, int y) {int res = 1;x = x % mod;if (x == 0)return 0;while (y > 0) {if ((y & 1) != 0)res = (res * x) % mod;y = y >> 1;x = (x * x) % mod;}return res;} public static int gcd(int a, int b) {if (b == 0)return a;return gcd(b, a % b);} public static long gcd(long a, long b) {if (b == 0)return a;return gcd(b, a % b);} public static void sort(long[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);long temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);} public static void reverse(int a[]) {int i, k, t, n = a.length;for (i = 0; i < n / 2; i++) {t = a[i];a[i] = a[n - i - 1];a[n - i - 1] = t;}} public static void sort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);} public static void revSort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);reverse(a);} public static long LCM(long a, long b) {if (a > b) {long t = a;a = b;b = t;}a /= gcd(a, b);return (a * b);} public static int findMax(int[] a, int left, int right) {int res = left;int max = a[left];for (int i = left + 1; i <= right; i++) {if (a[i] > max) {max = a[i];res = i;}}return res;} public static long findClosest(long arr[], long target) {int n = arr.length;if (target <= arr[0])return arr[0];if (target >= arr[n - 1])return arr[n - 1];int i = 0, j = n, mid = 0;while (i < j) {mid = (i + j) / 2;if (arr[mid] == target)return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];} public static long getClosest(long val1, long val2, long target) {if (target - val1 >= val2 - target)return val2;else return val1;} public static int findClosest(int arr[], int target) { int n = arr.length; if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];} public static int getClosest(int val1, int val2, int target) {if (target - val1 >= val2 - target)return val2;else return val1;} public static String reverse(String str) {String nstr = "";char ch;for (int i = 0; i < str.length(); i++) {ch = str.charAt(i);nstr = ch + nstr;}return nstr;} public static boolean isPrime(int n){if (n <= 1)return false;if (n <= 3)return true;if (n % 2 == 0 || n % 3 == 0)return false;for (int i = 5; i * i <= n; i = i + 6)if (n % i == 0 || n % (i + 2) == 0)return false;return true;} public static int xorSum(int arr[], int n){int bits = 0;for (int i = 0; i < n; ++i)bits |= arr[i];int ans = bits * (int)Math.pow(2, n-1);return ans;} public static ArrayList<Integer> primeFactors(int n) { ArrayList<Integer> res = new ArrayList<>();while (n%2 == 0) { res.add(2); n = n/2; } for (int i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;} static int lower_bound(int array[], int low, int high, int key){ int mid; while (low < high) { mid = low + (high - low) / 2; if (key <= array[mid]) high = mid; else low = mid + 1; } if (low < array.length && array[low] < key) low++; return low; } /********************************* Start Here ***********************************/ public static void main(String[] args) throws java.lang.Exception { if (System.getProperty("ONLINE_JUDGE") == null) { PrintStream ps = new PrintStream(new File("output.txt")); System.setOut(ps); } FastScanner sc = new FastScanner("input.txt"); int T = sc.nextInt(); // int T = 1; while (T-- > 0) { int n = sc.nextInt(); String s = sc.next(); char ch = 'z'; for(int i = 0; i < n; i++){ if(s.charAt(i) < ch) ch = s.charAt(i); } StringBuilder res = new StringBuilder(s); // System.out.println(ch); int ans = 1; for(int i = 0; i < n; i++){ if(s.charAt(i)==ch){ StringBuilder tmp = new StringBuilder(s.substring(i)); if((n-i)%2==0){ tmp.append(s.substring(0, i)); }else { for(int j = i-1; j >= 0; j--){ tmp.append(s.charAt(j)); } } int num = res.compareTo(tmp); if(num > 0) { res = tmp; ans = i+1; } // System.out.println(res +" " + tmp); } } System.out.println(res); System.out.println(ans); } System.out.close(); } // public static long solve(StringBuilder s1, StringBuilder s2, int i, int[] dp){ // if(i == s1.length()){ // return 0; // } // if(dp[i] != -1) return dp[i]; // if(s2.charAt(i)=='0'){ // } // return res; // } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { br = new BufferedReader(new InputStreamReader(System.in)); } } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { if (st == null || !st.hasMoreTokens()) { try { return br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken("\n"); } public String[] readStringArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = next(); } return a; } int nextInt() { return Integer.parseInt(nextToken()); } String next() { return nextToken(); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] read2dArray(int n, int m) { int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = nextInt(); } } return a; } long[][] read2dlongArray(int n, int m) { long[][] a = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = nextLong(); } } return a; } } }
java
1311
C
C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3 4 2 abca 1 3 10 5 codeforces 2 8 3 2 9 26 10 qwertyuioplkjhgfdsazxcvbnm 20 10 1 2 3 5 10 5 9 4 OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2 NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.
[ "brute force" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.TreeMap; public class PerformTheCombo { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pr=new PrintWriter(System.out); int t=Integer.parseInt(br.readLine()); while(t!=0){ solve(br,pr); t--; } pr.flush(); pr.close(); } public static void solve(BufferedReader br,PrintWriter pr) throws IOException{ String[] temp=br.readLine().split(" "); int n=Integer.parseInt(temp[0]); int m=Integer.parseInt(temp[1]); String s=br.readLine(); temp=br.readLine().split(" "); TreeMap<Integer,Integer> map=new TreeMap<>(); for(int i=0;i<m;i++){ int pos=Integer.parseInt(temp[i]); int start=0; int end=pos; map.put(start,map.getOrDefault(start,0)+1); map.put(end,map.getOrDefault(end,0)-1); } int[] count=new int[26]; int pressedTime=0; for(int i=0;i<n;i++){ if(map.containsKey(i)){ pressedTime+=map.get(i); } char button=s.charAt(i); count[button-'a']+=pressedTime; count[button-'a']++; } for(int i:count){ pr.print(i+" "); } pr.print('\n'); } }
java
1307
C
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb OutputCopy6 InputCopyusaco OutputCopy1 InputCopylol OutputCopy2 NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
[ "brute force", "dp", "math", "strings" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.sort; public class Round12 { public static void main(String[] args) { FastReader fastReader = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = 1; while (t-- > 0) { char c[] = fastReader.nextLine().toCharArray(); long ans = 0; long a1[] = new long[26]; long a2[][] = new long[26][26]; int n = c.length; for (int i = 0; i < n; i++) { int val = c[i] - 'a'; for (int j = 0; j < 26; j++) { a2[val][j] += a1[j]; } a1[val]++; } for (int i = 0; i < 26; i++) { ans = Math.max(ans, a1[i]); } for (int j = 0; j < 26; j++) { for (int i = 0; i < 26; i++) { ans = Math.max(a2[j][i], ans); } } out.println(ans); } out.close(); } // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final long LMAX = 9223372036854775807L; static Random __r = new Random(); // math util static int minof(int a, int b, int c) { return min(a, min(b, c)); } static int minof(int... x) { if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min; } static long minof(long a, long b, long c) { return min(a, min(b, c)); } static long minof(long... x) { if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min; } static int maxof(int a, int b, int c) { return max(a, max(b, c)); } static int maxof(int... x) { if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max; } static long maxof(long a, long b, long c) { return max(a, max(b, c)); } static long maxof(long... x) { if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max; } static int powi(int a, int b) { if (a == 0) return 0; int ans = 1; while (b > 0) { if ((b & 1) > 0) ans *= a; a *= a; b >>= 1; } return ans; } static long powl(long a, int b) { if (a == 0) return 0; long ans = 1; while (b > 0) { if ((b & 1) > 0) ans *= a; a *= a; b >>= 1; } return ans; } static int fli(double d) { return (int) d; } static int cei(double d) { return (int) ceil(d); } static long fll(double d) { return (long) d; } static long cel(double d) { return (long) ceil(d); } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static int[] exgcd(int a, int b) { if (b == 0) return new int[]{1, 0}; int[] y = exgcd(b, a % b); return new int[]{y[1], y[0] - y[1] * (a / b)}; } static long[] exgcd(long a, long b) { if (b == 0) return new long[]{1, 0}; long[] y = exgcd(b, a % b); return new long[]{y[1], y[0] - y[1] * (a / b)}; } static int randInt(int min, int max) { return __r.nextInt(max - min + 1) + min; } static long mix(long x) { x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31); } public static boolean[] findPrimes(int limit) { assert limit >= 2; final boolean[] nonPrimes = new boolean[limit]; nonPrimes[0] = true; nonPrimes[1] = true; int sqrt = (int) Math.sqrt(limit); for (int i = 2; i <= sqrt; i++) { if (nonPrimes[i]) continue; for (int j = i; j < limit; j += i) { if (!nonPrimes[j] && i != j) nonPrimes[j] = true; } } return nonPrimes; } // array util static void reverse(int[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(long[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(double[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(char[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void shuffle(int[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(long[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(double[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void rsort(int[] a) { shuffle(a); sort(a); } static void rsort(long[] a) { shuffle(a); sort(a); } static void rsort(double[] a) { shuffle(a); sort(a); } static int[] copy(int[] a) { int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static long[] copy(long[] a) { long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static double[] copy(double[] a) { double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static char[] copy(char[] a) { char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] ria(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = Integer.parseInt(next()); return a; } long nextLong() { return Long.parseLong(next()); } long[] rla(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = Long.parseLong(next()); return a; } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
java
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8 1 2 3 123 321 456 5 10 15 15 18 21 100 100 101 1 22 29 3 19 38 6 30 46 OutputCopy1 1 1 3 102 114 228 456 4 4 8 16 6 18 18 18 1 100 100 100 7 1 22 22 2 1 19 38 8 6 24 48
[ "brute force", "math" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) throws IOException { Reader input = new Reader(); int t = input.nextInt(); StringBuilder output = new StringBuilder(); while(t > 0) { int a = input.nextInt(); int b = input.nextInt(); int c = input.nextInt(); int min = b-a+c-b, toA, toB, m; int[] triples = new int[]{b, b, b}; int start = Math.max(a-min,0), end = c+min; for(int i = start+1; i <= end; ++i) { toA = countMove(a, i); if(toA >= min) continue; for(int j = i; j < end; j += i) { toB = countMove(b, j); if(toB+toA >= min) continue; for(int k = j; k < end; k += j) { m = toA+toB+countMove(c, k); if(m < min) { triples[0] = i; triples[1] = j; triples[2] = k; min = m; } } } } output.append(min); output.append("\n"); output.append(triples[0]); output.append(" "); output.append(triples[1]); output.append(" "); output.append(triples[2]); output.append(" "); output.append("\n"); --t; } System.out.print(output); } static int countMove(int from, int to) { if(to > from) return to-from; return from-to; } static class Reader { BufferedReader bufferedReader; StringTokenizer string; public Reader() { InputStreamReader inr = new InputStreamReader(System.in); bufferedReader = new BufferedReader(inr); } public String next() throws IOException { while(string == null || ! string.hasMoreElements()) { string = new StringTokenizer(bufferedReader.readLine()); } return string.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { return bufferedReader.readLine(); } } }
java
1305
B
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≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — 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  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()(( OutputCopy1 2 1 3 InputCopy)( OutputCopy0 InputCopy(()()) OutputCopy1 4 1 2 5 6 NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class B_Kuroni_and_Simple_Strings { public static void main(String[] args) { OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); FastReader f = new FastReader(); int t = 1; while(t-- > 0){ solve(f, out); } out.close(); } public static void solve(FastReader f, PrintWriter out) { String s = f.nextLine(); ArrayList<Integer> arrli = new ArrayList<>(); int i = 0; int j = s.length()-1; while(i < j) { if(s.charAt(i) != '(') { i++; } if(s.charAt(j) != ')') { j--; } if(j <= i) { break; } if(s.charAt(i) == '(' && s.charAt(j) == ')') { arrli.add(i+1); arrli.add(j+1); i++; j--; } } Collections.sort(arrli); if(arrli.size() == 0) { out.println(0); } else { out.println(1); out.println(arrli.size()); for(int num: arrli) { out.print(num + " "); } out.println(); } } public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } public static int gcd(int a, int b) { int dividend = a > b ? a : b; int divisor = a < b ? a : b; while(divisor > 0) { int reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } public static int lcm(int a, int b) { int lcm = gcd(a, b); int hcf = (a * b) / lcm; return hcf; } public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */
java
1312
B
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 OutputCopy7 1 5 1 3 2 4 6 1 3 5
[ "constructive algorithms", "sortings" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.InterruptedIOException; import java.security.PublicKey; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.StringTokenizer; public class Main { static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next(){ while(st==null || !st.hasMoreTokens()){ try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str=""; try { str=br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static void Parr(int[] arr) { for(int i=0;i<arr.length;i++) { System.out.print(arr[i]+" "); } System.out.println(); } static void sort(int[] a) { ArrayList<Integer> q = new ArrayList<>(); for (int i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } static void sort(long[] a) { ArrayList<Long> q = new ArrayList<>(); for (long i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } private static long gcd(long a, long b) { while (b > 0) { long temp = b; b = a % b; // % is remainder a = temp; } return a; } private static long lcm(long a, long b) { return a * (b / gcd(a, b)); } static long binpow(long a,long b) { long M=1000000007; long res=1; while(b>0) { if(b%2==1) { res=(res*a)%M; } a=(a*a)%M; b/=2; } return res; } static boolean ispalindrome(String s,int n) { for(int i=0;i<n;i++) { if(s.charAt(i)==s.charAt(s.length()-1-i)) { continue; } else { return false; } } return true; } static boolean isSquare(long x) { long y = (long)Math.sqrt(x); return y*y==x; } static int computeXOR(int n) { // If n is a multiple of 4 if (n % 4 == 0) return n; // If n%4 gives remainder 1 if (n % 4 == 1) return 1; // If n%4 gives remainder 2 if (n % 4 == 2) return n + 1; // If n%4 gives remainder 3 return 0; } static boolean prime[] = new boolean[100000 + 1]; public static void SoE(int n) { // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value in // prime[i] will finally be false if i is Not a // prime, else true. for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it numbers which // are multiple of p and are less than p^2 // are already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers // for (int i = 2; i <= n; i++) { // if (prime[i] == true) // System.out.print(i + " "); // } } static class Pair{ int idx; long val; public Pair(int idx,int val) { // TODO Auto-generated constructor stub this.idx=idx; this.val=val; } } //REMINDERS: //- CHECK FOR INTEGER-OVERFLOW BEFORE SUBMITTING //- CAN U BRUTEFORCE OVER SOMETHING, TO MAKE IT EASIER TO CALCULATE THE SOLUTION public static void main(String[] args) { // TODO Auto-generated method stub FastReader sc1=new FastReader(); int t=sc1.nextInt(); //SoE(100000); w:while(t-->0) { int n=sc1.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=sc1.nextInt(); } arr = Arrays.stream(arr). boxed(). sorted((a, b) -> b.compareTo(a)). // sort descending mapToInt(i -> i). toArray(); Parr(arr); } } }
java
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4 6 10 010010 5 3 10101 1 0 0 2 0 01 OutputCopy3 0 1 -1 NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.
[ "math", "strings" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) throws IOException { Reader input = new Reader(); int t = input.nextInt(); StringBuilder output = new StringBuilder(); while(t > 0) { int n = input.nextInt(); int x = input.nextInt(); char[] s = input.next().toCharArray(); output.append(solve(x, n, s)); --t; output.append("\n"); } System.out.print(output); } static int solve(int x, int n, char[] s) { int[] balance = new int[n]; balance[0] = s[0] == '0' ? 1 : -1; for(int i = 1; i < n; ++i) { balance[i] = balance[i-1] + (s[i] == '0' ? 1 : -1); } if(balance[n-1] == 0) { boolean hasX = false; for(int i = 0; i < n; ++i) { if(balance[i] == x) { hasX = true; break; } } if(hasX) return -1; else return 0; } int increase = balance[n-1]; int count = x == 0 ? 1 : 0; for(int i = 0; i < n; ++i) { if(increase < 0) { if(balance[i] > x) { int y = balance[i]-x; if(y%(-increase) == 0) { ++count; } } } else { if(balance[i] < x) { int y = x-balance[i]; if(y%increase == 0) { ++count; } } } if(balance[i] == x) { ++count; } } return count; } static class Reader { BufferedReader bufferedReader; StringTokenizer string; public Reader() { InputStreamReader inr = new InputStreamReader(System.in); bufferedReader = new BufferedReader(inr); } public String next() throws IOException { while(string == null || ! string.hasMoreElements()) { string = new StringTokenizer(bufferedReader.readLine()); } return string.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { return bufferedReader.readLine(); } } }
java
1293
A
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5 5 2 3 1 2 3 4 3 3 4 1 2 10 2 6 1 2 3 4 5 7 2 1 1 2 100 76 8 76 75 36 67 41 74 10 77 OutputCopy2 0 4 0 2 NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.
[ "binary search", "brute force", "implementation" ]
import java.math.BigInteger; import java.util.*; public class Main{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int testcase=sc.nextInt(); for(int tc=1;tc<=testcase;tc++){ //System.out.print("Case #"+tc+": "); int n = sc.nextInt(); int s = sc.nextInt(); int k = sc.nextInt(); Set<Integer> set = new HashSet<>(); for(int i=0;i<k;i++){ set.add(sc.nextInt()); } //Arrays.sort(arr); int i=s, j=s; int ans = 0; while(i>0 || j<=n){ if(i>0 && !set.contains(i)){ ans = s-i; break; } if(j<=n && !set.contains(j)){ ans = j-s; break; } i--; j++; } System.out.println(ans); } sc.close(); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } // method to return LCM of two numbers // static int lcm(int a, int b) // { // return (a / gcd(a, b)) * b; // } static int upper_bound(int arr[], int key) { int mid, N = arr.length; // Initialise starting index and // ending index int low = 0; int high = N; // Till low is less than high while (low < high && low != N) { // Find the index of the middle element mid = low + (high - low) / 2; // If key is greater than or equal // to arr[mid], then find in // right subarray if (key >= arr[mid]) { low = mid + 1; } // If key is less than arr[mid] // then find in left subarray else { high = mid; } } // If key is greater than last element which is // array[n-1] then upper bound // does not exists in the array if (low > N ) { low--; } // Print the upper_bound index return low; } static int lower_bound(int array[], int key) { // Initialize starting index and // ending index int low = 0, high = array.length; int mid; // Till high does not crosses low while (low < high) { // Find the index of the middle element mid = low + (high - low) / 2; // If key is less than or equal // to array[mid], then find in // left subarray if (key <= array[mid]) { high = mid; } // If key is greater than array[mid], // then find in right subarray else { low = mid + 1; } } // If key is greater than last element which is // array[n-1] then lower bound // does not exists in the array if(low==-1) low++; // Returning the lower_bound index return low; } static boolean palin(int arr[], int i, int j){ while(i < j){ if(arr[i] != arr[j]) return false; i++; j--; } return true; } static boolean palin(String s){ int i=0,j=s.length()-1; while(i<j){ if(s.charAt(i)!=s.charAt(j)) return false; i++; j--; } return true; } static long minSum(int arr[], int n, int k) { // k must be smaller than n if (n < k) { // System.out.println("Invalid"); return -1; } // Compute sum of first window of size k long res = 0; for (int i=0; i<k; i++) res += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. long curr_sum = res; for (int i=k; i<n; i++) { curr_sum += arr[i] - arr[i-k]; res = Math.min(res, curr_sum); } return res; } static int nextIndex(int a[], int x){ int n=a.length; for(int i=x;i<n-1;i++){ if(a[i]>a[i+1]){ return i; } } return n; } static void rev(int a[], int i, int j){ while(i<j){ int t=a[i]; a[i]=a[j]; a[j]=t; i++; j--; } } static int sorted(int arr[], int n) { // Array has one or no element or the // rest are already checked and approved. if (n == 1 || n == 0) return 1; // Unsorted pair found (Equal values allowed) if (arr[n - 1] < arr[n - 2]) return 0; // Last pair was sorted // Keep on checking return sorted(arr, n - 1); } static void sieveOfEratosthenes(int n, Set<Integer> set) { // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value in // prime[i] will finally be false if i is Not a // prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it numbers which // are multiple of p and are less than p^2 // are already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) set.add(i); } } static boolean isPowerOfTwo(int n) { return (int)(Math.ceil((Math.log(n) / Math.log(2)))) == (int)(Math.floor(((Math.log(n) / Math.log(2))))); } static int countBits(int number) { // log function in base 2 // take only integer part return (int)(Math.log(number) / Math.log(2) + 1); } public static void swap(int ans[], int i, int j) { int temp=ans[i]; ans[i]=ans[j]; ans[j]=temp; } static int power(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } }
java
1321
C
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≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 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≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8 bacabcab OutputCopy4 InputCopy4 bcda OutputCopy3 InputCopy6 abbbbb OutputCopy5 NoteThe 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.
[ "brute force", "constructive algorithms", "greedy", "strings" ]
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class C_Remove_Adjacent { static long mod = Long.MAX_VALUE; static OutputStream outputStream = System.out; static PrintWriter out = new PrintWriter(outputStream); static FastReader f = new FastReader(); public static void main(String[] args) { int t = 1; while(t-- > 0){ solve(); } out.close(); } public static void solve() { int n = f.nextInt(); String s = f.nextLine(); StringBuilder sb = new StringBuilder(s); for(char c = 'z'; c >= 'a'; c--) { int ind = 0; while(ind < sb.length()) { if((sb.charAt(ind) == c) && ((ind > 0 && sb.charAt(ind) == sb.charAt(ind-1)+1) || (ind < sb.length()-1 && sb.charAt(ind) == sb.charAt(ind+1)+1))) { sb.deleteCharAt(ind); } else { ind++; } } ind = sb.length()-1; while(ind >= 0) { if((sb.charAt(ind) == c) && ((ind > 0 && sb.charAt(ind) == sb.charAt(ind-1)+1) || (ind < sb.length()-1 && sb.charAt(ind) == sb.charAt(ind+1)+1))) { sb.deleteCharAt(ind); } ind--; } } out.println(n-sb.length()); } // Sort an array public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } // Find all divisors of n public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } // Check if n is prime or not public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } // Find gcd of a and b public static long gcd(long a, long b) { long dividend = a > b ? a : b; long divisor = a < b ? a : b; while(divisor > 0) { long reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } // Find lcm of a and b public static long lcm(long a, long b) { long lcm = gcd(a, b); long hcf = (a * b) / lcm; return hcf; } // Find factorial in O(n) time public static long fact(int n) { long res = 1; for(int i = 2; i <= n; i++) { res = res * i; } return res; } // Find power in O(logb) time public static long power(long a, long b) { long res = 1; while(b > 0) { if((b&1) == 1) { res = (res * a)%mod; } a = (a * a)%mod; b >>= 1; } return res; } // Find nCr public static long nCr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / (fact(r) * fact(n-r)); return ans; } // Find nPr public static long nPr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / fact(r); return ans; } // sort all characters of a string public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } // User defined class for fast I/O static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } boolean hasNext() { if (st != null && st.hasMoreTokens()) { return true; } String tmp; try { br.mark(1000); tmp = br.readLine(); if (tmp == null) { return false; } br.reset(); } catch (IOException e) { return false; } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */ // (a/b)%mod == (a * moduloInverse(b)) % mod; // moduloInverse(b) = power(b, mod-2);
java
1285
A
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4 LRLR OutputCopy5 NoteIn the example; Zoma may end up anywhere between −2−2 and 22.
[ "math" ]
import java.util.*; public class Test{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = sc.next(); int countL=0; int countR=0; for(int i=0;i<n;i++){ if(s.charAt(i)=='L'){ countL++; } else{ countR++; } } System.out.println(countL+countR+1); } }
java
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
import java.util.*; public class C1304 { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int q = scn.nextInt(); while (q-- > 0) { int n = scn.nextInt(); int m = scn.nextInt(); // maxmium and minimum that we can acheive in k minutes int mx = m; int mn = m; int ct = 0; boolean check = true; for (int i = 0; i < n; i++) { int k = scn.nextInt(); int l = scn.nextInt(); int r = scn.nextInt(); int tl = k - ct; mx += tl; mn -= tl; if (l > mx || r < mn) { check = false; } mx = Math.min(mx,r); mn = Math.max(mn,l); ct = k; } if(check){ System.out.println("yes"); }else{ System.out.println("no"); } } } }
java
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
import java.io.*; import java.lang.*; import java.util.*; public class Main { public static int mod = (int)1e9 + 7; // **** -----> Disjoint Set Union(DSU) Start ********** public static int findPar(int node, int[] parent) { if (parent[node] == node) return node; return parent[node] = findPar(parent[node], parent); } public static boolean union(int u, int v, int[] rank, int[] parent) { u = findPar(u, parent); v = findPar(v, parent); if(u == v) return false; if (rank[u] < rank[v]) parent[u] = v; else if (rank[u] > rank[v]) parent[v] = u; else { parent[u] = v; rank[v]++; } return true; } // **** DSU Ends *********** //Pair with int int public static class Pair{ public int a; public int b; Pair(int a , int b){ this.a = a; this.b = b; } @Override public String toString(){ return a + " -> " + b; } } public static String toBinary(int n) {return Integer.toBinaryString(n);} public static boolean isPalindrome(String s) {int i = 0, j = s.length() - 1;while (i < j) {if (s.charAt(i) != s.charAt(j))return false;i++;j--;}return true;} public static boolean isPalindrome(int[] arr) {int i = 0, j = arr.length - 1;while (i < j) {if (arr[i] != arr[j])return false;}return true;} public static int pow(int x, int y) {int res = 1;x = x % mod;if (x == 0)return 0;while (y > 0) {if ((y & 1) != 0)res = (res * x) % mod;y = y >> 1;x = (x * x) % mod;}return res;} public static int gcd(int a, int b) {if (b == 0)return a;return gcd(b, a % b);} public static long gcd(long a, long b) {if (b == 0)return a;return gcd(b, a % b);} public static void sort(long[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);long temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);} public static void reverse(int a[]) {int i, k, t, n = a.length;for (i = 0; i < n / 2; i++) {t = a[i];a[i] = a[n - i - 1];a[n - i - 1] = t;}} public static void sort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);} public static void revSort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);reverse(a);} public static long LCM(long a, long b) {if (a > b) {long t = a;a = b;b = t;}a /= gcd(a, b);return (a * b);} public static int findMax(int[] a, int left, int right) {int res = left;int max = a[left];for (int i = left + 1; i <= right; i++) {if (a[i] > max) {max = a[i];res = i;}}return res;} public static long findClosest(long arr[], long target) {int n = arr.length;if (target <= arr[0])return arr[0];if (target >= arr[n - 1])return arr[n - 1];int i = 0, j = n, mid = 0;while (i < j) {mid = (i + j) / 2;if (arr[mid] == target)return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];} public static long getClosest(long val1, long val2, long target) {if (target - val1 >= val2 - target)return val2;else return val1;} public static int findClosest(int arr[], int target) { int n = arr.length; if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];} public static int getClosest(int val1, int val2, int target) {if (target - val1 >= val2 - target)return val2;else return val1;} public static String reverse(String str) {StringBuilder sb = new StringBuilder(str);sb.reverse();return sb.toString();} public static boolean isPrime(int n){if (n <= 1)return false;if (n <= 3)return true;if (n % 2 == 0 || n % 3 == 0)return false;for (int i = 5; i * i <= n; i = i + 6)if (n % i == 0 || n % (i + 2) == 0)return false;return true;} public static int xorSum(int arr[], int n){int bits = 0;for (int i = 0; i < n; ++i)bits |= arr[i];int ans = bits * (int)Math.pow(2, n-1);return ans;} public static ArrayList<Integer> primeFactors(int n) { ArrayList<Integer> res = new ArrayList<>();while (n%2 == 0) { res.add(2); n = n/2; } for (int i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;} public static ArrayList<Long> primeFactors(long n) { ArrayList<Long> res = new ArrayList<>();while (n%2 == 0) { res.add(2L); n = n/2; } for (long i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;} static int lower_bound(int array[], int low, int high, int key){ int mid; while (low < high) { mid = low + (high - low) / 2; if (key <= array[mid]) high = mid; else low = mid + 1; } if (low < array.length && array[low] < key) low++; return low; } static long fastPower(long a, long b, long mod){ long ans = 1 ; while (b > 0) { if ((b&1) != 0) ans = (ans%mod * a%mod) %mod; b >>= 1 ; a = (a%mod * a%mod)%mod ; } return ans ; } /********************************* Start Here ***********************************/ // int mod = 1000000007; static HashMap<String, Integer> map; static boolean[] vis; public static void main(String[] args) throws java.lang.Exception { if (System.getProperty("ONLINE_JUDGE") == null) { PrintStream ps = new PrintStream(new File("output.txt")); System.setOut(ps); } FastScanner sc = new FastScanner("input.txt"); StringBuilder result = new StringBuilder(); // sieveOfEratosthenes(1000000); // int T = sc.nextInt(); int T = 1; for(int test = 1; test <= T; test++){ int n = sc.nextInt(); List<List<Integer>> tree = new ArrayList<>(); for(int i = 0; i <= n; i++) tree.add(new ArrayList<>()); int[][] arr = new int[n][2]; HashMap<String, Integer> map = new HashMap<>(); for(int i = 0; i < n-1; i++){ int u = sc.nextInt(), v = sc.nextInt(); tree.get(u).add(v); tree.get(v).add(u); arr[i][0] = u; arr[i][1] = v; map.put(u+"-"+v, -1); map.put(v+"-"+u, -1); } boolean[] vis = new boolean[n+1]; int c = solve(tree, 1, map, vis); // StringBuilder res = new StringBuilder(sb); if(c != -1){ for(int i = 0; i < n-1; i++){ String key = arr[i][0]+"-"+arr[i][1]; if(map.get(key) != -1) result.append(map.get(key)+"\n"); else { result.append(c+"\n"); c++; } } }else { c = 0; for(int i = 0; i < n-1; i++){ result.append(c+"\n"); c++; } } // result.append(res+"\n"); } System.out.println(result); System.out.close(); } public static int solve(List<List<Integer>> tree, int node, HashMap<String, Integer> map, boolean[]vis){ vis[node] = true; if(tree.get(node).size() > 2) { int i = 0; for(int nb : tree.get(node)){ map.put(node+"-"+nb, i); map.put(nb+"-"+node, i); i++; } return i; } for(int nb : tree.get(node)){ if(!vis[nb]){ int i = solve(tree, nb, map,vis); if(i != -1) return i; } } return -1; } // static void sieveOfEratosthenes(int n){ // boolean prime[] = new boolean[n + 1]; // for (int i = 0; i <= n; i++) // prime[i] = true; // for (int p = 2; p * p <= n; p++){ // if (prime[p] == true){ // for (int i = p * p; i <= n; i += p) // prime[i] = false; // } // } // for (int i = 2; i <= n; i++){ // if (prime[i] == true) // set.add(i); // } // } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { br = new BufferedReader(new InputStreamReader(System.in)); } } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { if (st == null || !st.hasMoreTokens()) { try { return br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken("\n"); } public String[] readStringArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = next(); } return a; } int nextInt() { return Integer.parseInt(nextToken()); } String next() { return nextToken(); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] read2dArray(int n, int m) { int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = nextInt(); } } return a; } long[][] read2dlongArray(int n, int m) { long[][] a = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = nextLong(); } } return a; } } }
java
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class RestoringPermutation { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); int count=0; while(count<t){ solve(br); count++; } } public static void solve(BufferedReader br) throws IOException{ int n=Integer.parseInt(br.readLine()); String[] temp=br.readLine().trim().split(" "); int[] nums=new int[n]; for(int i=0;i<n;i++){ nums[i]=Integer.parseInt(temp[i]); } int[] res=new int[n*2]; Arrays.fill(res,-1); TreeSet<Integer> available=new TreeSet<>(); for(int i=1;i<=n*2;i++){ available.add(i); } for(int i=0;i<n;i++){ int num=nums[i]; if(available.contains(num)==false){ System.out.println(-1); return; } res[i*2]=num; available.remove(num); } for(int i=0;i<res.length;i+=2){ int min=res[i]; var bigger=available.ceiling(min); if(bigger==null){ System.out.println(-1); return; } res[i+1]=bigger; available.remove(bigger); } output(res); } public static void output(int[] res){ for(int i:res){ System.out.print(i); System.out.print(' '); } System.out.print('\n'); } }
java
1325
A
A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2 2 14 OutputCopy1 1 6 4 NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.
[ "constructive algorithms", "greedy", "number theory" ]
// 1 Sec = 1e8 = 100000000 import java.util.Scanner; import java.util.Vector; import java.util.List; import java.util.ArrayList; public class Test{ public static void main(String[] args){ Scanner input = new Scanner(System.in); // GCD(a,b) + LCM(a,b) = x // Note: // GCD(A , A) = LCM(A , A) = A // GCD(1 , Value) = 1 // LCM(1 , Value) = Value // GCD(a,b) + LCM(a,b) = x --> GCD(1,b) + LCM(1,b) = x --> 1 + Value = x --> Value = x - 1 int t = input.nextInt(); int x; while(t-- != 0){ x = input.nextInt(); System.out.println(1 + " " + (x-1)); // We Will Consider The A = 1 And B = X - 1 Because He Said Print Any Of Pairs. } } static long gcd(long A , long B){ // O(Log(Max(A , B))) long Temp; while(B != 0){ Temp = A; A = B; B = Temp % B; } return A; } static long lcm(long A , long B){ // (A * B) / gcd(A, B); return A / gcd(A , B) * B; // Because If A = 1e18 And B = 1e18 Then Will Minimize This Step } }
java
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
[ "greedy" ]
import java.io.*; import java.math.*; import java.util.*; public class A { public static void main(String[] agrs) { FastScanner sc = new FastScanner(); // int yo = sc.nextInt(); // while(yo-->0) { int n = sc.nextInt(); int[] r = sc.readArray(n); int[] b = sc.readArray(n); boolean isEqual = true; boolean isZero = true; boolean isSpecial = true; for(int i = 0; i < n; i++) { if(r[i] != b[i]) { isEqual = false; } if(r[i]==1) { isZero = false; } if(r[i] == 1 && b[i] == 0) { isSpecial = false; } } if(isEqual || isZero || isSpecial) { System.out.println(-1); return; } List<Integer> indexes = new ArrayList<>(); for(int i = 0; i < n; i++) { if(r[i] == 1 && b[i] == 0) { indexes.add(i); } } int[] res = new int[n]; Arrays.fill(res, 1); for(int i = 1; i <= 1000; i++) { for(int j = 0; j < indexes.size(); j++) { res[indexes.get(j)] = i; } int rScore = cal(r,res); int bScore = cal(b,res); if(rScore > bScore) { System.out.println(i); break; } } } // } static int cal(int[] arr, int[] res) { int ans = 0; for(int i = 0; i < arr.length; i++) { ans += arr[i] * res[i]; } return ans; } static int mod = 1000000007; static long pow(int a, int b) { if(b == 0) { return 1; } if(b == 1) { return a; } if(b%2 == 0) { long ans = pow(a,b/2); return ans*ans; } else { long ans = pow(a,(b-1)/2); return a * ans * ans; } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
java
1321
C
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≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 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≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8 bacabcab OutputCopy4 InputCopy4 bcda OutputCopy3 InputCopy6 abbbbb OutputCopy5 NoteThe 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.
[ "brute force", "constructive algorithms", "greedy", "strings" ]
import java.util.*; import java.io.*; public class Main { static long mod = 1000000007; static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int t = 1; while( t-- > 0) { int n = sc.nextInt(); StringBuilder x = new StringBuilder(); x.append(sc.next()); boolean check = true; int ans = 0; while( check) { check = false; // out.println(x); for( int i = 25 ;i >= 1 ; i--) { for( int j = 0 ;j < x.length() ; j++) { if( j-1 >= 0 && x.charAt(j-1)-'a' == i-1 && x.charAt(j)-'a' == i) { x.deleteCharAt(j); j = 0; ans++; check = true; } else if( j+1 < x.length() && x.charAt(j+1) - 'a'== i-1 && x.charAt(j)-'a' == i) { x.deleteCharAt(j); j = 0; ans++; check = true; } } } } out.println(ans); } out.flush(); } /* * time for a change */ public static boolean ifpowof2(long n ) { return ((n&(n-1)) == 0); } static boolean isprime(long x ) { if( x== 2) { return true; } if( x%2 == 0) { return false; } for( long i = 3 ;i*i <= x ;i+=2) { if( x%i == 0) { return false; } } return true; } static boolean[] sieveOfEratosthenes(long n) { boolean prime[] = new boolean[(int)n + 1]; for (int i = 0; i <= n; i++) { prime[i] = true; } for (long p = 2; p * p <= n; p++) { if (prime[(int)p] == true) { for (long i = p * p; i <= n; i += p) prime[(int)i] = false; } } return prime; } public static int[] nextLargerElement(int[] arr, int n) { Stack<Integer> stack = new Stack<>(); int rtrn[] = new int[n]; rtrn[n-1] = -1; stack.push( n-1); for( int i = n-2 ;i >= 0 ; i--){ int temp = arr[i]; int lol = -1; while( !stack.isEmpty() && arr[stack.peek()] <= temp){ if(arr[stack.peek()] == temp ) { lol = stack.peek(); } stack.pop(); } if( stack.isEmpty()){ if( lol != -1) { rtrn[i] = lol; } else { rtrn[i] = -1; } } else{ rtrn[i] = stack.peek(); } stack.push( i); } return rtrn; } static void mysort(int[] arr) { for(int i=0;i<arr.length;i++) { int rand = (int) (Math.random() * arr.length); int loc = arr[rand]; arr[rand] = arr[i]; arr[i] = loc; } Arrays.sort(arr); } static void mySort(long[] arr) { for(int i=0;i<arr.length;i++) { int rand = (int) (Math.random() * arr.length); long loc = arr[rand]; arr[rand] = arr[i]; arr[i] = loc; } Arrays.sort(arr); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static long rightmostsetbit(long n) { return n&-n; } static long leftmostsetbit(long n) { long k = (long)(Math.log(n) / Math.log(2)); return k; } static HashMap<Long,Long> primefactor( long n){ HashMap<Long ,Long> hm = new HashMap<>(); long temp = 0; while( n%2 == 0) { temp++; n/=2; } if( temp!= 0) { hm.put( 2L, temp); } long c = (long)Math.sqrt(n); for( long i = 3 ; i <= c ; i+=2) { temp = 0; while( n% i == 0) { temp++; n/=i; } if( temp!= 0) { hm.put( i, temp); } } if( n!= 1) { hm.put( n , 1L); } return hm; } static ArrayList<Long> allfactors(long abs) { HashMap<Long,Integer> hm = new HashMap<>(); ArrayList<Long> rtrn = new ArrayList<>(); for( long i = 2 ;i*i <= abs; i++) { if( abs% i == 0) { hm.put( i , 0); hm.put(abs/i, 0); } } for( long x : hm.keySet()) { rtrn.add(x); } if( abs != 0) { rtrn.add(abs); } return rtrn; } public static int[][] prefixsum( int n , int m , int arr[][] ){ int prefixsum[][] = new int[n+1][m+1]; for( int i = 1 ;i <= n ;i++) { for( int j = 1 ; j<= m ; j++) { int toadd = 0; if( arr[i-1][j-1] == 1) { toadd = 1; } prefixsum[i][j] = toadd + prefixsum[i][j-1] + prefixsum[i-1][j] - prefixsum[i-1][j-1]; } } return prefixsum; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
java
1301
B
B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7 5 -1 10 -1 12 -1 5 -1 40 35 -1 35 6 -1 -1 9 -1 3 -1 2 -1 -1 2 0 -1 4 1 -1 3 -1 7 1 -1 7 5 2 -1 5 OutputCopy1 11 5 35 3 6 0 42 0 0 1 2 3 4 NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.
[ "binary search", "greedy", "ternary search" ]
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; import java.util.ArrayList; public class Solve{ static int[] arr; static int T,N; public static void main(String[] args){ FastScan fs = new FastScan(); int[] arr = new int[100001]; //adjs = new ArrayList<Integer>(); T = fs.nextInt(); while( T > 0 ){ //adjs.clear(); N = fs.nextInt(); arr[0] = fs.nextInt(); int max_diff = 0, max_adj = Integer.MIN_VALUE, min_adj = Integer.MAX_VALUE; for(int i=1;i<N;++i){ arr[i] = fs.nextInt(); if( arr[i] > -1 && arr[i-1] > -1 ){ max_diff = Math.max( max_diff, Math.abs(arr[i]-arr[i-1]) ); } else if( arr[i] == -1 && arr[i-1] > -1 ){ max_adj = Math.max( max_adj, arr[i-1] ); min_adj = Math.min( min_adj, arr[i-1] ); } else if( arr[i] > -1 && arr[i-1] == -1 ){ max_adj = Math.max( max_adj, arr[i] ); min_adj = Math.min( min_adj, arr[i] ); } } int k = (max_adj + min_adj)/2; int m = Math.max( max_diff, Math.max(max_adj-k, k-min_adj) ); System.out.println(m+" "+k); --T; } } } class FastScan{ BufferedReader br; StringTokenizer stok; public FastScan(){ br = new BufferedReader( new InputStreamReader(System.in) ); } String next(){ while( stok == null || !stok.hasMoreElements() ){ try{ stok = new StringTokenizer( br.readLine() ); }catch(IOException e){ e.printStackTrace(); } } return stok.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch(IOException e){ e.printStackTrace(); } return str; } int nextInt(){ return Integer.parseInt( this.next() ); } long nextLong(){ return Long.parseLong( this.next() ); } double nextDouble(){ return Double.parseDouble( this.next() ); } }
java
1288
A
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3 1 1 4 5 5 11 OutputCopyYES YES NO NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days.
[ "binary search", "brute force", "math", "ternary search" ]
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import static java.lang.Math.ceil; public class App { public static void main( String[] args ) { Scanner in = new Scanner(System.in); int datasetNum = Integer.parseInt(in.nextLine()); List<Integer[]> dataset = new ArrayList<>(); for (int i = 0; i < datasetNum; i++) { String[] stringDataset = in.nextLine().split(" "); Integer[] intDataset = new Integer[2]; for (int j = 0; j < stringDataset.length; j++) { intDataset[j] = Integer.parseInt(stringDataset[j]); } dataset.add(intDataset); } for (int i = 0; i < datasetNum; i++) { int deadlineDays = dataset.get(i)[0]; int workDays = dataset.get(i)[1]; boolean flag = false; if (deadlineDays >= workDays) { flag = true; } else { int x = deadlineDays; while(x > 0) { if (x + ceil((double)workDays / (x + 1)) <= deadlineDays) { flag = true; break; } else { x = x / 2; flag = false; } } } if (flag) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
java
1322
A
A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8 ))((())( OutputCopy6 InputCopy3 (() OutputCopy-1 NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.
[ "greedy" ]
import java.io.*; import java.util.*; public class Run { public static int mod = 1000000007; public static PrintWriter out = new PrintWriter(System.out); public static boolean testing = false; public static FastIO io; public static String input_file = "./input.txt"; static { try { io = new FastIO(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public static int[] sort(int[] arr) { List<Integer> nums = new ArrayList<>(); for (int el : arr) nums.add(el); Collections.sort(nums); int[] res = new int[arr.length]; for (int i = 0; i < arr.length; i++) res[i] = nums.get(i); return res; } public static long[] sort(long[] arr) { List<Long> nums = new ArrayList<>(); for (long el : arr) nums.add(el); Collections.sort(nums); long[] res = new long[arr.length]; for (int i = 0; i < arr.length; i++) res[i] = nums.get(i); return res; } public static void reverse(int[] arr, int i, int j) { while (i < j) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; ++i; --j; } } public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static int lowerBound(long[] arr, long x) { int l = -1; int r = arr.length; while (r > l + 1) { int m = l + (r - l) / 2; if (arr[m] <= x) l = m; else r = m; } return Math.max(0, l); } public static int upperBound(long[] arr, long x) { int l = -1; int r = arr.length; while (r > l + 1) { int m = l + (r - l) / 2; if (arr[m] >= x) r = m; else l = m; } return Math.min(arr.length - 1, r); } public static int log2(int a) { return (int) (Math.log(a) / Math.log(2)); } public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void main(String[] args) { int n = io.nextInt(); char[] arr = io.next().toCharArray(); int ans = 0; int curr = 0; int prev = 0; for (int i = 0; i < n; i++) { if (arr[i] == '(') ++curr; else --curr; if (curr < 0) ++ans; if (curr == 0 && prev < 0) ++ans; prev = curr; } if (curr != 0) ans = -1; out.write(ans + "\n"); out.close(); } static class CC implements Comparator<Pair> { public int compare(Pair o1, Pair o2) { if (o1.first == o2.first) return o1.second - o2.second; return o1.first - o2.first; } } static class Pair { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } @Override public String toString() { return "Pair{" + "first=" + first + ", second=" + second + '}'; } } static class FastIO { InputStreamReader s = new InputStreamReader(testing ? new FileInputStream(input_file) : System.in); BufferedReader br = new BufferedReader(s); StringTokenizer st = new StringTokenizer(""); FastIO() throws FileNotFoundException { } String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
java
1301
A
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4 aaa bbb ccc abc bca bca aabb bbaa baba imi mii iim OutputCopyNO YES YES NO NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.
[ "implementation", "strings" ]
import java.util.Arrays; import java.util.Scanner; public class ThreeStrings { public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); boolean[] ans = new boolean[t]; Arrays.fill(ans, true); for (int i = 0; i < t; i++) { String a = input.next(); String b = input.next(); String c = input.next(); for (int j = 0; j < a.length(); j++) { if (c.charAt(j) != a.charAt(j) && c.charAt(j) != b.charAt(j)) { ans[i] = false; break; } } } for (int i = 0; i < t; i++) { if (ans[i]) System.out.println("YES"); else System.out.println("NO"); } } }
java
1296
B
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6 1 10 19 9876 12345 1000000000 OutputCopy1 11 21 10973 13716 1111111111
[ "math" ]
import java.util.Scanner; /** * @author 明宇 * @version 1.0 */ public class MainT7 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int s = n; while (n >= 10) { s += n / 10; n = (n / 10) + (n % 10); } System.out.println(s); } } }
java
1141
F1
F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7 4 1 2 2 1 5 3 OutputCopy3 7 7 2 3 4 5 InputCopy11 -5 -4 -3 -2 -1 0 1 2 3 4 5 OutputCopy2 3 4 1 1 InputCopy4 1 1 1 1 OutputCopy4 4 4 1 1 2 2 3 3
[ "greedy" ]
import java.util.*; public class MyClass { static class Pair implements Comparable<Pair>{ int x,y; Pair(int x,int y){ this.x=x; this.y=y; } public int compareTo(Pair p){ return Integer.compare(this.y,p.y); } } public static void main(String args[]) { Scanner in =new Scanner(System.in); HashMap<Long,ArrayList<Pair>> hm=new HashMap<Long,ArrayList<Pair>>(); int n=in.nextInt(); int a[]=new int[n]; long sum[]=new long[n]; long s=0; for(int i=0;i<n;i++){ a[i]=in.nextInt(); s+=a[i]; sum[i]=s; } for(int i=0;i<n;i++){ for(int j=i;j<n;j++){ long x=sum[j]-sum[i]+a[i]; ArrayList<Pair> temp=new ArrayList<Pair>(); if(hm.containsKey(x)) { temp=hm.get(x); } temp.add(new Pair(i+1,j+1)); hm.put(x,temp); } } ArrayList<Pair> ans=new ArrayList<Pair>(); for(Map.Entry em:hm.entrySet()){ ArrayList<Pair> array=hm.get(em.getKey()); Collections.sort(array); int prev=0; ArrayList<Pair> temp=new ArrayList<Pair>(); for(int i=0;i<array.size();i++){ if(array.get(i).x>prev){ temp.add(new Pair(array.get(i).x,array.get(i).y)); prev=array.get(i).y; } } // System.out.println(temp.size()); if(temp.size()>ans.size()){ ans=(ArrayList<Pair>)temp.clone(); } } long g=-5; System.out.println(ans.size()); for(int i=0;i<ans.size();i++){ System.out.println(ans.get(i).x+" "+ans.get(i).y); } } }
java
1293
A
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5 5 2 3 1 2 3 4 3 3 4 1 2 10 2 6 1 2 3 4 5 7 2 1 1 2 100 76 8 76 75 36 67 41 74 10 77 OutputCopy2 0 4 0 2 NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.
[ "binary search", "brute force", "implementation" ]
import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Scanner; import java.io.BufferedWriter; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; public class connerajftgdhjgfszdjsgb { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); int tt = in.nextInt(); for(int w = 0; w<tt; w++) { int n = in.nextInt(); int s = in.nextInt(); //gdje se nalazi// int k = in.nextInt(); // broj zatvorenih// int[] a = new int[k]; HashMap<Integer,Integer> hash =new HashMap<>(); for(int i=0; i<k; i++) { a[i] = in.nextInt(); hash.put(a[i], 1); } int ans = 0; for(int i = 0; i<=k; i++) { if( s-i>0 && !hash.containsKey(s-i)) { ans = i; break; } else if( s+i<=n && !hash.containsKey(s+i)) { ans = i; break; } } log.write(ans+"\n"); log.flush(); } } }
java
1313
B
B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
[ "constructive algorithms", "greedy", "implementation", "math" ]
import java.io.*; import java.lang.*; import java.util.*; public class ComdeFormces { static int x[]= {0,-1,1,1,1,1,-1,-1}; static int y[]= {-1,0,0,0,1,-1,1,-1}; // static int dp[][][]; static int seg[]; static int E; static class Trie{ Trie a[]; int ind; public Trie() { this.a=new Trie[3]; this.ind=-1; } } static long ncr[][]; static int cst; static HashMap<Integer,Integer> hm; static int dp[][]; static ArrayList<Integer> tp; public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub FastReader sc=new FastReader(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); // OutputStream out = new BufferedOutputStream ( System.out ); int t=sc.nextInt(); int tc=1; // InverseofNumber(m); // InverseofFactorial(m); // factorial(m); // while(t--!=0) { int n=sc.nextInt(); int x=sc.nextInt(); int y=sc.nextInt(); if(n==1) { log.write("1 1\n"); continue; } int best=0; int s=1; int e=x-1; while(s<=e) { int m=s+(e-s)/2; if(m+(y==n?n-1:n)<=x+y) { s=m+1; } else e=m-1; } best+=s-1; s=1; e=y-1; while(s<=e) { int m=s+(e-s)/2; if(m+(x==n?n-1:n)<=x+y) { s=m+1; } else e=m-1; } best+=Math.max(s-1-best, 0); int worst=0; s=x+1; e=n; while(s<=e) { int m=s+(e-s)/2; if((y==1?2:1)+m<=x+y)s=m+1; else e=m-1; } worst+=n-s+1; s=y+1; e=n; while(s<=e) { int m=s+(e-s)/2; if((x==1?2:1)+m<=x+y)s=m+1; else e=m-1; } worst+=Math.max(n-s+1-worst, 0); log.write((best+1)+" "+(n-worst)+"\n"); log.flush(); } } static int N = 1000001; // Array to store inverse of 1 to N static long[] factorialNumInverse = new long[N + 1]; // Array to precompute inverse of 1! to N! static long[] naturalNumInverse = new long[N + 1]; // Array to store factorial of first N numbers static long[] fact = new long[N + 1]; // Function to precompute inverse of numbers public static void InverseofNumber(int p) { naturalNumInverse[0] = naturalNumInverse[1] = 1; for(int i = 2; i <= N; i++) naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p; } // Function to precompute inverse of factorials public static void InverseofFactorial(int p) { factorialNumInverse[0] = factorialNumInverse[1] = 1; // Precompute inverse of natural numbers for(int i = 2; i <= N; i++) factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p; } // Function to calculate factorial of 1 to N public static void factorial(int p) { fact[0] = 1; // Precompute factorials for(int i = 1; i <= N; i++) { fact[i] = (fact[i - 1] * (long)i) % p; } } // Function to return nCr % p in O(1) time public static long Binomial(int N, int R, int p) { // n C r = n!*inverse(r!)*inverse((n-r)!) long ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p; return ans; } public static int m=(int)(998244353); public static int mul(int a, int b) { return ((a%m)*(b%m))%m; } public static long mul(long a, long b) { return ((a%m)*(b%m))%m; } public static int add(int a, int b) { return ((a%m)+(b%m))%m; } public static long add(long a, long b) { return ((a%m)+(b%m))%m; } public static long sub(long a,long b) { return ((a%m)-(b%m)+m)%m; } static long gcd(long a,long b) { if(b==0)return a; else return gcd(b,a%b); } static int gcd(int a,int b) { if(b==0)return a; else return gcd(b,a%b); } static long ncr(int n, int r){ if(r>n-r)r=n-r; long ans=1; long m=(int)(1e9+7); for(int i=0;i<r;i++){ ans=ans*(n-i); ans/=i+1; } return ans; } public static class num{ long v; } static long gcd(long a,long b,num x,num y) { if(b==0) { x.v=1; y.v=0; return a; } num x1=new num(); num y1=new num(); long ans=gcd(b,a%b,x1,y1); x.v=y1.v; y.v=x1.v-(a/b)*y1.v; return ans; } static long inverse(long b,long m) { num x=new num(); num y=new num(); long gc=gcd(b,m,x,y); if(gc!=1) { return -1; } return (x.v%m+m)%m; } static long div(long a,long b,long m) { a%=m; if(inverse(b,m)==-1)return a/b; return (inverse(b,m)*a)%m; } public static class trip{ int a; int b; long c; int d; public trip(int a,int b,long c,int d) { this.a=a; this.b=b; this.c=c; this.d=d; } } static void mergesort(int[] a,int start,int end) { if(start>=end)return ; int mid=start+(end-start)/2; mergesort(a,start,mid); mergesort(a,mid+1,end); merge(a,start,mid,end); } static void merge(int[] a, int start,int mid,int end) { int ptr1=start; int ptr2=mid+1; int b[]=new int[end-start+1]; int i=0; while(ptr1<=mid && ptr2<=end) { if(a[ptr1]<=a[ptr2]) { b[i]=a[ptr1]; ptr1++; i++; } else { b[i]=a[ptr2]; ptr2++; i++; } } while(ptr1<=mid) { b[i]=a[ptr1]; ptr1++; i++; } while(ptr2<=end) { b[i]=a[ptr2]; ptr2++; i++; } for(int j=start;j<=end;j++) { a[j]=b[j-start]; } } public static class FastReader { BufferedReader b; StringTokenizer s; public FastReader() { b=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(s==null ||!s.hasMoreElements()) { try { s=new StringTokenizer(b.readLine()); } catch(IOException e) { e.printStackTrace(); } } return s.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=b.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } boolean hasNext() { if (s != null && s.hasMoreTokens()) { return true; } String tmp; try { b.mark(1000); tmp = b.readLine(); if (tmp == null) { return false; } b.reset(); } catch (IOException e) { return false; } return true; } } public static class pair{ int a; int b; public pair(int a,int b) { this.a=a; this.b=b; } @Override public String toString() { return "{"+this.a+" "+this.b+"}"; } } static long pow(long a, long pw) { long temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return mul(temp,temp); return mul(a,mul(temp,temp)); } public static int md=998244353; static int pow(int a, int pw) { int temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*temp; } }
java
1304
A
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5 0 10 2 3 0 10 3 3 900000000 1000000000 1 9999999 1 2 1 1 1 3 1 1 OutputCopy2 -1 10 -1 1 NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
[ "math" ]
import java.util.*; public class CP { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int testcases = sc.nextInt(); while(testcases-->0){ long x = sc.nextLong(); long y = sc.nextLong(); long a = sc.nextLong(); long b = sc.nextLong(); long v = Math.abs(x-y); long z = Math.abs(a+b); if(v%z==0){ System.out.println(v/z); } else{ System.out.println("-1"); } } } }
java
1296
A
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5 2 2 3 4 2 2 8 8 3 3 3 3 4 5 5 5 5 4 1 1 1 1 OutputCopyYES NO YES NO NO
[ "math" ]
import java.util.*; public class MyClass { public static void main(String args[]) { Scanner kb = new Scanner(System.in); int t = kb.nextInt(); while(t-- > 0) { int n = kb.nextInt(); int even=0; int odd=0; int temp=n; while(n-- > 0) { if(kb.nextInt() % 2 == 0) { even++; } else { odd++; } } if(even == 0) { if(temp%2==0) { System.out.println("NO"); } else { System.out.println("YES"); } } else if(odd == 0) { System.out.println("NO"); } else { System.out.println("YES"); } } } }
java
1305
B
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≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — 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  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()(( OutputCopy1 2 1 3 InputCopy)( OutputCopy0 InputCopy(()()) OutputCopy1 4 1 2 5 6 NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
import java.util.*; import java.lang.*; import java.io.*; public class Main { static long mod = (int)1e9+7; static PrintWriter out=new PrintWriter(new BufferedOutputStream(System.out)); static char a[]; static ArrayList<Integer> ans; public static void main (String[] args) throws java.lang.Exception { FastReader sc =new FastReader(); // int t=sc.nextInt(); int t=1; O : while(t-->0) { a=sc.next().toCharArray(); ans=new ArrayList<>(); recur(0 , a.length-1); if(ans.size()==0){ out.println(0); continue; } out.println("1\n"+ans.size()); Collections.sort(ans); for(int i=0;i<ans.size();i++){ out.print(ans.get(i)+ " "); } out.println(); } out.flush(); } public static void recur(int l, int r) { if (l >= r) return; if (a[l]=='(' && a[r]==')'){ ans.add(l+1); ans.add(r+1); recur(l+1,r-1); } else if(a[l] != '('){ recur(l+1,r); } else if(a[r] != ')') { recur(l,r-1); } } static void printN() { System.out.println("NO"); } static void printY() { System.out.println("YES"); } static int findfrequencies(int a[],int n) { int count=0; for(int i=0;i<a.length;i++) { if(a[i]==n) { count++; } } return count; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readArrayLong(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } public static int[] radixSort2(int[] a) { int n = a.length; int[] c0 = new int[0x101]; int[] c1 = new int[0x101]; int[] c2 = new int[0x101]; int[] c3 = new int[0x101]; for(int v : a) { c0[(v&0xff)+1]++; c1[(v>>>8&0xff)+1]++; c2[(v>>>16&0xff)+1]++; c3[(v>>>24^0x80)+1]++; } for(int i = 0;i < 0xff;i++) { c0[i+1] += c0[i]; c1[i+1] += c1[i]; c2[i+1] += c2[i]; c3[i+1] += c3[i]; } int[] t = new int[n]; for(int v : a)t[c0[v&0xff]++] = v; for(int v : t)a[c1[v>>>8&0xff]++] = v; for(int v : a)t[c2[v>>>16&0xff]++] = v; for(int v : t)a[c3[v>>>24^0x80]++] = v; return a; } static int[] EvenOddArragement(int nums[]) { int i1=0,i2=nums.length-1; while(i1<i2){ while(nums[i1]%2==0 && i1<i2){ i1++; } while(nums[i2]%2!=0 && i2>i1){ i2--; } int temp=nums[i1]; nums[i1]=nums[i2]; nums[i2]=temp; } return nums; } static int gcd(int a, int b) { while (b != 0) { int t = a; a = b; b = t % b; } return a; } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<Integer, Integer> > list = new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() { public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // put data from sorted list to hashmap HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } static int DigitSum(int n) { int r=0,sum=0; while(n>=0) { r=n%10; sum=sum+r; n=n/10; } return sum; } static boolean checkPerfectSquare(int number) { double sqrt=Math.sqrt(number); return ((sqrt - Math.floor(sqrt)) == 0); } static boolean isPowerOfTwo(int n) { if(n==0) return false; return (int)(Math.ceil((Math.log(n) / Math.log(2)))) == (int)(Math.floor(((Math.log(n) / Math.log(2))))); } static boolean isPrime2(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } if (n % 2 == 0) { return false; } for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) { if (n % i == 0) { return false; } } return true; } static String minLexRotation(String str) { int n = str.length(); String arr[] = new String[n]; String concat = str + str; for(int i=0;i<n;i++) { arr[i] = concat.substring(i, i + n); } Arrays.sort(arr); return arr[0]; } static String maxLexRotation(String str) { int n = str.length(); String arr[] = new String[n]; String concat = str + str; for (int i = 0; i < n; i++) { arr[i] = concat.substring(i, i + n); } Arrays.sort(arr); return arr[arr.length-1]; } static class P implements Comparable<P> { int i, j; public P(int i, int j) { this.i=i; this.j=j; } public int compareTo(P o) { return Integer.compare(i, o.i); } } static class pair{ int i,j; pair(int x,int y){ i=x; j=y; } } static int binary_search(int a[],int value) { int start=0; int end=a.length-1; int mid=start+(end-start)/2; while(start<=end) { if(a[mid]==value) { return mid; } if(a[mid]>value) { end=mid-1; } else { start=mid+1; } mid=start+(end-start)/2; } return -1; } }
java
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4 6 10 010010 5 3 10101 1 0 0 2 0 01 OutputCopy3 0 1 -1 NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.
[ "math", "strings" ]
import java.io.*; import java.util.*; import java.math.*; public class Main{ public static void main(String[]args)throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int T=Integer.parseInt(br.readLine()); while(T>0){ StringTokenizer st=new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int x=Integer.parseInt(st.nextToken()); String s=br.readLine(); int b[]=new int[n]; int zero=0,one=0; for(int i=0;i<n;i++){ if(s.charAt(i)=='1'){ one++; } else{ zero++; } b[i]=zero-one; } if(b[n-1]==0){ boolean ok=false; for(int i=0;i<n;i++){ if(b[i]==x){ ok=true; break; } } if(ok){ System.out.println(-1); } else{ System.out.println(0); } } else if(b[n-1]>0){ int cnt=0; if(x==0){ cnt=1; } for(int i=0;i<n;i++){ if(b[i]<=x && (x-b[i])%(b[n-1])==0){ cnt++; } } System.out.println(cnt); } else{ int cnt=0; if(x==0){ cnt=1; } for(int i=0;i<n;i++){ if(b[i]>=x && (b[i]-x)%(Math.abs(b[n-1]))==0){ cnt++; } } System.out.println(cnt); } T--; } } }
java
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; import static java.lang.Double.parseDouble; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.in; import static java.lang.System.out; public class Restoring_Permutation { public static void main(String[] args) { try { FastReader in = new FastReader(); FastWriter out = new FastWriter(); int test = in.nextInt(); while (test > 0) { //Your Code Here int n = in.nextInt(); int[] array = new int[n]; for (int i = 0; i < array.length; i++) { array[i] = in.nextInt(); } calc(n, array); test--; } out.close(); } catch (Exception e) { return; } } private static void calc(int n, int[] array) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < array.length; i++) { list.add(array[i]); list.add(0); } for (int i = 0; i < 2 * n; i = i + 2) { int value = list.get(i) + 1; while (value <= 2 * n) { if (!list.contains(value)) { list.set(i + 1, value); break; } else { value++; } } } boolean check = false; for (int i = 1; i <= 2 * n; i++) { if (!list.contains(i)) { check = true; break; } } if (check) { out.println(-1); } else { for (Integer i : list) { out.print(i + " "); } out.println(""); } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return parseInt(next()); } long nextLong() { return parseLong(next()); } double nextDouble() { return parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } }
java
1313
C2
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "data structures", "dp", "greedy" ]
/* "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." Just have Patience + 1... */ import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = 1; for (int t = 1; t <= test; t++) { solve(); } out.close(); } private static void solve() { int n = sc.nextInt(); int[] maxHeight = new int[n]; for (int i = 0; i < n; i++) { maxHeight[i] = sc.nextInt(); } int[] prevSmallerHeight = getPreviousSmallerHeights(maxHeight, n); int[] nextSmallerHeight = getNextSmallerHeights(maxHeight, n); long[] prefixSkyscrapers = getPrefixSkyscraper(prevSmallerHeight, maxHeight, n); long[] suffixSkyscrapers = getSuffixSkyscraper(nextSmallerHeight, maxHeight, n); long maxSkyscraperFloors = getTotalFloorsWithFixedPeak(prefixSkyscrapers, suffixSkyscrapers, maxHeight, 0); int maxSkyscrapersIndex = 0; for (int i = 1; i < n; i++) { long totalFloors = getTotalFloorsWithFixedPeak(prefixSkyscrapers, suffixSkyscrapers, maxHeight, i); if (totalFloors > maxSkyscraperFloors) { maxSkyscraperFloors = totalFloors; maxSkyscrapersIndex = i; } } long[] perfectHeights = new long[n]; perfectHeights[maxSkyscrapersIndex] = maxHeight[maxSkyscrapersIndex]; long atMost = maxHeight[maxSkyscrapersIndex]; for (int i = maxSkyscrapersIndex - 1; i >= 0; i--) { atMost = Math.min(atMost, maxHeight[i]); perfectHeights[i] = atMost; } atMost = maxHeight[maxSkyscrapersIndex]; for (int i = maxSkyscrapersIndex + 1; i < n; i++) { atMost = Math.min(atMost, maxHeight[i]); perfectHeights[i] = atMost; } for (int i = 0; i < n; i++) { out.print(perfectHeights[i] + " "); } out.println(); } private static long getTotalFloorsWithFixedPeak(long[] prefixSkyscrapers, long[] suffixSkyscrapers, int[] maxHeight, int index) { return prefixSkyscrapers[index] + suffixSkyscrapers[index] - maxHeight[index]; } private static int[] getPreviousSmallerHeights(int[] maxHeight, int n) { int[] prevSmallerHeight = new int[n]; Stack<Integer> stack = new Stack<>(); for (int i = 0; i < n; i++) { while (!stack.isEmpty() && maxHeight[stack.peek()] >= maxHeight[i]) { stack.pop(); } if (!stack.isEmpty()) { prevSmallerHeight[i] = stack.peek(); }else { prevSmallerHeight[i] = -1; } stack.add(i); } return prevSmallerHeight; } private static int[] getNextSmallerHeights(int[] maxHeight, int n) { int[] nextSmallerHeight = new int[n]; Stack<Integer> stack = new Stack<>(); for (int i = n - 1; i >= 0; i--) { while (!stack.isEmpty() && maxHeight[stack.peek()] >= maxHeight[i]) { stack.pop(); } if (!stack.isEmpty()) { nextSmallerHeight[i] = stack.peek(); }else { nextSmallerHeight[i] = -1; } stack.add(i); } return nextSmallerHeight; } private static long[] getPrefixSkyscraper(int[] prevSmallerHeight, int[] maxHeight, int n) { long[] prefixSkyscrapers = new long[n]; for (int i = 0; i < n; i++) { if (prevSmallerHeight[i] == -1) { prefixSkyscrapers[i] = (long) (i + 1) * maxHeight[i]; }else { prefixSkyscrapers[i] = (long) (i - prevSmallerHeight[i]) * maxHeight[i] + prefixSkyscrapers[prevSmallerHeight[i]]; } } return prefixSkyscrapers; } private static long[] getSuffixSkyscraper(int[] nextSmallerHeight, int[] maxHeight, int n) { long[] suffixSkyscrapers = new long[n]; for (int i = n - 1; i >= 0; i--) { if (nextSmallerHeight[i] == -1) { suffixSkyscrapers[i] = (long) (n - i) * maxHeight[i]; }else { suffixSkyscrapers[i] = (long) (nextSmallerHeight[i] - i) * maxHeight[i] + suffixSkyscrapers[nextSmallerHeight[i]]; } } return suffixSkyscrapers; } public static FastReader sc; public static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } } return str.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } return str; } } }
java
1286
A
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≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5 0 5 0 2 3 OutputCopy2 InputCopy7 1 0 0 5 0 0 2 OutputCopy1 NoteIn 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.
[ "dp", "greedy", "sortings" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Solution { static int n, o = 0, e = 0; static int[] a; static Integer[][][] memo; static int[] zeros; public static void main(String[] args) throws IOException { Reader input = new Reader(); n = input.nextInt(); a = new int[n]; for(int i = 0; i < n; ++i) { a[i] = input.nextInt(); } boolean[] used = new boolean[n+1]; zeros = new int[n]; for(int i = 0; i < n; ++i) { used[a[i]] = true; zeros[i] = (a[i] == 0 ? 1 : 0)+(i > 0 ? zeros[i-1] : 0); } for(int i = 1; i <= n; ++i) { if(!used[i]) { if(i%2 == 0) ++e; else ++o; } } memo = new Integer[n][e+1][2]; System.out.println(solve(0, e, 0)); } static int solve(int p, int evens, int prevParty) { if(p >= n) { return 0; } if(memo[p][evens][prevParty] != null) { return memo[p][evens][prevParty]; } int answer = n+1; if(a[p] != 0) { answer = p == 0 ? 0 : (a[p]%2 == prevParty ? 0 : 1); answer += solve(p+1, evens, a[p]%2); } else { if(evens > 0) { int test = p == 0 ? 0 : (prevParty == 0 ? 0 : 1); test += solve(p+1, evens-1, 0); answer = Math.min(test, answer); } int odds = p == 0 ? o : (o-(zeros[p-1]-(e-evens))); if(odds > 0) { int test = p == 0 ? 0 : (prevParty == 0 ? 1 : 0); test += solve(p+1, evens, 1); answer = Math.min(test, answer); } } memo[p][evens][prevParty] = answer; return answer; } static class Reader { BufferedReader bufferedReader; StringTokenizer string; public Reader() { InputStreamReader inr = new InputStreamReader(System.in); bufferedReader = new BufferedReader(inr); } public String next() throws IOException { while(string == null || ! string.hasMoreElements()) { string = new StringTokenizer(bufferedReader.readLine()); } return string.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { return bufferedReader.readLine(); } } }
java
1295
E
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3 3 1 2 7 1 4 OutputCopy4 InputCopy4 2 4 1 3 5 9 8 3 OutputCopy3 InputCopy6 3 5 1 6 2 4 9 1 9 9 1 9 OutputCopy2
[ "data structures", "divide and conquer" ]
/** * ******* Created on 25/2/20 8:03 PM******* */ import java.io.*; import java.util.*; public class ED81E implements Runnable { private static final int MAX = 2*(int) (1E5 + 5); private static final int MOD = (int) (1E9 + 7); private static final long Inf = (long) (1E14 + 10); int n; private void solve() throws IOException { n = reader.nextInt(); int[] p = new int[MAX]; int[] rp = new int[MAX]; int[] a = new int[MAX]; for(int i=0;i<n;i++){ p[i] = reader.nextInt(); p[i]--; rp[p[i]]=i; } for(int i=0;i<n;i++) a[i] = reader.nextInt(); b[0] = a[0]; for(int i=1;i<n;i++) b[i] = a[i] + b[i-1]; build(0,0,n); long res = get(0, n - 1); for(int i = 0; i < n; ++i){ int pos = rp[i]; upd(pos, n, -a[pos]); upd(0, pos, a[pos]); res = Math.min(res, get(0, n - 1)); } writer.println(res); } long[] b = new long[MAX]; long[] t = new long[4*MAX]; long[] add = new long[4*MAX]; private void build(int v, int l, int r) { if(r-l ==1){ t[v] = b[l]; return; } int mid = (l+r)/2; build(v*2 +1, l, mid); build(2*v+2, mid,r); t[v] = Math.min(t[2*v+1], t[2*v+2]); } void push(int v, int l, int r){ if(add[v] != 0){ if(r - l > 1) for(int i = v+v+1; i < v+v+3; ++i){ add[i] += add[v]; t[i] += add[v]; } add[v] = 0; } } void upd(int v, int l, int r, int L, int R, int x){ if(L >= R) return; if(l == L && r == R){ add[v] += x; t[v] += x; push(v, l, r); return; } push(v, l, r); int mid = (l + r) / 2; upd(v * 2 + 1, l, mid, L, Math.min(mid, R), x); upd(v * 2 + 2, mid, r, Math.max(mid, L), R, x); t[v] = Math.min(t[v * 2 + 1], t[v * 2 + 2]); } void upd(int l, int r, int x){ upd(0, 0, n, l, r, x); } long get(int v, int l, int r, int L, int R){ if(L >= R) return Inf; push(v, l, r); if(l == L && r == R) return t[v]; int mid = (l + r) / 2; return Math.min(get(v * 2 + 1, l, mid, L, Math.min(R, mid)), get(v * 2 + 2, mid, r, Math.max(L, mid), R)); } long get(int l, int r){ return get(0, 0, n, l, r); } public static void main(String[] args) throws IOException { try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) { new ED81E().run(); } } StandardInput reader; PrintWriter writer; @Override public void run() { try { reader = new StandardInput(); writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); } } interface Input extends Closeable { String next() throws IOException; default int nextInt() throws IOException { return Integer.parseInt(next()); } default long nextLong() throws IOException { return Long.parseLong(next()); } default double nextDouble() throws IOException { return Double.parseDouble(next()); } default int[] readIntArray() throws IOException { return readIntArray(nextInt()); } default int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int i = 0; i < array.length; i++) { array[i] = nextInt(); } return array; } default long[] readLongArray(int size) throws IOException { long[] array = new long[size]; for (int i = 0; i < array.length; i++) { array[i] = nextLong(); } return array; } } private static class StandardInput implements Input { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer stringTokenizer; @Override public void close() throws IOException { reader.close(); } @Override public String next() throws IOException { if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } } }
java
1316
C
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2 1 1 2 2 1 OutputCopy1 InputCopy2 2 999999937 2 1 3 1 OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.
[ "constructive algorithms", "math", "ternary search" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); CPrimitivePrimes solver = new CPrimitivePrimes(); solver.solve(1, in, out); out.close(); } static class CPrimitivePrimes { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); int p = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int res = 0; for (int i = 0; i < n; i++) { if (a[i] % p != 0) { res += i; break; } } int[] b = new int[m]; for (int i = 0; i < m; i++) { b[i] = in.nextInt(); } for (int i = 0; i < m; i++) { if (b[i] % p != 0) { res += i; break; } } out.println(res); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
java
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4 1 2 3 2 3 4 2 1 2 5 1 3 3 OutputCopy5 3 5 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 OutputCopy5 3 1 2 1 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 OutputCopy-1
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.function.IntUnaryOperator; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); Output out = new Output(outputStream); FBerlandBeauty solver = new FBerlandBeauty(); solver.solve(1, in, out); out.close(); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28); thread.start(); thread.join(); } static class FBerlandBeauty { private final int iinf = 1_000_000_000; ArrayList<Integer>[] graph; int n; int clock; int[] parent; int[] weight; int[] tin; int[] tout; public FBerlandBeauty() { } public void dfs(int u, int p) { parent[u] = p; tin[u] = clock++; for(int v: graph[u]) { if(v!=p) { dfs(v, u); } } tout[u] = clock-1; } public boolean anc(int u, int v) { return tin[u]<=tin[v]&&tout[u]>=tout[v]; } public void solve(int kase, InputReader in, Output pw) { n = in.nextInt(); int[][] arr = in.nextInt(n-1, 2, o -> o-1); graph = new ArrayList[n]; for(int i = 0; i<n; i++) { graph[i] = new ArrayList<>(); } for(int i = 0; i<n-1; i++) { graph[arr[i][0]].add(arr[i][1]); graph[arr[i][1]].add(arr[i][0]); } parent = new int[n]; tin = new int[n]; tout = new int[n]; dfs(0, -1); int m = in.nextInt(); int[][] queries = in.nextInt(m, 3); weight = new int[n]; Arrays.fill(weight, 1); for(int i = 0; i<m; i++) { queries[i][0]--; queries[i][1]--; for(int j = queries[i][0]; !anc(j, queries[i][1]); j = parent[j]) { weight[j] = Math.max(weight[j], queries[i][2]); } for(int j = queries[i][1]; !anc(j, queries[i][0]); j = parent[j]) { weight[j] = Math.max(weight[j], queries[i][2]); } } for(int i = 0; i<m; i++) { int val = iinf; for(int j = queries[i][0]; !anc(j, queries[i][1]); j = parent[j]) { val = Math.min(val, weight[j]); } for(int j = queries[i][1]; !anc(j, queries[i][0]); j = parent[j]) { val = Math.min(val, weight[j]); } if(val!=queries[i][2]) { pw.println(-1); return; } } for(int i = 0; i<n-1; i++) { if(parent[arr[i][1]]==arr[i][0]) { Utilities.swap(arr[i], 0, 1); } pw.print(weight[arr[i][0]]+" "); } pw.println(); } } static class FastReader implements InputReader { final private int BUFFER_SIZE = 1<<16; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public FastReader(InputStream is) { din = new DataInputStream(is); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public int nextInt() { int ret = 0; byte c = skipToDigit(); boolean neg = (c=='-'); if(neg) { c = read(); } do { ret = ret*10+c-'0'; } while((c = read())>='0'&&c<='9'); if(neg) { return -ret; } return ret; } private boolean isDigit(byte b) { return b>='0'&&b<='9'; } private byte skipToDigit() { byte ret; while(!isDigit(ret = read())&&ret!='-') ; return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); }catch(IOException e) { e.printStackTrace(); throw new InputMismatchException(); } if(bytesRead==-1) { buffer[0] = -1; } } private byte read() { if(bytesRead==-1) { throw new InputMismatchException(); }else if(bufferPointer==bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public String lineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); lineSeparator = System.lineSeparator(); } public void print(String s) { sb.append(s); if(sb.length()>BUFFER_SIZE >> 1) { flushToBuffer(); } } public void println(int i) { println(String.valueOf(i)); } public void println(String s) { sb.append(s); println(); } public void println() { sb.append(lineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static interface InputReader { int nextInt(); default int[] nextInt(int n) { int[] ret = new int[n]; for(int i = 0; i<n; i++) { ret[i] = nextInt(); } return ret; } default int[][] nextInt(int n, int m) { int[][] ret = new int[n][m]; for(int i = 0; i<n; i++) { ret[i] = nextInt(m); } return ret; } default int[] nextInt(int n, IntUnaryOperator operator) { int[] ret = new int[n]; for(int i = 0; i<n; i++) { ret[i] = operator.applyAsInt(nextInt()); } return ret; } default int[][] nextInt(int n, int m, IntUnaryOperator operator) { int[][] ret = new int[n][m]; for(int i = 0; i<n; i++) { ret[i] = nextInt(m, operator); } return ret; } } static class Utilities { public static void swap(int[] arr, int i, int j) { if(i!=j) { arr[i] ^= arr[j]; arr[j] ^= arr[i]; arr[i] ^= arr[j]; } } } }
java
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0 2 4 20 OutputCopy3InputCopy1 1 2 3 1 0 15 27 26 OutputCopy2InputCopy1 1 2 3 1 0 2 2 1 OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
import java.io.*; import java.util.*; public class Main implements Runnable { static boolean use_n_tests = false; static int stack_size = 1 << 27; static long modulo = 1_000_000_007; void solve(FastScanner in, PrintWriter out, int testNumber) { long x0, y0; x0 = in.nextLong(); y0 = in.nextLong(); long ax, ay; ax = in.nextLong(); ay = in.nextLong(); long bx, by; bx = in.nextLong(); by = in.nextLong(); long xs, ys; xs = in.nextLong(); ys = in.nextLong(); long t; t = in.nextLong(); List<Long> pts = new ArrayList<>(); long prevDist = Long.MAX_VALUE; while (true) { long curDist = dist(x0, y0, xs, ys); if (curDist <= t) { pts.add(x0); pts.add(y0); } else if (curDist > prevDist) { break; } prevDist = curDist; long x1 = ax * x0 + bx; long y1 = ay * y0 + by; x0 = x1; y0 = y1; } int ans = getAnswer(pts, t, xs, ys); Collections.reverse(pts); for (int i = 0; i < pts.size(); i += 2) { long tmp = pts.get(i); pts.set(i, pts.get(i + 1)); pts.set(i + 1, tmp); } int ans1 = getAnswer(pts, t, xs, ys); out.println(Math.max(ans, ans1)); } int getAnswer(List<Long> pts, long t1, long x, long y) { int ans = 0; for (int i = 0; i < pts.size(); i += 2) { long start = dist(pts.get(i), pts.get(i + 1), x, y); long t = t1 - start; int c = 1; for (int j = i + 2; j < pts.size() && t > 0; j += 2) { long extra = dist(pts.get(j - 2), pts.get(j - 1), pts.get(j), pts.get(j + 1)); if (extra <= t) { t -= extra; c++; } else { break; } } ans = Math.max(ans, c); } return ans; } // ****************************** template code *********** long dist(long x0, long y0, long x1, long y1) { return Math.abs(x0 - x1) + Math.abs(y0 - y1); } static class Range { int l, r; int id; public int getL() { return l; } public int getR() { return r; } public Range(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } } static class Array { static Range[] readRanges(int n, FastScanner in) { Range[] result = new Range[n]; for (int i = 0; i < n; i++) { result[i] = new Range(in.nextInt(), in.nextInt(), i); } return result; } static public Integer[] read(int n, FastScanner in) { Integer[] out = new Integer[n]; for (int i = 0; i < out.length; i++) { out[i] = in.nextInt(); } return out; } static public int[] readint(int n, FastScanner in) { int[] out = new int[n]; for (int i = 0; i < out.length; i++) { out[i] = in.nextInt(); } return out; } } class Graph { List<List<Integer>> create(int n) { List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } return graph; } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream io) { br = new BufferedReader(new InputStreamReader(io)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } void run_t_tests() { int t = in.nextInt(); int i = 0; while (t-- > 0) { solve(in, out, i++); } } void run_one() { solve(in, out, -1); } @Override public void run() { in = new FastScanner(System.in); out = new PrintWriter(System.out); if (use_n_tests) { run_t_tests(); } else { run_one(); } out.close(); } static FastScanner in; static PrintWriter out; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(null, new Main(), "", stack_size); thread.start(); thread.join(); } }
java
1311
B
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6 3 2 3 2 1 1 2 4 2 4 1 2 3 3 2 5 1 1 2 3 4 5 1 4 2 2 1 4 3 1 3 4 2 4 3 2 1 1 3 5 2 2 1 2 3 3 1 4 OutputCopyYES NO YES YES NO YES
[ "dfs and similar", "sortings" ]
import java.util.Arrays; import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int testNum = sc.nextInt(); StringBuilder ans = new StringBuilder(); for (int i = 0; i < testNum; i++) { int arrLen = sc.nextInt(); int setLen = sc.nextInt(); //先读取数组的数据 int[] arr = new int[arrLen + 1]; int[] arrCopy = new int[arrLen + 1]; int[] set = new int[setLen + 1]; //arr for (int j = 1; j <= arrLen; j++) { arr[j] = sc.nextInt(); arrCopy[j] = arr[j]; } arrCopy[0] = -100; //正确的顺序 Arrays.sort(arrCopy); //set for (int j = 1; j <= setLen; j++) { set[j] = sc.nextInt(); } for (int j = 1; j <= arrLen; j++) { for (int k = 1; k <= setLen; k++) { if (arr[set[k]] > arr[set[k] + 1]) { int temp = arr[set[k]]; arr[set[k]] = arr[set[k] + 1]; arr[set[k] + 1] = temp; } } } Boolean flag = true; for (int j = 1; j <= arrLen; j++) { if (arr[j] != arrCopy[j]) { ans.append("NO\n"); flag = false; break; } } if (flag) { ans.append("YES\n"); } } System.out.println(ans); sc.close(); } }
java
1285
C
C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2 OutputCopy1 2 InputCopy6 OutputCopy2 3 InputCopy4 OutputCopy1 4 InputCopy1 OutputCopy1 1
[ "brute force", "math", "number theory" ]
import java.io.*; import java.util.*; public class B { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]) { if (System.getProperty("ONLINE_JUDGE") == null) { // Input is a file try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { System.err.println("Error"); } } else { // Input is System.in } FastReader sc = new FastReader(); // Scanner sc = new Scanner(System.in); //System.out.println(java.time.LocalTime.now()); StringBuilder sb = new StringBuilder(); // int t = sc.nextInt(); // while (t > 0) { long n = sc.nextLong(); int sq = (int)Math.sqrt(n); ArrayList<Long> al = new ArrayList<>(); //System.out.println(sq); long a = 0, b = 0; for (int i = sq; i >= 1; i--) { if (n % i == 0) { if (gcd(i, (n / i)) == 1) { a = i; b = n / i; break; } } } sb.append(a + " " + b + "\n"); // t--; // } System.out.println(sb); } //------------------------------------------------------------------------// class Pair implements Comparable<Pair> { int a; //first member of pair int b; //second member of pair public Pair(int a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "(" + this.a + ", " + this.b + ")"; } @Override public int compareTo(Pair o) { return this.a - o.a; } } //----------------------------------------------------// public static void shuffleArray(int[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } //----------------------------------------------------// public static boolean isPowerOfTwo(long x) { return x != 0 && ((x & (x - 1)) == 0); } //----------------------------------------------------// public static long digSum(long a) { long sum = 0; while (a > 0) { sum += a % 10; a /= 10; } return sum; } //----------------------------------------------------// public static boolean isPrime(int n) { if (n <= 1)return false; if (n <= 3)return true; if (n % 2 == 0 || n % 3 == 0)return false; for (int i = 5; i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0)return false; } return true; } //----------------------------------------------------// public static int nextPrime(int n) { while (true) { n++; if (isPrime(n)) break; } return n; } //----------------------------------------------------// public static long gcd(long a, long b) { if (b == 0)return a; return gcd(b, a % b); } //----------------------------------------------------// // public static int lcm(int a, int b) { // return (a * b) / gcd(a, b); // } }
java
1288
E
E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4 3 5 1 4 OutputCopy1 3 2 5 1 4 1 5 1 5 InputCopy4 3 1 2 4 OutputCopy1 3 1 2 3 4 1 4 NoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3]
[ "data structures" ]
import java.io.*; import java.util.*; public class Main { static class BIT { int n; int[] tree; public BIT(int n) { this.n = n; tree = new int[n + 2]; } int read(int i) { i++; int sum = 0; while (i > 0) { sum += tree[i]; i -= i & -i; } return sum; } void update(int i, int val) { i++; while (i <= n) { tree[i] += val; i += i & -i; } } } public static void main(String[] args) throws IOException { FastScanner f = new FastScanner(); int ttt=1; // ttt=f.nextInt(); PrintWriter out=new PrintWriter(System.out); for(int tt=0;tt<ttt;tt++) { int n=f.nextInt(); int m=f.nextInt(); BIT bit=new BIT(n+2*m); int[] mn=new int[n]; int[] mx=new int[n]; int[] pos=new int[n]; for(int i=0;i<n;i++) { mn[i]=mx[i]=i+1; pos[i]=m+i+1; bit.update(pos[i], 1); } int top=m; for(int i=0;i<m;i++) { int u=f.nextInt(); mn[u-1]=1; mx[u-1]=Math.max(mx[u-1], bit.read(pos[u-1])); if(bit.read(pos[u-1])==1) { continue; } bit.update(pos[u-1],-1); pos[u-1]=top; bit.update(pos[u-1],1); top--; } for(int i=0;i<n;i++) { mx[i]=Math.max(mx[i],bit.read(pos[i])); } for(int i=0;i<n;i++) { out.println(mn[i]+" "+mx[i]); } } out.close(); } static void sort(int[] p) { ArrayList<Integer> q = new ArrayList<>(); for (int i: p) q.add( i); Collections.sort(q); for (int i = 0; i < p.length; i++) p[i] = q.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } }
java
1311
B
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6 3 2 3 2 1 1 2 4 2 4 1 2 3 3 2 5 1 1 2 3 4 5 1 4 2 2 1 4 3 1 3 4 2 4 3 2 1 1 3 5 2 2 1 2 3 3 1 4 OutputCopyYES NO YES YES NO YES
[ "dfs and similar", "sortings" ]
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(f.readLine()); while (t-- > 0) { StringTokenizer st = new StringTokenizer(f.readLine()); int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); int[][] arr=new int[n][2]; HashSet<Integer> p=new HashSet<>(); st=new StringTokenizer(f.readLine()); for(int i=0;i<n;i++) { arr[i][0]=Integer.parseInt(st.nextToken()); arr[i][1]=i; } st=new StringTokenizer(f.readLine()); for(int i=0;i<m;i++) { p.add(Integer.parseInt(st.nextToken())-1); } Arrays.sort(arr,(a,b)->a[0]-b[0]==0?a[1]-b[1]:a[0]-b[0]); HashSet<Integer> ans=new HashSet<>(); for(int i=0;i<arr.length;i++) { if(arr[i][1]>i) { for(int j=i;j<arr[i][1];j++) { ans.add(j); } } else { for(int j=arr[i][1];j<i;j++) { ans.add(j); } } } boolean good=true; for(int i:ans) { if(!p.contains(i)) { good=false; break; } } if(good) { out.println("YES"); } else { out.println("NO"); } } out.close(); f.close(); } }
java
1313
A
A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.
[ "brute force", "greedy", "implementation" ]
/* "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." Just have Patience + 1... */ import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = sc.nextInt(); for (int t = 1; t <= test; t++) { solve(); } out.close(); } private static void solve() { List<Integer> list = new ArrayList<>(); for (int i = 0; i < 3; i++) { int freq = sc.nextInt(); list.add(freq); } Collections.sort(list, Collections.reverseOrder()); int count = 0; for (int i = 0; i < 3; i++) { if (list.get(i) == 0) { break; } list.set(i, list.get(i) - 1); count++; } for (int i = 1; i < 3; i++) { if (list.get(0) > 0 && list.get(i) > 0) { list.set(0, list.get(0) - 1); list.set(i, list.get(i) - 1); count++; } } if (list.get(1) > 0 && list.get(2) > 0) { list.set(1, list.get(1) - 1); list.set(2, list.get(2) - 1); count++; } int min = 1; for (int i = 0; i < 3; i++) { min = Math.min(min, list.get(i)); } if (min > 0) { count++; } out.println(count); } public static FastReader sc; public static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } } return str.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } return str; } } }
java
1285
A
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4 LRLR OutputCopy5 NoteIn the example; Zoma may end up anywhere between −2−2 and 22.
[ "math" ]
import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = sc.next(); int l=0,r=0; for(char c:s.toCharArray()){ if(c=='L')l++; if(c=='R')r++; } System.out.println(l+r+1); } }
java
1304
E
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5 1 2 2 3 3 4 4 5 5 1 3 1 2 2 1 4 1 3 2 1 4 1 3 3 4 2 3 3 9 5 2 3 3 9 OutputCopyYES YES NO YES NO NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
[ "data structures", "dfs and similar", "shortest paths", "trees" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.LinkedList; import java.util.StringTokenizer; public class Solution{ static LinkedList<Integer>[] adjList; static int n,m; static int[] dep; static int[][] par; public static void main(String[] args) throws Exception{ FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); n = fs.nextInt(); m = 16; par = new int[n+1][m+1]; dep = new int[n+1]; adjList = new LinkedList[n+1]; for(int i=0;i<=n;i++) adjList[i] = new LinkedList<Integer>(); for(int i=0;i<n-1;i++) { int u = fs.nextInt(), v = fs.nextInt(); adjList[u].add(v); adjList[v].add(u); } build(1,0); int q = fs.nextInt(); while(q-->0) { int x = fs.nextInt(), y = fs.nextInt(), a = fs.nextInt(), b = fs.nextInt(), k = fs.nextInt(); int len1 = lenPath(a,b); int len2 = Math.min(lenPath(a,x)+lenPath(b,y), lenPath(a,y)+ lenPath(b,x)) + 1; boolean bool = false; if(len1%2==k%2 && len1<=k) bool = true; if(len2%2==k%2 && len2<=k) bool = true; out.println(bool?"YES":"NO"); } out.close(); } static int lenPath(int a, int b) { return dep[a] + dep[b] - 2*dep[lca(a,b)]; } //O(NLOG(N)) static void build(int cur, int p) { par[cur][0] = p; for(int j=1;j<=m;j++) { par[cur][j] = par[par[cur][j-1]][j-1]; } for(int n: adjList[cur]) { if(n!=p) { dep[n] = 1 + dep[cur]; build(n,cur); } } } //O(LOG(N)) static int lca(int u, int v) { if(u==v) return v; if(dep[u]<dep[v]) { int temp = u; u = v; v = temp; } int dif = dep[u]-dep[v]; for(int i=m;i>=0;i--) { if(((dif>>i)&1)==1) { u = par[u][i]; } } if(u==v) return u; for(int i=m;i>=0;i--) { if(par[u][i]!=par[v][i]) { u = par[u][i]; v = par[v][i]; } } return par[u][0]; } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } } }
java
1316
A
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105)  — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m)  — scores of the students.OutputFor each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2 4 10 1 2 3 4 4 5 1 2 3 4 OutputCopy10 5 NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.
[ "implementation" ]
import java.io.PrintWriter; import java.math.BigInteger; import java.util.HashSet; import java.util.*; public class meta { public static void main(String[] args) { Scanner real = new Scanner(System.in); int n= real.nextInt(); while (n--!=0) { int sum=0; int a = real.nextInt(); int k= real.nextInt(); long[] arr = new long[a]; for (int i = 0; i < a; i++) { arr[i] = real.nextInt(); sum+=arr[i]; } System.out.println(Math.min(k,sum)); } } }
java
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3 6 2 4 OutputCopy0 InputCopy5 9 8 7 3 1 OutputCopy4 NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.
[ "math", "number theory", "probabilities" ]
//package round2020; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Random; import java.util.Set; public class F { InputStream is; PrintWriter out; String INPUT = ""; long[] a; void solve() { int n = ni(); a = new long[n]; int[] primes = sieveEratosthenes(1000000); for(int i = 0;i < n;i++){ a[i] = nl(); } long ans = 0; for(int i = 0;i < n;i++)ans += a[i]%2; long can = 0; for(int i = 0;i < n;i++)can += a[i] < 3 ? 3-a[i] : a[i]%3 == 0 ? 0 : 1; ans = Math.min(ans, can); cache.add(2L); cache.add(3L); Random gen = new Random(); for(int i = 0;i < 10;i++){ int ind = gen.nextInt(n); for(long k = a[ind]-1;k <= a[ind]+1;k++){ if(k == 0)continue; long x = k; for(int p : primes){ int e = 0; while(x % p == 0){ x /= p; e++; } if(e > 0){ ans = Math.min(ans, go(p)); } } ans = Math.min(ans, go(x)); } } out.println(ans); } Set<Long> cache = new HashSet<>(); long go(long p) { if(p == 1 || !cache.add(p)){ return Long.MAX_VALUE; } long ret = 0; int n = a.length; for(long v : a){ if(v < p){ ret += p - v; }else{ long vp = v%p; ret += Math.min(vp, p-vp); } if(ret > n)break; } return ret; } public static int[] sieveEratosthenes(int n) { if (n <= 32) { int[] primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 }; for (int i = 0; i < primes.length; i++) { if (n < primes[i]) { return Arrays.copyOf(primes, i); } } return primes; } int u = n + 32; double lu = Math.log(u); int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)]; ret[0] = 2; int pos = 1; int[] isnp = new int[(n + 1) / 32 / 2 + 1]; int sup = (n + 1) / 32 / 2 + 1; int[] tprimes = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 }; for (int tp : tprimes) { ret[pos++] = tp; int[] ptn = new int[tp]; for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31); for (int j = 0; j < sup; j += tp) { for (int i = 0; i < tp && i + j < sup; i++) { isnp[j + i] |= ptn[i]; } } } // 3,5,7 // 2x+3=n int[] magic = { 0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14 }; int h = n / 2; for (int i = 0; i < sup; i++) { for (int j = ~isnp[i]; j != 0; j &= j - 1) { int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27]; int p = 2 * pp + 3; if (p > n) break; ret[pos++] = p; if ((long) p * p > n) continue; for (int q = (p * p - 3) / 2; q <= h; q += p) isnp[q >> 5] |= 1 << q; } } return Arrays.copyOf(ret, pos); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new F().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
java
1287
B
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3 SET ETS TSE OutputCopy1InputCopy3 4 SETE ETSE TSES OutputCopy0InputCopy5 4 SETT TEST EEET ESTE STES OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES"
[ "brute force", "data structures", "implementation" ]
/* _oo0oo_ o8888888o 88" . "88 (| -_- |) 0\ = /0 ___/`---'\___ .' \\| |// '. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' |_/ | \ .-\__ '-' ___/-. / ___'. .' /--.--\ `. .'___ ."" '< `.___\_<|>_/___.' >' "". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `_. \_ __\ /__ _/ .-` / / =====`-.____`.___ \_____/___.-`___.-'===== `=---=' */ import java.util.function.Consumer; import java.util.*; import java.math.*; import java.io.*; import java.lang.Math.*; public class KickStart2020 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static class Pair implements Comparable<Pair> { public int index; public int value; public Pair(int index, int value) { this.index = index; this.value = value; } @Override public int compareTo(Pair other) { // multiplied to -1 as the author need descending sort order return -1 * Integer.valueOf(this.value).compareTo(other.value); } } static boolean isPrime(long d) { if (d == 1) return true; for (int i = 2; i <= (long) Math.sqrt(d); i++) { if (d % i == 0) return false; } return true; } static void decimalTob(long n, int b, int arr[], int i) { long z = n % b; arr[i] += (int) z; n /= b; if (n > 0) { i++; decimalTob(n, b, arr, i); } } static long powermod(long x, long y, long mod) { long ans = 1; x = x % mod; if (x == 0) return 0; int i = 1; while (y > 0) { if ((y & 1) != 0) ans = (ans * x) % mod; y = y >> 1; x = (x * x) % mod; } return ans; } static boolean isSorted(int arr[]) { for (int i = 1; i <= arr.length; i++) if (arr[i - 1] != i) return false; return true; } static char help(char a, char b) { return a!= 'S' && b!= 'S'? 'S': a!= 'E' && b!= 'E'? 'E': 'T'; } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = 1; outerloop: while (t-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); String arr[] = new String[n]; HashMap<String, Integer> ss = new HashMap<>(); for(int i = 0; i < n; i++) { arr[i] = sc.next(); ss.put(arr[i], ss.getOrDefault(arr[i], 0) + 1); } long count = 0; for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { char a[] = new char[k]; for(int l = 0; l < k; l++) { if(arr[i].charAt(l) == arr[j].charAt(l)) a[l] = arr[i].charAt(l); else a[l] = help(arr[i].charAt(l), arr[j].charAt(l)); } ss.put(arr[i], ss.get(arr[i]) - 1); ss.put(arr[j], ss.get(arr[j]) - 1); count += ss.getOrDefault(new String(a), 0); ss.put(arr[i], ss.get(arr[i]) + 1); ss.put(arr[j], ss.get(arr[j]) + 1); } } out.println(count / 3); } out.close(); } }
java
1312
C
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5 4 100 0 0 0 0 1 2 1 3 4 1 4 1 3 2 0 1 3 3 9 0 59049 810 OutputCopyYES YES NO NO YES NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.
[ "bitmasks", "greedy", "implementation", "math", "number theory", "ternary search" ]
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class C_Adding_Powers { static long mod = Long.MAX_VALUE; public static void main(String[] args) { OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); FastReader f = new FastReader(); int t = f.nextInt(); while(t-- > 0){ solve(f, out); } out.close(); } public static void solve(FastReader f, PrintWriter out) { int n = f.nextInt(); int k = f.nextInt(); long arr[] = f.nextArray(n); int powSize = (int)(Math.log(mod)/Math.log(k)); int pow[] = new int[powSize]; for(int i = 0; i < n; i++) { for(int j = powSize-1; j >= 0; j--) { if(power(k, j) <= arr[i]) { arr[i] -= power(k, j); pow[j]++; } } if(arr[i] != 0) { out.println("NO"); return; } } for(int i = 0; i < powSize; i++) { if(pow[i] > 1) { out.println("NO"); return; } } out.println("YES"); } // Sort an array public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } // Find all divisors of n public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } // Check if n is prime or not public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } // Find gcd of a and b public static long gcd(long a, long b) { long dividend = a > b ? a : b; long divisor = a < b ? a : b; while(divisor > 0) { long reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } // Find lcm of a and b public static long lcm(long a, long b) { long lcm = gcd(a, b); long hcf = (a * b) / lcm; return hcf; } // Find factorial in O(n) time public static long fact(int n) { long res = 1; for(int i = 2; i <= n; i++) { res = res * i; } return res; } // Find power in O(logb) time public static long power(long a, long b) { long res = 1; while(b > 0) { if((b&1) == 1) { res = (res * a)%mod; } a = (a * a)%mod; b >>= 1; } return res; } // Find nCr public static long nCr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / (fact(r) * fact(n-r)); return ans; } // Find nPr public static long nPr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / fact(r); return ans; } // sort all characters of a string public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } // User defined class for fast I/O static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } boolean hasNext() { if (st != null && st.hasMoreTokens()) { return true; } String tmp; try { br.mark(1000); tmp = br.readLine(); if (tmp == null) { return false; } br.reset(); } catch (IOException e) { return false; } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } long[] nextArray(int n) { long[] a = new long[n]; for(int i=0; i<n; i++) { a[i] = nextLong(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */ // (a/b)%mod == (a * moduloInverse(b)) % mod; // moduloInverse(b) = power(b, mod-2);
java
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3 6 2 4 OutputCopy0 InputCopy5 9 8 7 3 1 OutputCopy4 NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.
[ "math", "number theory", "probabilities" ]
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; import java.util.stream.Collectors; public class C1305F { public static void main(String[] args) { var scanner = new BufferedScanner(); var writer = new PrintWriter(new BufferedOutputStream(System.out)); var n = scanner.nextInt(); var a = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = scanner.nextLong(); } var distinct = Arrays.stream(a)/*.distinct()*/.boxed().collect(Collectors.toList()); Collections.shuffle(distinct); // var distinct = Arrays.stream(a).distinct().toArray(); var factors = new HashSet<Long>(); for (int guess = 0; guess < 20 && guess < distinct.size(); guess++) { for (int j = -1; j <= 1; j++) { factors.addAll(factor(distinct.get(guess) + j)); } } // for (int guess = 0; guess < 20; guess++) { // var i = (int) (Math.random() * distinct.length); // for (int j = -1; j <= 1; j++) { // factors.addAll(factor(distinct[i] + j)); // } // } var ans = countOps(2, a, n); factors.remove(2L); for (var factor : factors) { var ops = countOps(factor, a, ans); ans = Math.min(ans, ops); } writer.println(ans); scanner.close(); writer.flush(); writer.close(); } private static long countOps(long factor, long[] a, long already) { var ans = 0L; for (var x : a) { if (x < factor) { ans += factor - x; } else { var remain = x % factor; ans += Math.min(remain, factor - remain); // if (remain < factor / 2) { // ans += remain; // } else { // ans += factor - remain; // } } if (ans >= already) { break; } } return ans; } private static List<Long> factor(long a) { if (a <= 1) { return List.of(); } var limit = (long) Math.sqrt(a); var ans = new ArrayList<Long>(); for (long i = 2; i <= limit; i++) { var count = 0; while (a % i == 0) { a /= i; count++; } if (count > 0) { ans.add(i); } } if (a > 1) { ans.add(a); } return ans; } public static class BufferedScanner { BufferedReader br; StringTokenizer st; public BufferedScanner(Reader reader) { br = new BufferedReader(reader); } public BufferedScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } static long gcd(long a, long b) { if (a < b) { return gcd(b, a); } while (b > 0) { long tmp = b; b = a % b; a = tmp; } return a; } static long inverse(long a, long m) { long[] ans = extgcd(a, m); return ans[0] == 1 ? (ans[1] + m) % m : -1; } private static long[] extgcd(long a, long m) { if (m == 0) { return new long[]{a, 1, 0}; } else { long[] ans = extgcd(m, a % m); long tmp = ans[1]; ans[1] = ans[2]; ans[2] = tmp; ans[2] -= ans[1] * (a / m); return ans; } } private static List<Integer> primes(double upperBound) { var limit = (int) Math.sqrt(upperBound); var isComposite = new boolean[limit + 1]; var primes = new ArrayList<Integer>(); for (int i = 2; i <= limit; i++) { if (isComposite[i]) { continue; } primes.add(i); int j = i + i; while (j <= limit) { isComposite[j] = true; j += i; } } return primes; } }
java
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3 tab one bat OutputCopy6 tabbat InputCopy4 2 oo ox xo xx OutputCopy6 oxxxxo InputCopy3 5 hello codef orces OutputCopy0 InputCopy9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji OutputCopy20 ababwxyzijjizyxwbaba NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
/* It's always like another kick for me to make sure I get what I want to get done, because honestly you never know. */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main extends PrintWriter { Main() { super(System.out); } static boolean cases = false; // Solution void solve() { int n = sc.nextInt(); int m = sc.nextInt(); List<String> al = new ArrayList<>(); HashMap<String, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { String s = sc.next(); al.add(s); map.put(s, map.getOrDefault(s, 0) + 1); } LinkedList<String> ans = new LinkedList<>(); int len = 0; for (String s : al) { String rev = new StringBuilder(s).reverse().toString(); if (map.containsKey(rev)) { int t = min(map.get(s), map.get(rev)); if (rev.equals(s)) t = map.get(s) / 2; for (int i = 0; i < t; i++) { ans.addFirst(s); len += s.length(); } for (int i = 0; i < t; i++) { ans.addLast(rev); len += s.length(); } map.put(s, map.get(s) - t); map.put(rev, map.get(rev) - t); if (map.get(s) == 0) map.remove(s); if (map.get(rev) == 0) map.remove(rev); } } String max = ""; for (String s : map.keySet()) { if (isPal(s)) { if (s.length() > max.length()) { // max = s; } } } len += max.length(); System.out.println(len); for (int i = 0; i < ans.size() / 2; i++) { System.out.print(ans.get(i)); } System.out.print(max); for (int i = ans.size() / 2; i < ans.size(); i++) { System.out.print(ans.get(i)); } } boolean isPal(String s) { int i = 0, j = s.length() - 1; while (i <= j) { if (s.charAt(i++) != s.charAt(j--)) return false; } return true; } void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } public static void main(String[] args) { Main obj = new Main(); int c = 1; for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve(); obj.solve(); obj.flush(); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } char[] readCharArray(int n) { char a[] = new char[n]; String s = sc.next(); for (int i = 0; i < n; i++) { a[i] = s.charAt(i); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } final int ima = Integer.MAX_VALUE; final int imi = Integer.MIN_VALUE; final long lma = Long.MAX_VALUE; final long lmi = Long.MIN_VALUE; static final long mod = (long) 1e9 + 7; private static final FastScanner sc = new FastScanner(); private PrintWriter out = new PrintWriter(System.out); }
java
1141
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5 1 0 1 0 1 OutputCopy2 InputCopy6 0 1 0 1 1 0 OutputCopy2 InputCopy7 1 0 1 1 1 0 1 OutputCopy3 InputCopy3 0 0 0 OutputCopy0 NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
[ "implementation" ]
/* package codeForces; // don't place package name! */ // algo_messiah23 , NIT RKL ... import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import static java.lang.System.*; import java.util.stream.IntStream; import java.util.Map.Entry; /* Name of the class has to be "Main" only if the class is public. */ public class CodeForces { static PrintWriter out = new PrintWriter((System.out)); static FastReader in = new FastReader(); static int INF = Integer.MAX_VALUE; static int NINF = Integer.MIN_VALUE; public static void main(String[] args) throws java.lang.Exception { // your code goes here int t = 1; //t = i(); while (t-- > 0) algo_messiah23(); out.close(); } public static void algo_messiah23() { int n = i(); int a[] = input(n); List<Integer> list = new ArrayList<>(); for(int i : a) list.add(i); for(int i : a) list.add(i); int maxe = NINF; int c = 0; for(int i=0;i<list.size();i++){ if(list.get(i) == 1) c++; else{ maxe = (int)Math.max(c,maxe); c = 0; } } out.println(maxe); } static String rev(String s) { StringBuilder st = new StringBuilder(s); st.reverse(); String ans = st.toString(); return ans; } static int[] input(int N) { int[] A = new int[N]; for (int i = 0; i < N; i++) A[i] = in.nextInt(); return A; } public static void print(int[] arr) { int n = arr.length; for (int i = 0; i < n; i++) { out.print(arr[i] + " "); } out.println(); } public static void sort(int[] arr) { ArrayList<Integer> ls = new ArrayList<>(); for (int x : arr) { ls.add(x); } Collections.sort(ls); for (int i = 0; i < arr.length; i++) { arr[i] = ls.get(i); } } public static void reverse(int[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) { int temp = arr[i]; arr[i] = arr[n - 1 - i]; arr[n - 1 - i] = temp; } } public static void reverse(long[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) { long temp = arr[i]; arr[i] = arr[n - 1 - i]; arr[n - 1 - i] = temp; } } public static void print(ArrayList<Integer> arr) { int n = arr.size(); for (int i = 0; i < n; i++) { out.print(arr.get(i) + " "); } out.println(); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static char ich() { return in.next().charAt(0); } static String is() { return in.next(); } static String isl() { return in.nextLine(); } public static int max(int[] arr) { int max = -1; int n = arr.length; for (int i = 0; i < n; i++) max = Math.max(max, arr[i]); return max; } public static int min(int[] arr) { int min = INF; int n = arr.length; for (int i = 0; i < n; i++) min = Math.min(min, arr[i]); return min; } public static int gcd(int x, int y) { if (y == 0) { return x; } return gcd(y, x % y); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
java
1301
D
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4 OutputCopyYES 2 2 R 2 L InputCopy3 3 1000000000 OutputCopyNO InputCopy3 3 8 OutputCopyYES 3 2 R 2 D 1 LLRR InputCopy4 4 9 OutputCopyYES 1 3 RLD InputCopy3 4 16 OutputCopyYES 8 3 R 3 L 1 D 3 R 1 D 1 U 3 L 1 D NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
[ "constructive algorithms", "graphs", "implementation" ]
import java.io.*; import java.util.*; import static java.lang.Math.*; public class C{ static int n,m; static boolean w(int i, int j) { return min(i,j)>=0 && i < n && j < m; } static class Type{ char mov; int i, j; public Type(char a, int b, int c) { mov=a; i=b; j=c; } } static StringBuilder res = new StringBuilder(); static void add(char c, int times) { while(times-->0 && k--> 0)res.append(c); } static int k; public static void main(String[] args) throws IOException { // br = new BufferedReader(new FileReader(".in")); // out = new PrintWriter(new FileWriter(".out")); //new Thread(null, new (), "peepee", 1<<28).start(); n=readInt(); m =readInt(); k =readInt(); if (4*n*m-2*(m+n) < k) { System.out.println("NO"); System.exit(0); } out.println("YES"); for (int i = 0; i < m; i++) { if (i == m-1) { add('D', n-1); for (int j = 0; j < n-1; j++) { add('L', m-1); add('R', m-1); add('U', 1); } add('L', m-1); } else { add('D',n-1); add('U', n-1); add('R', 1); } } List<String> ans = new ArrayList<String>(); char c = res.charAt(0); int len = 1; for (int i = 1; i < res.length(); i++) { if (res.charAt(i) == c) len++; else { ans.add("" + len + " " + c); len = 1; } c=res.charAt(i); } ans.add("" + len + " " + c); out.println(ans.size()); for (String s: ans) out.println(s); //System.out.println(res + " " +res.length()); out.close(); } /* Stupid things to try if stuck: * n=1, expand bsearch range * brute force small patterns * submit stupid intuition */ static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static StringTokenizer st = new StringTokenizer(""); static String read() throws IOException{return st.hasMoreTokens() ? st.nextToken():(st = new StringTokenizer(br.readLine())).nextToken();} static int readInt() throws IOException{return Integer.parseInt(read());} static long readLong() throws IOException{return Long.parseLong(read());} static double readDouble() throws IOException{return Double.parseDouble(read());} }
java
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
/* JAIKARA SHERAWAALI DA BOLO SACHE DARBAR KI JAI HAR HAR MAHADEV JAI BHOLENAATH Rohit Kumar "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." */ import java.io.*; import java.util.*; public class Main { static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next(){ while(st==null||!st.hasMoreTokens()){ try{ st=new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken();} long nextLong(){ return Long.parseLong(next());} int nextInt(){ return Integer.parseInt(next());} } static int mod=(int)1e9+7; public static void main(String[] args) { try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { System.err.println("Error"); } FastReader sc = new FastReader(); int tt=sc.nextInt(); while(tt-->0) { int n=sc.nextInt(); Pair arr[]=new Pair[n]; for(int i=0;i<n;i++) { arr[i]=new Pair(sc.nextInt(),i); } // Arrays.sort(arr,(p1,p2)->p1.ele-p2.ele); TreeSet<Integer> vis=new TreeSet<>(); for(int i=0;i<n;i++) { vis.add(arr[i].ele); } List<Integer> visited=new ArrayList<>(); for(int i=1;i<=2*n;i++) { if(!vis.contains(i)) { visited.add(i); } } // for(int i=0;i<visited.size();i++) // { // print(visited.get(i)); // } Collections.sort(visited); int k=visited.size()-1; HashMap<Integer,Integer> hs=new HashMap<>(); for(int i=0;i<arr.length;i++) { //hs.put(arr[i],visited.get(i)); for(int j=0;j<visited.size();j++) { //print(arr[i].ele+" "+visited.get(j)); if(arr[i].ele<visited.get(j)) { hs.put(arr[i].ele,visited.get(j)); visited.set(j,-1); break; } } } boolean flag=false; Arrays.sort(arr,(p1,p2)->p1.idx-p2.idx); for(int i=0;i<arr.length;i++) { if(arr[i].ele!=Math.min(arr[i].ele,hs.getOrDefault(arr[i].ele,-1))) { flag=true; break; } } if(flag) { print(-1); } else{ for(int i=0;i<arr.length;i++) { System.out.print(arr[i].ele+" "+hs.get(arr[i].ele)+" "); } System.out.println(); } } } static class Pair{ int ele; int idx; public Pair(int ele,int idx) { this.ele=ele; this.idx=idx; } } static <t>void print(t o){ System.out.println(o); } static void reverse(int[] arr, int from, int till) { for (int i = from, j = till; i < j; i++, j--) { swap(arr, i, j); } } static void swap(int[] arr, int a, int b) { int tmp = arr[a]; arr[a] = arr[b]; arr[b] = tmp; } void sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n+1]; for(int i=0;i<=n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p] == true) { for(int i = p*p; i <= n; i += p) prime[i] = false; } } for(int i = 2; i <= n; i++) { if(prime[i] == true) System.out.print(i + " "); } } static long gcd(long a,long b) { if(b==0) return a; return gcd(b,a%b); } static boolean isprime(int n) { if(n<=1) return false; if(n<=3) return true; if(n%2==0||n%3==0) return false; for(int i=5;i*i<=n;i=i+6) { if(n%i==0||n%(i+2)==0) return false; } return true; } }
java
1307
B
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,…,ana1,a2,…,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−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)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) →→ (2,−5–√)(2,−5) →→ (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≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — 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,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — 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 — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(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) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (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) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
import java.util.Scanner; public class codeforce { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int t=scan.nextInt(); for(int tt=0;tt<t;tt++) { int n=scan.nextInt(), dist=scan.nextInt(); boolean one=false; int max=0; for(int i=0;i<n;i++) { int x=scan.nextInt(); if(dist==x) { one=true; } max=Math.max(max,x); } if(one) { System.out.println(1); continue; } System.out.println(Math.max((int)Math.ceil(dist*1.0/max),2)); } } }
java
1322
A
A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8 ))((())( OutputCopy6 InputCopy3 (() OutputCopy-1 NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.
[ "greedy" ]
/* Created on = 08-Feb-2022 / 9:10:39 AM */ import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class Main { public static void main(String[] args) throws IOException { try { solve(); out.close(); } catch (Exception e) { return; } } // SOLUTION STARTS HERE // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: static void solve() { int n = sc.nextInt(); char a[] = sc.next().toCharArray(); int x[] = new int[n]; x[0] = a[0] == '(' ? 1 : -1; for (int i = 1; i < n; i++) { x[i] = x[i - 1] + (a[i] == '(' ? 1 : -1); } if (x[n - 1] != 0) { System.out.println(-1); return; } int last = 0; boolean f = false; int ans = 0; for (int i = 0; i < n; i++) { if (!f && x[i] < 0) { last = i; f = true; } if (x[i] == 0 && f) { ans += i - last + 1; f = false; } } System.out.println(ans); } // SOLUTION ENDS HERE // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: static long binPow(long a, long b, long mod) { long ans = 1; while (b != 0) { if ((b & 1) == 1) ans = (ans * a) % mod; a = (a * a) % mod; b >>= 1; } return ans; } static class DSU { int rank[]; int parent[]; DSU(int n) { rank = new int[n + 1]; parent = new int[n + 1]; for (int i = 1; i <= n; i++) { parent[i] = i; } } int findParent(int node) { if (parent[node] == node) return node; return parent[node] = findParent(parent[node]); } boolean union(int x, int y) { int px = findParent(x); int py = findParent(y); if (px == py) return false; if (rank[px] < rank[py]) { parent[px] = py; } else if (rank[px] > rank[py]) { parent[py] = px; } else { parent[px] = py; rank[py]++; } return true; } } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static boolean[] seiveOfEratosthenes(int n) { boolean[] isPrime = new boolean[n + 1]; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { for (int j = i * i; j <= n; j += i) { isPrime[j] = false; } } return isPrime; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static boolean isPrime(long n) { if (n < 2) return false; for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } private static final FastScanner sc = new FastScanner(); private static PrintWriter out = new PrintWriter(System.out); }
java
1295
C
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3 aabce ace abacaba aax ty yyt OutputCopy1 -1 3
[ "dp", "greedy", "strings" ]
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class C_Obtain_The_String { static long mod = Long.MAX_VALUE; static OutputStream outputStream = System.out; static PrintWriter out = new PrintWriter(outputStream); static FastReader f = new FastReader(); public static void main(String[] args) { int t = f.nextInt(); while(t-- > 0){ solve(); } out.close(); } public static void solve() { String s = f.nextLine(); String t = f.nextLine(); int sl = s.length(); int tl = t.length(); int next[][] = new int[sl+1][26]; for(int row[]: next) { Arrays.fill(row, Integer.MAX_VALUE); } for(int i = sl-1; i >= 0; i--) { for(int j = 0; j < 26; j++) { next[i][j] = next[i+1][j]; } next[i][s.charAt(i)-'a'] = i; } int ops = 1; int ind = 0; for(int i = 0; i < tl; i++) { int c = t.charAt(i)-'a'; if(next[ind][c] != Integer.MAX_VALUE) { ind = next[ind][c]+1; } else { ind = 0; ops++; if(next[ind][c] == Integer.MAX_VALUE) { out.println(-1); return; } ind = next[ind][c]+1; } } out.println(ops); } // Sort an array public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } // Find all divisors of n public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } // Check if n is prime or not public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } // Find gcd of a and b public static long gcd(long a, long b) { long dividend = a > b ? a : b; long divisor = a < b ? a : b; while(divisor > 0) { long reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } // Find lcm of a and b public static long lcm(long a, long b) { long lcm = gcd(a, b); long hcf = (a * b) / lcm; return hcf; } // Find factorial in O(n) time public static long fact(int n) { long res = 1; for(int i = 2; i <= n; i++) { res = res * i; } return res; } // Find power in O(logb) time public static long power(long a, long b) { long res = 1; while(b > 0) { if((b&1) == 1) { res = (res * a)%mod; } a = (a * a)%mod; b >>= 1; } return res; } // Find nCr public static long nCr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / (fact(r) * fact(n-r)); return ans; } // Find nPr public static long nPr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / fact(r); return ans; } // sort all characters of a string public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } // User defined class for fast I/O static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } boolean hasNext() { if (st != null && st.hasMoreTokens()) { return true; } String tmp; try { br.mark(1000); tmp = br.readLine(); if (tmp == null) { return false; } br.reset(); } catch (IOException e) { return false; } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */ // (a/b)%mod == (a * moduloInverse(b)) % mod; // moduloInverse(b) = power(b, mod-2);
java
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.StringTokenizer; import java.util.TreeMap; /** * * @author eslam */ public class IceCave { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static final double cmp = 0.0000000001; static int l = 0; static int r; static boolean ca = false; public static void main(String[] args) throws IOException { FastReader input = new FastReader(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); int n = input.nextInt(); r = n-2; pair b[] = new pair[n-1]; ArrayList<Integer> a[] = new ArrayList[n]; TreeMap<pair, Integer> ans = new TreeMap<>(new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.x > o2.x) { return 1; } else if (o1.x < o2.x) { return -1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } } }); for (int i = 0; i < n; i++) { a[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int x = input.nextInt() - 1; int y = input.nextInt() - 1; b[i] = new pair(Math.min(x, y), Math.max(x, y)); a[b[i].x].add(b[i].y); a[b[i].y].add(b[i].x); } dfsRecursive(0, -1, a, new boolean[n], ans); for (int i = 0; i < b.length; i++) { log.write(ans.get(b[i])+"\n"); } log.flush(); } public static void dfsRecursive(int n, int p, ArrayList<Integer>[] a, boolean visited[], TreeMap<pair, Integer> ans) { ArrayList<Integer> nodes = a[n]; visited[n] = true; for (Integer node : nodes) { if (!visited[node]) { ca = false; dfsRecursive(node, n, a, visited, ans); } } if (p == -1) { return; } if (!ca) { ans.put(new pair(Math.min(n, p), Math.max(n, p)), l++); ca = true; }else{ ans.put(new pair(Math.min(n, p), Math.max(n, p)), r--); } } static class pair { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } } }
java
1285
D
D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3 1 2 3 OutputCopy2 InputCopy2 1 5 OutputCopy4 NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.
[ "bitmasks", "brute force", "dfs and similar", "divide and conquer", "dp", "greedy", "strings", "trees" ]
import java.io.*; import java.util.ArrayList; import java.util.InputMismatchException; public class E1285D { public static void main(String[] args) { FastIO io = new FastIO(); int n = io.nextInt(); ArrayList<Integer> l = new ArrayList<>(); for (int i = 0; i < n; i++) l.add(io.nextInt()); int ans = dc(30, l); io.println(ans); io.close(); } static int dc(int p, ArrayList<Integer> l) { if (p == -1) return 0; ArrayList<Integer> zeroList = new ArrayList<>(); ArrayList<Integer> oneList = new ArrayList<>(); for (int v : l) { if (((v >> p) & 1) == 1) oneList.add(v); else zeroList.add(v); } int ans; if (zeroList.size() == 0) ans = dc(p - 1, oneList); else if (oneList.size() == 0) ans = dc(p - 1, zeroList); else ans = Math.min(dc(p - 1, oneList), dc(p - 1, zeroList)) | (1 << p); return ans; } private static class FastIO extends PrintWriter { private final InputStream stream; private final byte[] buf = new byte[1 << 16]; private int curChar, numChars; // standard input public FastIO() { this(System.in, System.out); } public FastIO(InputStream i, OutputStream o) { super(o); stream = i; } // file input public FastIO(String i, String o) throws IOException { super(new FileWriter(o)); stream = new FileInputStream(i); } // throws InputMismatchException() if previously detected end of file private int nextByte() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars == -1) return -1; // end of file } return buf[curChar++]; } // to read in entire lines, replace c <= ' ' // with a function that checks whether c is a line break public String next() { int c; do { c = nextByte(); } while (c <= ' '); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > ' '); return res.toString(); } public int nextInt() { // nextLong() would be implemented similarly int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10 * res + c - '0'; c = nextByte(); } while (c > ' '); return res * sgn; } public long nextLong() { // nextLong() would be implemented similarly int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10 * res + c - '0'; c = nextByte(); } while (c > ' '); return res * sgn; } public double nextDouble() { return Double.parseDouble(next()); } } }
java
1324
E
E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23 16 17 14 20 20 11 22 OutputCopy3 NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.
[ "dp", "implementation" ]
import java.io.*; import java.math.*; import java.util.*; public class E_Sleeping_Schedule { public static void main(String[] args)throws Exception { new Solver().solve(); } } //* Success is not final, failure is not fatal: it is the courage to continue that counts. class Solver { int[][] dp; public int recFun(int i,int time,int[] arr,int hr,int l,int r){ if(i>=arr.length){ return 0; } // sleep for ai hours if(dp[i][time]!=-1){ return dp[i][time]; } int sleep = recFun(i+1, (time+arr[i])%hr, arr,hr,l,r); int wait =recFun(i+1, (time+arr[i]-1)%hr, arr,hr,l,r); if((time+arr[i])%hr>=l && (time+arr[i])%hr<=r){ sleep++; } if((time+arr[i]-1)%hr>=l && (time+arr[i]-1)%hr<=r){ wait++; } return dp[i][time] = Math.max(sleep,wait); } void solve() throws Exception { int n = sc.nextInt(); int hr = sc.nextInt(); int l =sc.nextInt(); int r = sc.nextInt(); int[] arr = sc.getIntArray(n); dp = new int[n][hr]; for(int i =0;i<n;i++){ Arrays.fill(dp[i],-1); } int ans = recFun(0, 0, arr, hr, l, r); sc.println(ans); sc.flush(); } final Helper sc; final int MAXN = 1000_006; final long MOD = (long) 1e9 + 7; Solver() { sc = new Helper(MOD, MAXN); sc.initIO(System.in, System.out); } } class Helper { final long MOD; final int MAXN; final Random rnd; public Helper(long mod, int maxn) { MOD = mod; MAXN = maxn; rnd = new Random(); } public static int[] sieve; public static ArrayList<Integer> primes; public void setSieve() { primes = new ArrayList<>(); sieve = new int[MAXN]; int i, j; for (i = 2; i*i < MAXN; ++i) if (sieve[i] == 0) { primes.add(i); for (j = i*i; j < MAXN; j += i) { sieve[j] = i; } } } public static long[] factorial; public void setFactorial() { factorial = new long[MAXN]; factorial[0] = 1; for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD; } public long getFactorial(int n) { if (factorial == null) setFactorial(); return factorial[n]; } public long ncr(int n, int r) { if (r > n) return 0; if (factorial == null) setFactorial(); long numerator = factorial[n]; long denominator = factorial[r] * factorial[n - r] % MOD; return numerator * pow(denominator, MOD - 2, MOD) % MOD; } public long[] getLongArray(int size) throws Exception { long[] ar = new long[size]; for (int i = 0; i < size; ++i) ar[i] = nextLong(); return ar; } public int[] getIntArray(int size) throws Exception { int[] ar = new int[size]; for (int i = 0; i < size; ++i) ar[i] = nextInt(); return ar; } public long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } public int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public long max(long[] ar) { long ret = ar[0]; for (long itr : ar) ret = Math.max(ret, itr); return ret; } public int max(int[] ar) { int ret = ar[0]; for (int itr : ar) ret = Math.max(ret, itr); return ret; } public long min(long[] ar) { long ret = ar[0]; for (long itr : ar) ret = Math.min(ret, itr); return ret; } public int min(int[] ar) { int ret = ar[0]; for (int itr : ar) ret = Math.min(ret, itr); return ret; } public long sum(long[] ar) { long sum = 0; for (long itr : ar) sum += itr; return sum; } public long sum(int[] ar) { long sum = 0; for (int itr : ar) sum += itr; return sum; } public void shuffle(int[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void shuffle(long[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public long pow(long base, long exp, long MOD) { base %= MOD; long ret = 1; while (exp > 0) { if ((exp & 1) == 1) ret = ret * base % MOD; base = base * base % MOD; exp >>= 1; } return ret; } static byte[] buf = new byte[1000_006]; static int index, total; static InputStream in; static BufferedWriter bw; public void initIO(InputStream is, OutputStream os) { try { in = is; bw = new BufferedWriter(new OutputStreamWriter(os)); } catch (Exception e) { } } public void initIO(String inputFile, String outputFile) { try { in = new FileInputStream(inputFile); bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputFile))); } catch (Exception e) { } } private int scan() throws Exception { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public String nextLine() throws Exception { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c >= 32; c = scan()) sb.append((char) c); return sb.toString(); } public String next() throws Exception { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) sb.append((char) c); return sb.toString(); } public int nextInt() throws Exception { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') c = scan(); for (; c >= '0' && c <= '9'; c = scan()) val = (val << 3) + (val << 1) + (c & 15); return neg ? -val : val; } public long nextLong() throws Exception { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') c = scan(); for (; c >= '0' && c <= '9'; c = scan()) val = (val << 3) + (val << 1) + (c & 15); return neg ? -val : val; } public void print(Object a) throws Exception { bw.write(a.toString()); } public void printsp(Object a) throws Exception { print(a); print(" "); } public void println() throws Exception { bw.write("\n"); } public void printArray(int[] arr) throws Exception{ for(int i = 0;i<arr.length;i++){ print(arr[i]+ " "); } println(); } public void println(Object a) throws Exception { print(a); println(); } public void flush() throws Exception { bw.flush(); } }
java
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.sort; public class Round12 { public static void main(String[] args) { FastReader fastReader = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = 1; while (t-- > 0) { int n = fastReader.nextInt(); ArrayList<Integer> adj[] = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int u = fastReader.nextInt() - 1; int v = fastReader.nextInt() - 1; adj[u].add(i); adj[v].add(i); } int color[] = new int[n - 1]; for (int r = 0; r < n - 1; r++) { color[r] = -1; } int nextC = 0; for (int i = 0; i < n; i++) { if (adj[i].size() >= 3) { for (int index = 0; index < adj[i].size(); index++) { color[adj[i].get(index)] = nextC++; } break; } } for (int i = 0; i < n - 1; i++) { if (color[i] == -1) color[i] = nextC++; } for (int i = 0; i< n-1; i++){ out.println(color[i]); } } out.close(); } // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final long LMAX = 9223372036854775807L; static Random __r = new Random(); // math util static int minof(int a, int b, int c) { return min(a, min(b, c)); } static int minof(int... x) { if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min; } static long minof(long a, long b, long c) { return min(a, min(b, c)); } static long minof(long... x) { if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min; } static int maxof(int a, int b, int c) { return max(a, max(b, c)); } static int maxof(int... x) { if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max; } static long maxof(long a, long b, long c) { return max(a, max(b, c)); } static long maxof(long... x) { if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max; } static int powi(int a, int b) { if (a == 0) return 0; int ans = 1; while (b > 0) { if ((b & 1) > 0) ans *= a; a *= a; b >>= 1; } return ans; } static long powl(long a, int b) { if (a == 0) return 0; long ans = 1; while (b > 0) { if ((b & 1) > 0) ans *= a; a *= a; b >>= 1; } return ans; } static int fli(double d) { return (int) d; } static int cei(double d) { return (int) ceil(d); } static long fll(double d) { return (long) d; } static long cel(double d) { return (long) ceil(d); } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static int[] exgcd(int a, int b) { if (b == 0) return new int[]{1, 0}; int[] y = exgcd(b, a % b); return new int[]{y[1], y[0] - y[1] * (a / b)}; } static long[] exgcd(long a, long b) { if (b == 0) return new long[]{1, 0}; long[] y = exgcd(b, a % b); return new long[]{y[1], y[0] - y[1] * (a / b)}; } static int randInt(int min, int max) { return __r.nextInt(max - min + 1) + min; } static long mix(long x) { x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31); } public static boolean[] findPrimes(int limit) { assert limit >= 2; final boolean[] nonPrimes = new boolean[limit]; nonPrimes[0] = true; nonPrimes[1] = true; int sqrt = (int) Math.sqrt(limit); for (int i = 2; i <= sqrt; i++) { if (nonPrimes[i]) continue; for (int j = i; j < limit; j += i) { if (!nonPrimes[j] && i != j) nonPrimes[j] = true; } } return nonPrimes; } // array util static void reverse(int[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(long[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(double[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(char[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void shuffle(int[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(long[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(double[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void rsort(int[] a) { shuffle(a); sort(a); } static void rsort(long[] a) { shuffle(a); sort(a); } static void rsort(double[] a) { shuffle(a); sort(a); } static int[] copy(int[] a) { int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static long[] copy(long[] a) { long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static double[] copy(double[] a) { double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static char[] copy(char[] a) { char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] ria(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = Integer.parseInt(next()); return a; } long nextLong() { return Long.parseLong(next()); } long[] rla(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = Long.parseLong(next()); return a; } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
java
1291
A
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4 4 1227 1 0 6 177013 24 222373204424185217171912 OutputCopy1227 -1 17703 2237344218521717191 NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).
[ "greedy", "math", "strings" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { static long M = (long) (1e9 + 7); static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if (st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static void heapify(int arr[], int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < n && arr[l] > arr[largest]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; heapify(arr, n, largest); } } public static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static int lcm(int a, int b) { return (a * b / gcd(a, b)); } public static String sortString(String inputString) { // Converting input string to character array char[] tempArray = inputString.toCharArray(); // Sorting temp array using Arrays.sort(tempArray); // Returning new sorted string return new String(tempArray); } static boolean isSquare(int n) { int v = (int) Math.sqrt(n); return v * v == n; } static boolean PowerOfTwo(int n) { if (n == 0) return false; return (int) (Math.ceil((Math.log(n) / Math.log(2)))) == (int) (Math.floor(((Math.log(n) / Math.log(2))))); } static int power(long a, long b) { long res = 1; while (b > 0) { if (b % 2 == 1) { res = (res * a) % M; } a = ((a * a) % M); b = b / 2; } return (int) res; } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); int t = sc.nextInt(); while (t-- != 0) { String ans=""; int n=sc.nextInt(); String s=sc.next(); for(int i=0;i<s.length();i++) { if((s.charAt(i)-'0')%2!=0) { ans=ans+s.charAt(i); } if(ans.length()==2) { break; } } if(ans.length()==2) { System.out.println(ans); } else{ System.out.println("-1"); } } } }
java
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
import java.util.*; import java.io.*; import java.math.*; import java.lang.*; public class CP { static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st==null || !st.hasMoreTokens()) { try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } static void ruffleSort(int[] a) { Random rnd=new Random(); for(int i=0;i<=a.length-1;i++) { int temp=a[i]; int rndPos=i+rnd.nextInt(a.length-i); a[i]=a[rndPos]; a[rndPos]=temp; } Arrays.sort(a); } static void testCase(FastScanner sc) { long mod1=(long)1e9+7, mod2=998244353; long inf=(long)1e18+5; int n=sc.nextInt(); int[] a=new int[n]; int[] b=new int[n]; for(int i=0;i<=n-1;i++) { a[i]=sc.nextInt(); } for(int i=0;i<=n-1;i++) { b[i]=sc.nextInt(); } ruffleSort(a); ruffleSort(b); for(int i=0;i<=n-1;i++) { System.out.print(a[i]+" "); } System.out.println(); for(int i=0;i<=n-1;i++) { System.out.print(b[i]+" "); } System.out.println(); } public static void main(String[] args) { FastScanner sc=new FastScanner(); boolean test=true; int t=1; if(test) { t=sc.nextInt(); } for(int i=0;i<=t-1;i++) { testCase(sc); } } }
java
1296
E1
E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9 abacbecfd OutputCopyYES 001010101 InputCopy8 aaabbcbb OutputCopyYES 01011011 InputCopy7 abcdedc OutputCopyNO InputCopy5 abcde OutputCopyYES 00000
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
// package CP; import java.util.*; import java.io.*; import java.lang.*; public class contest { static long primeMod = 999999999999989L; static class pair { int x, y, p, q; pair(int x, int y, int p, int q) { this.x = x; this.y = y; this.p = p; this.q = q; } pair(int x, int y, int p) { this.x = x; this.y = y; this.p = p; } pair(int x, int y) { this.x = x; this.y = y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return x == p.x && y == p.y; } return false; } public int hashCode() { return (Long.valueOf(x).hashCode()) * 31 + (Long.valueOf(y).hashCode()); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void swap(int arr[], int x, int y) { int t = arr[x]; arr[x] = arr[y]; arr[y] = t; } static int LongestIncreasingSubsequenceLength(int A[], int size) { int[] tailTable = new int[size]; int len; tailTable[0] = A[0]; len = 1; for (int i = 1; i < size; i++) { if (A[i] < tailTable[0]) tailTable[0] = A[i]; else if (A[i] > tailTable[len - 1]) tailTable[len++] = A[i]; else tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i]; } return len; } static int CeilIndex(int A[], int l, int r, int key) { while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] >= key) r = m; else l = m; } return r; } public static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } public static long sum(long n) { return (n * (n + 1)) / 2; } static int N = 1000000; static boolean primeSeiveDp[] = new boolean[N]; public static void primeSeive() { primeSeiveDp[0] = true; primeSeiveDp[1] = true; for (int i = 2; i * i < N; i += 2) { if (primeSeiveDp[i] == false) { for (int j = i * i; j < N; j += i) { primeSeiveDp[j] = true; } } } } public static ArrayList<Integer> primeLessThan(int m) { ArrayList<Integer> primes = new ArrayList<Integer>(); for (int i = 2; i * i <= m; i++) { if (primeSeiveDp[i] == false) { primes.add(i); } } return primes; } public static ArrayList<Integer> primesList(int n, int m) { primeSeive(); ArrayList<Integer> primes = primeLessThan(m); boolean primeSeiveRange[] = new boolean[m - n + 1]; for (int pr : primes) { int nextMultiple = (n / pr) * pr; if (nextMultiple < n) { nextMultiple += pr; } for (int i = Math.max(nextMultiple, pr * pr); i <= m; i += pr) { primeSeiveRange[i - n] = true; } } ArrayList<Integer> primesRange = new ArrayList<Integer>(); for (int i = n; i <= m; i++) { if (primeSeiveRange[i - n] == false && i != 1) { primesRange.add(i); } } return primesRange; } public static HashMap<Integer, ArrayList<Integer>> findDivisors() { HashMap<Integer, ArrayList<Integer>> divisors = new HashMap<>(); for (int i = 2; i < 100000; i++) { for (int j = i; j < 100000; j += i) { ArrayList<Integer> list = divisors.getOrDefault(j, new ArrayList<Integer>()); list.add(i); divisors.put(j, list); } } return divisors; } public static int[] findprimeFact() { int seivepf[] = new int[10000000]; for (int i = 0; i < 10000000; i++) { seivepf[i] = i; } for (int i = 2; i * i < 10000000; i++) { if (seivepf[i] == i) { for (int j = i * i; j < 10000000; j += i) { if (seivepf[j] == j) seivepf[j] = i; } } } return seivepf; } public static ArrayList<Integer> primeFactors(int n) { int spf[] = findprimeFact(); ArrayList<Integer> primeFactors = new ArrayList<Integer>(); while (n != 1) { primeFactors.add(spf[n]); n = n / spf[n]; } return primeFactors; } public static long moduloMulInv(long n, long m) { // m is modulo // n and must be co-prime // n<m return binaryExpo(n, m - 2, m); } public static long binaryExpo(long a, long b, long m) { long result = 1; while (b > 0) { if ((b & 1) == 1) { // odd result = (result * 1L * a) % m; } // multiply to base a = (a * 1L * a) % m; b >>= 1; } return result; } public static long setBit(long a, long i) { // i starts from 0 return a | (1 << i); } public static long unSetBit(long a, long i) { // i starts from 0 return a & (~(1 << i)); } public static long toggleBit(long a, long i) { // i starts from 0 return a ^ (1 << i); } public static long removeRightMostSetBit(long a) { // right most set bit = a&(-a) return a - (a & (-a)); } public static long addRightMostSetBit(long a) { // right most set bit = a&(-a) return a + (a & (-a)); } public static int[] buildLPS(String str) { int n = str.length(); int[] lps = new int[n]; int i = 1; int len = 0; lps[0] = 0; while (i < n) { if (str.charAt(i) == str.charAt(len)) { len++; lps[i] = len; i++; } else if (len == 0) { lps[i] = 0; i++; } else { len = lps[len - 1]; } } return lps; } public static void dfsEdgeCutAlgo(ArrayList<ArrayList<Integer>> adj, int n, HashSet<String> iscut) { int timer = 0; int dis[] = new int[n]; int low[] = new int[n]; Arrays.fill(dis, -1); Arrays.fill(low, -1); for (int i = 0; i < n; i++) { if (dis[i] == -1) { dfsEdgeCut(adj, i, -1, dis, low, timer, iscut); } } } public static void dfsEdgeCut(ArrayList<ArrayList<Integer>> adj, int i, int parent, int dis[], int low[], int timer, HashSet<String> iscut) { dis[i] = timer; low[i] = timer; timer++; for (int it : adj.get(i)) { if (it == parent) continue; if (dis[it] == -1) { dfsEdgeCut(adj, it, i, dis, low, timer, iscut); low[i] = Math.min(low[i], low[it]); if (low[it] > dis[i]) { if (!iscut.contains(i + "#" + it) && !iscut.contains(it + "#" + i)) iscut.add(it + "#" + i); } } else { low[i] = Math.min(low[i], dis[it]); } } } public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int t = 1; // t = sc.nextInt(); while (t-- != 0) { int n = sc.nextInt(); String str=sc.next(); char p1='a'; char p2='a'; String ans = ""; for(int i=0;i<n;i++){ char curr=str.charAt(i); if(curr>=p1){ ans+='0'; p1=curr; }else if(curr>=p2){ ans+='1'; p2=curr; }else{ System.out.println("NO"); return; } } System.out.println("YES"); System.out.println(ans); } } }
java
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5 1 1 1 1 1 2 1 4 1 3 OutputCopy9 InputCopy3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 OutputCopy7 InputCopy10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 OutputCopy72 NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
/* _oo0oo_ o8888888o 88" . "88 (| -_- |) 0\ = /0 ___/`---'\___ .' \\| |// '. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' |_/ | \ .-\__ '-' ___/-. / ___'. .' /--.--\ `. .'___ ."" '< `.___\_<|>_/___.' >' "". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `_. \_ __\ /__ _/ .-` / / =====`-.____`.___ \_____/___.-`___.-'===== `=---=' */ import java.util.function.Consumer; import java.util.*; import java.math.*; import java.io.*; import java.lang.Math.*; public class KickStart2020 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long lcm(long a, long b) { return a / gcd(a,b) * b; } public static class Pair implements Comparable<Pair> { public int index; public int value; public Pair(int index, int value) { this.index = index; this.value = value; } @Override public int compareTo(Pair other) { // multiplied to -1 as the author need descending sort order return -1 * Integer.valueOf(this.value).compareTo(other.value); } } static boolean isPrime(long d) { if (d == 1) return false; for (int i = 2; i <= (long) Math.sqrt(d); i++) { if (d % i == 0) return false; } return true; } static void decimalTob(long n, int b, int arr[], int i) { long z = n % b; arr[i] += (int) z; n /= b; if (n > 0) { i++; decimalTob(n, b, arr, i); } } static long powermod(long x, long y, long mod) { long ans = 1; x = x % mod; if (x == 0) return 0; int i = 1; while (y > 0) { if ((y & 1) != 0) ans = (ans * x) % mod; y = y >> 1; x = (x * x) % mod; } return ans; } static boolean isEqual(ArrayList<Integer> ss , ArrayList<Integer> ssf) { for(int i = 0; i < ss.size(); i++) if((int)ss.get(i) != (int)ssf.get(i)) return false; return true; } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = 1; outerloop: while (t-- > 0) { int n = sc.nextInt(); long count = 0, count1 = 0; int arr[] = new int[1000000 + 2]; ArrayList<Pair> ss =new ArrayList<>(); for(int i = 0; i < n; i++) { int m = sc.nextInt(); ArrayList<Integer> ssf = new ArrayList<>(); ArrayList<Integer> ssd = new ArrayList<>(); for(int j = 0; j < m; j++) { int a = sc.nextInt(); ssf.add(a); ssd.add(a); } Collections.sort(ssf, Collections.reverseOrder()); if(isEqual(ssf, ssd)) { ss.add(new Pair(ssf.get(0), ssf.get(m - 1))); arr[ssf.get(0)]++; } else { count += n; count1++;} } for(int i = arr.length - 2; i >= 0; i--) arr[i] += arr[i + 1]; count += count1 * ss.size(); for(int i = 0; i < ss.size(); i++) { int z = ss.get(i).value; count += arr[z + 1]; } out.println(count); } out.close(); } }
java
1324
E
E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23 16 17 14 20 20 11 22 OutputCopy3 NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.
[ "dp", "implementation" ]
import java.io.*; import java.util.*; public class Sleeping_Schedule2 { static FastScanner fs; static FastWriter fw; static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null; private static final int[][] kdir = new int[][]{{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}}; private static final int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; private static final int iMax = Integer.MAX_VALUE, iMin = Integer.MIN_VALUE; private static final long lMax = Long.MAX_VALUE, lMin = Long.MIN_VALUE; private static final int mod1 = (int) (1e9 + 7); private static final int mod2 = 998244353; public static void main(String[] args) throws IOException { fs = new FastScanner(); fw = new FastWriter(); int t = 1; //t = fs.nextInt(); while (t-- > 0) { solve(); } fw.out.close(); } private static void solve() { int n = fs.nextInt(), h = fs.nextInt(), l = fs.nextInt(), r = fs.nextInt(); int[] arr = readIntArray(n); int[][] dp = new int[n + 1][h]; for (int[] row : dp) Arrays.fill(row, iMin); dp[0][0] = 0; for (int i = 1; i <= n; i++) { int a = arr[i - 1]; for (int j = 0; j < h; j++) { int inRange = (j >= l && j <= r) ? 1 : 0; int jj = (j - a + h) % h; if (dp[i - 1][jj] != iMin) { dp[i][j] = inRange + dp[i - 1][jj]; } jj = (j - a + 1 + h) % h; if (dp[i - 1][jj] != iMin) { dp[i][j] = Math.max(dp[i][j], inRange + dp[i - 1][jj]); } } } int ans = 0; for (int j = 0; j < h; j++) ans = Math.max(ans, dp[n][j]); fw.out.println(ans); } private static class UnionFind { private final int[] parent; private final int[] rank; UnionFind(int n) { parent = new int[n + 5]; rank = new int[n + 5]; for (int i = 0; i <= n; i++) { parent[i] = i; rank[i] = 0; } } private int find(int i) { if (parent[i] == i) return i; return parent[i] = find(parent[i]); } private void union(int a, int b) { a = find(a); b = find(b); if (a != b) { if (rank[a] < rank[b]) { int temp = a; a = b; b = temp; } parent[b] = a; if (rank[a] == rank[b]) rank[a]++; } } } private static class SCC { private final int n; private final List<List<Integer>> adjList; SCC(int _n, List<List<Integer>> _adjList) { n = _n; adjList = _adjList; } private List<List<Integer>> getSCC() { List<List<Integer>> ans = new ArrayList<>(); Stack<Integer> stack = new Stack<>(); boolean[] vis = new boolean[n]; for (int i = 0; i < n; i++) { if (!vis[i]) dfs(i, adjList, vis, stack); } vis = new boolean[n]; List<List<Integer>> rev_adjList = rev_graph(n, adjList); while (!stack.isEmpty()) { int curr = stack.pop(); if (!vis[curr]) { List<Integer> scc_list = new ArrayList<>(); dfs2(curr, rev_adjList, vis, scc_list); ans.add(scc_list); } } return ans; } private void dfs(int curr, List<List<Integer>> adjList, boolean[] vis, Stack<Integer> stack) { vis[curr] = true; for (int x : adjList.get(curr)) { if (!vis[x]) dfs(x, adjList, vis, stack); } stack.add(curr); } private void dfs2(int curr, List<List<Integer>> adjList, boolean[] vis, List<Integer> scc_list) { vis[curr] = true; scc_list.add(curr); for (int x : adjList.get(curr)) { if (!vis[x]) dfs2(x, adjList, vis, scc_list); } } } private static List<List<Integer>> rev_graph(int n, List<List<Integer>> adjList) { List<List<Integer>> ans = new ArrayList<>(); for (int i = 0; i < n; i++) ans.add(new ArrayList<>()); for (int i = 0; i < n; i++) { for (int x : adjList.get(i)) { ans.get(x).add(i); } } return ans; } private static class Calc_nCr { private final long[] fact; private final long[] invfact; private final int p; Calc_nCr(int n, int prime) { fact = new long[n + 5]; invfact = new long[n + 5]; p = prime; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = (i * fact[i - 1]) % p; } invfact[n] = pow_with_mod(fact[n], p - 2, p); for (int i = n - 1; i >= 0; i--) { invfact[i] = (invfact[i + 1] * (i + 1)) % p; } } private long nCr(int n, int r) { if (r > n || n < 0 || r < 0) return 0; return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p; } } private static int random_between_two_numbers(int l, int r) { Random ran = new Random(); return ran.nextInt(r - l) + l; } private static long gcd(long a, long b) { return (b == 0 ? a : gcd(b, a % b)); } private static long lcm(long a, long b) { return ((a * b) / gcd(a, b)); } private static long pow(long a, long b) { long result = 1; while (b > 0) { if ((b & 1L) == 1) { result = (result * a); } a = (a * a); b >>= 1; } return result; } private static long pow_with_mod(long a, long b, int mod) { long result = 1; while (b > 0) { if ((b & 1L) == 1) { result = (result * a) % mod; } a = (a * a) % mod; b >>= 1; } return result; } private static long ceilDiv(long a, long b) { return ((a + b - 1) / b); } private static long getMin(long... args) { long min = lMax; for (long arg : args) min = Math.min(min, arg); return min; } private static long getMax(long... args) { long max = lMin; for (long arg : args) max = Math.max(max, arg); return max; } private static boolean isPalindrome(String s, int l, int r) { int i = l, j = r; while (j - i >= 1) { if (s.charAt(i) != s.charAt(j)) return false; i++; j--; } return true; } private static List<Integer> primes(int n) { boolean[] primeArr = new boolean[n + 5]; Arrays.fill(primeArr, true); for (int i = 2; (i * i) <= n; i++) { if (primeArr[i]) { for (int j = i * i; j <= n; j += i) { primeArr[j] = false; } } } List<Integer> primeList = new ArrayList<>(); for (int i = 2; i <= n; i++) { if (primeArr[i]) primeList.add(i); } return primeList; } private static int noOfSetBits(long x) { int cnt = 0; while (x != 0) { x = x & (x - 1); cnt++; } return cnt; } private static int sumOfDigits(long num) { int cnt = 0; while (num > 0) { cnt += (num % 10); num /= 10; } return cnt; } private static int noOfDigits(long num) { int cnt = 0; while (num > 0) { cnt++; num /= 10; } return cnt; } private static boolean isPerfectSquare(long num) { long sqrt = (long) Math.sqrt(num); return ((sqrt * sqrt) == num); } private static class Pair<U, V> { private final U first; private final V second; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return first.equals(pair.first) && second.equals(pair.second); } @Override public int hashCode() { return Objects.hash(first, second); } @Override public String toString() { return "(" + first + ", " + second + ")"; } private Pair(U ff, V ss) { this.first = ff; this.second = ss; } } private static void randomizeIntArr(int[] arr, int n) { Random r = new Random(); for (int i = (n - 1); i > 0; i--) { int j = r.nextInt(i + 1); swapInIntArr(arr, i, j); } } private static void randomizeLongArr(long[] arr, int n) { Random r = new Random(); for (int i = (n - 1); i > 0; i--) { int j = r.nextInt(i + 1); swapInLongArr(arr, i, j); } } private static void swapInIntArr(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } private static void swapInLongArr(long[] arr, int a, int b) { long temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } private static int[] readIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = fs.nextInt(); return arr; } private static long[] readLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = fs.nextLong(); return arr; } private static List<Integer> readIntList(int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(fs.nextInt()); return list; } private static List<Long> readLongList(int n) { List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(fs.nextLong()); return list; } private static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() throws IOException { if (checkOnlineJudge) this.br = new BufferedReader(new FileReader("src/input.txt")); else this.br = new BufferedReader(new InputStreamReader(System.in)); this.st = new StringTokenizer(""); } public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException err) { err.printStackTrace(); } } return st.nextToken(); } public String nextLine() { if (st.hasMoreTokens()) { return st.nextToken("").trim(); } try { return br.readLine().trim(); } catch (IOException err) { err.printStackTrace(); } return ""; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } private static class FastWriter { PrintWriter out; FastWriter() throws IOException { if (checkOnlineJudge) out = new PrintWriter(new FileWriter("src/output.txt")); else out = new PrintWriter(System.out); } } }
java
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3 2 3 4 7 2 4 3 2 5 11 1 2 4 2 1 6 3 4 6 OutputCopy1
[ "brute force", "data structures", "sortings" ]
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; // lazy prop sgt impl partly from benq's https://codeforces.com/contest/1320/submission/72172966 // sgt specialized for range sum upd and range max qry public class cf1320c { static int n, m, p, mx = 262144; static long sgt[], lazy[]; static void build(long[] a, int node, int l, int r) { if(l == r) { sgt[node] = l < a.length ? a[l] : LMIN >> 1; } else if(l < r) { int m = l + (r - l) / 2; build(a, node << 1, l, m); build(a, node << 1 | 1, m + 1, r); pull(node); } } static void push(int node, int l, int r) { if(lazy[node] != 0) { sgt[node] += lazy[node]; if(l < r) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; } lazy[node] = 0; } } static void pull(int node) { sgt[node] = max(sgt[node << 1], sgt[node << 1 | 1]); } static void upd(int i, int j, long x, int node, int l, int r) { push(node, l, r); if(j < l || r < i) { return; } if(i <= l && r <= j) { lazy[node] = x; push(node, l, r); } else { int m = l + (r - l) / 2; upd(i, j, x, node << 1, l, m); upd(i, j, x, node << 1 | 1, m + 1, r); pull(node); } } static long qry(int i, int j, int node, int l, int r) { push(node, l, r); if(j < l || r < i) { return 0; } if(i <= l && r <= j) { return sgt[node]; } else { int m = l + (r - l) / 2; return qry(i, j, node << 1, l, m) + qry(i, j, node << 1 | 1, m + 1, r); } } public static void main(String[] args) throws IOException { n = rni(); m = ni(); p = ni(); int a[][] = new int[n][2], b[][] = new int[m][2], mon[][] = new int[p][3]; sgt = new long[mx << 1]; lazy = new long[mx << 1]; for(int i = 0; i < n; ++i) { a[i][0] = rni(); a[i][1] = ni(); } for(int i = 0; i < m; ++i) { b[i][0] = rni(); b[i][1] = ni(); } for(int i = 0; i < p; ++i) { mon[i][0] = rni(); mon[i][1] = ni(); mon[i][2] = ni(); } Comparator<int[]> cmp = (x, y) -> x[0] - y[0]; sort(a, cmp); sort(b, cmp); sort(mon, cmp); long[] sgtinit = new long[m]; TreeMap<Integer, Integer> find = new TreeMap<>(); for(int i = 0; i < m; ++i) { sgtinit[i] = -b[i][1]; if(!find.containsKey(b[i][0])) { find.put(b[i][0], i); } } build(sgtinit, 1, 0, mx - 1); int curmon = 0; long ans = LMIN; for(int i = 0; i < n; ++i) { while(curmon < p && mon[curmon][0] < a[i][0]) { Integer ind = find.higherKey(mon[curmon][1]); if(ind != null) { // prln(mon[curmon][1], ind, find.get(ind)); upd(find.get(ind), mx - 1, mon[curmon][2], 1, 0, mx - 1); } ++curmon; } // prln(-a[i][1], qry(0, mx - 1, 1, 0, m - 1)); ans = max(ans, -a[i][1] + qry(0, mx - 1, 1, 0, mx - 1)); } prln(ans); close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int)d;} static int cei(double d) {return (int)ceil(d);} static long fll(double d) {return (long)d;} static long cel(double d) {return (long)ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long hash(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static int[] sorted(int[] a) {int[] ans = copy(a); sort(ans); return ans;} static long[] sorted(long[] a) {long[] ans = copy(a); sort(ans); return ans;} static int[] rsorted(int[] a) {int[] ans = copy(a); rsort(ans); return ans;} static long[] rsorted(long[] a) {long[] ans = copy(a); rsort(ans); return ans;} // graph util static List<List<Integer>> graph(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<List<Integer>> graph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;} static List<List<Integer>> graph(int n, int m) throws IOException {return graph(graph(n), m);} static List<List<Integer>> dgraph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;} static List<List<Integer>> dgraph(List<List<Integer>> g, int n, int m) throws IOException {return dgraph(graph(n), m);} static List<Set<Integer>> sgraph(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static List<Set<Integer>> sgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;} static List<Set<Integer>> sgraph(int n, int m) throws IOException {return sgraph(sgraph(n), m);} static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;} static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int n, int m) throws IOException {return dsgraph(sgraph(n), m);} static void connect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void connecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dconnect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dconnecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()) - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
java
1296
B
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6 1 10 19 9876 12345 1000000000 OutputCopy1 11 21 10973 13716 1111111111
[ "math" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Vc { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); int numberSets = Integer.parseInt(br.readLine()); for (int nos = 0; nos < numberSets; nos++) { // int [] data = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); int number = Integer.parseInt(br.readLine()); int res = 0; while (number >= 10) { res += number - number%10; number = number/10 + number%10; } res+= number; System.out.println(res); } } }
java
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3 1 3 2 -100 2 3 OutputCopy3 InputCopy5 2 1 4 3 5 2 2 2 3 4 OutputCopy19 InputCopy2 2 1 -3 0 OutputCopy0
[ "data structures", "divide and conquer", "implementation", "sortings" ]
// package codeforce.Training1900; import java.io.PrintWriter; import java.util.*; public class MovingPoints { // well this segment tree only can do range query and point update, so if you want range update, please go to lazy segment tree static class SegTree { private int N; // Let UNIQUE be a value which does NOT // and will not appear in the segment tree private long UNIQUE = 0; // Segment tree values private long[] tree; public SegTree(int size) { tree = new long[2 * (N = size)]; java.util.Arrays.fill(tree, UNIQUE); } public SegTree(long[] values) { this(values.length); for (int i = 0; i < N; i++) modify(i, values[i]); } // This is the segment tree function we are using for queries. // The function must be an associative function, meaning // the following property must hold: f(f(a,b),c) = f(a,f(b,c)). // Common associative functions used with segment trees // include: min, max, sum, product, GCD, and etc... private long function(long a, long b) { if (a == UNIQUE) return b; else if (b == UNIQUE) return a; return a + b; // sum over a range //return (a > b) ? a : b; // maximum value over a range //return (a < b) ? a : b; // minimum value over a range // return a * b; // product over a range (watch out for overflow!) } // Adjust point i by a value, O(log(n)) public void modify(int i, long value) { //tree[i + N] = function(tree[i + N], value); tree[i + N] = value; for (i += N; i > 1; i >>= 1) { tree[i >> 1] = function(tree[i], tree[i ^ 1]); } } // Query interval [l, r), O(log(n)) ----> notice the exclusion of r public long query(int l, int r) { long res = UNIQUE; for (l += N, r += N; l < r; l >>= 1, r >>= 1) { if ((l & 1) != 0) res = function(res, tree[l++]); if ((r & 1) != 0) res = function(res, tree[--r]); } if (res == UNIQUE) { //throw new IllegalStateException("UNIQUE should not be the return value."); return 0; } return res; } } // MUST SEE BEFORE SUBMISSION // check whether int part would overflow or not, especially when it is a * b!!!! public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); // int t = sc.nextInt(); int t = 1; for (int i = 0; i < t; i++) { solve(sc, pw); } pw.close(); } static long maxRight = Integer.MAX_VALUE; static void solve(Scanner in, PrintWriter out){ int n = in.nextInt(); int[][] arr = new int[n][2]; for (int i = 0; i < n; i++) { arr[i][0] = in.nextInt(); } for (int i = 0; i < n; i++) { arr[i][1] = in.nextInt(); } LinkedList<int[]> rev = new LinkedList<>(); LinkedList<int[]> ok = new LinkedList<>(); long ans = 0; for (int i = 0; i < n; i++) { if (arr[i][1] < 0){ rev.add(new int[]{-arr[i][0], -arr[i][1]}); }else{ ok.add(arr[i]); } } ans = sameDirection(rev) + sameDirection(ok); LinkedList<int[]> qs = new LinkedList<>(); LinkedList<int[]> ql = new LinkedList<>(); for (int i = 0; i < n; i++) { if (arr[i][1] < 0){ qs.add(arr[i]); }else{ ql.add(arr[i]); } } ans += differenDirection(qs, ql); out.println(ans); } static long sameDirection(LinkedList<int[]> q){ long ans = 0; int n = q.size(); SegTree sg = new SegTree(n + 5); SegTree ct = new SegTree(n + 5); List<int[]> qq = new ArrayList<>(); Collections.sort(q, (a, b) -> (a[0] - b[0])); for (int i = 0; i < n; i++) { int[] fk = q.poll(); qq.add(new int[]{fk[0], fk[1], i}); } Collections.sort(qq, (a, b) -> (a[1] - b[1])); for(int[] arr : qq){ int pos = arr[0], idx = arr[2]; long get = sg.query(0, idx); long tot = ct.query(0, idx); ans += (get - (maxRight - pos) * tot); sg.modify(idx, maxRight - pos); ct.modify(idx, 1); } return ans; } static long differenDirection(LinkedList<int[]> qs, LinkedList<int[]> ql){ Collections.sort(qs, (a, b) -> (a[0] - b[0])); Collections.sort(ql, (a, b) -> (a[0] - b[0])); long ans = 0; int cnt = 0; long pre = 0; while (ql.size() > 0){ int[] shit = ql.poll(); int pos = shit[0]; while (qs.size() > 0 && qs.peek()[0] < pos){ int[] get = qs.poll(); cnt++; pre += (maxRight - get[0]); } ans += (pre - cnt * (maxRight - pos)); } return ans; } }
java
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2 OutputCopy5 InputCopy10 1 OutputCopy55 InputCopy723 9 OutputCopy157557417 NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
[ "combinatorics", "dp" ]
/* _oo0oo_ o8888888o 88" . "88 (| -_- |) 0\ = /0 ___/`---'\___ .' \\| |// '. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' |_/ | \ .-\__ '-' ___/-. / ___'. .' /--.--\ `. .'___ ."" '< `.___\_<|>_/___.' >' "". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `_. \_ __\ /__ _/ .-` / / =====`-.____`.___ \_____/___.-`___.-'===== `=---=' */ import java.util.*; import java.math.*; import java.io.*; import java.lang.Math.*; public class KickStart2020 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long lcm(long a, long b) { return a / gcd(a, b) * b; } public static class Pair implements Comparable<Pair> { public int index; public int value; public Pair(int index, int value) { this.index = index; this.value = value; } @Override public int compareTo(Pair other) { // multiplied to -1 as the author need descending sort order if(other.index < this.index) return -1; if(other.index > this.index) return 1; if(other.value < this.value) return -1; if(other.value > this.value) return 1; return 0; } @Override public String toString() { return this.index + " " + this.value; } } static boolean isPrime(long d) { if(d == 0) return true; if (d == 1) return false; for (int i = 2; i <= (long) Math.sqrt(d); i++) { if (d % i == 0) return false; } return true; } static String decimalTob(int n, int k , String count) { int x = n % k; int y = n / k; count += x; if(y > 0) { count = decimalTob(y, k, count); } return count; } static long powermod(long x, long y, long mod) { if(y == 0) return 1; long value = powermod(x, y / 2, mod); if(y % 2 == 0) return (value * value) % mod; return (value * (value * x) % mod) % mod; } static long power(long x, long y) { if(y == 0) return 1; long value = power(x, y / 2); if(y % 2 == 0) return (value * value); return value * value * x; } static int bS(int l, int r, int find, int arr[]) { if(r < l) return l; int mid = (l + r) / 2; if(arr[mid] >= find) return bS(l, mid - 1, find, arr); return bS(mid + 1, r, find, arr); } static int dp(int l, int r, int dp[][]) { if(r == 0 || r == l) return 1; if(dp[l][r] != 0) return dp[l][r]; int ans = dp(l - 1, r - 1, dp) + dp(l - 1, r, dp); return dp[l][r] = ans % 1000000007; } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = 1; outerloop: while(t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int dp[][] = new int[2*m + n][n]; int ans = dp(2 * m + n - 1, n - 1, dp); out.println(ans); } out.close(); } }
java
1285
A
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4 LRLR OutputCopy5 NoteIn the example; Zoma may end up anywhere between −2−2 and 22.
[ "math" ]
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String s = in.next(); int r = 0; int l = 0; for (int i = 0; i < n; i++) { if(s.charAt(i) == 'R') r++; else l++; } System.out.println(r + l + 1); } } /* * BAN * */
java
1313
B
B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
[ "constructive algorithms", "greedy", "implementation", "math" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); BDifferentRules solver = new BDifferentRules(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) { solver.solve(i, in, out); } out.close(); } static class BDifferentRules { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int x = in.nextInt(); int y = in.nextInt(); int res1 = Math.min(n, Math.max(1, x + y - n + 1)); int res2 = Math.min(n, x + y - 1); out.println(res1, res2); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
java
1320
D
D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5 11011 3 1 3 3 1 4 2 1 2 3 OutputCopyYes Yes No
[ "data structures", "hashing", "strings" ]
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class C1320D { static long modulo1 = (long) 1e9 + 9; static long modulo2 = (long) 1e9 + 7; static long r1 = 3; static long r2 = 5; public static void main(String[] args) { var scanner = new BufferedScanner(); var writer = new PrintWriter(new BufferedOutputStream(System.out)); var n = scanner.nextInt(); var t = scanner.next(); var count0 = new int[n + 1]; { count0[0] = 0; for (int len = 1; len <= n; len++) { count0[len] = count0[len - 1] + (t.charAt(len - 1) == '0' ? 1 : 0); } } var power1 = new long[n + 1]; var power2 = new long[n + 1]; power1[0] = 1; power2[0] = 1; for (int i = 1; i <= n; i++) { power1[i] = power1[i - 1] * r1 % modulo1; power2[i] = power2[i - 1] * r2 % modulo2; } var hashEven1 = new long[n + 1][]; var hashOdd1 = new long[n + 1][]; calcHash(t, n, power1, hashEven1, hashOdd1, count0, modulo1, r1); var hashEven2 = new long[n + 1][]; var hashOdd2 = new long[n + 1][]; calcHash(t, n, power2, hashEven2, hashOdd2, count0, modulo2, r2); var q = scanner.nextInt(); for (int qi = 0; qi < q; qi++) { var l1 = scanner.nextInt() - 1; var l2 = scanner.nextInt() - 1; var len = scanner.nextInt(); var ans = false; // 首先,0的个数得一样多 if (count0[l1 + len] - count0[l1] == count0[l2 + len] - count0[l2]) { // 其次,从各子串开头算起的0的下标得对应位同奇偶。 var fp11 = fingerprint(l1, l1 + len - 1, power1, hashEven1, hashOdd1, count0, modulo1); var fp21 = fingerprint(l2, l2 + len - 1, power1, hashEven1, hashOdd1, count0, modulo1); var fp12 = fingerprint(l1, l1 + len - 1, power2, hashEven2, hashOdd2, count0, modulo2); var fp22 = fingerprint(l2, l2 + len - 1, power2, hashEven2, hashOdd2, count0, modulo2); // System.out.println(String.format("%d,%d,%d %d,%d", qi + 1, fp11, fp21, fp12, fp22)); if (fp11 == fp21 && fp12 == fp22) { ans = true; } } writer.println(ans ? "Yes" : "No"); } scanner.close(); writer.flush(); writer.close(); } private static void calcHash(String t, int n, long[] power, long[][] hashEven, long[][] hashOdd, int[] count0, long modulo, long r) { var limit = r * modulo; // System.out.println(String.format("modulo=%d,r=%d", modulo, r)); for (int len = 1; len <= n; len <<= 1) { hashEven[len] = new long[n]; hashOdd[len] = new long[n]; var he = 0L; var ho = 0L; for (int i = 0; i < n; i++) { if (t.charAt(i) == '0') { var bitEven = (i & 1) + r / 2; // 对偶数开头子字符串来说,i是偶数在子字符串也是偶数位,用0表示;否则用1。 var bitOdd = r - bitEven; // 对奇数位开头的子字符串来说,i是偶数在子字符串是奇数位,用1表示;否则用0。 he = (he * r + bitEven) % modulo; ho = (ho * r + bitOdd) % modulo; } if (i >= len && t.charAt(i - len) == '0') { var bitEven0 = ((i - len) & 1) + r / 2; var bitOdd0 = r - bitEven0; var cnt0 = count0[i + 1] - count0[i + 1 - len]; he = (he + limit - power[cnt0] * bitEven0) % modulo; // power[cnt0]*bitEven0<modulo*r ho = (ho + limit - power[cnt0] * bitOdd0) % modulo; // power[cnt0]*bitOdd0<modulo*r } if (i >= len - 1) { hashEven[len][i - len + 1] = he; hashOdd[len][i - len + 1] = ho; } if (he < 0 || ho < 0) { throw new RuntimeException("wtf"); } } } } private static long fingerprint(int start, int end, long[] power, long[][] hashEven, long[][] hashOdd, int[] count0, long modulo) { if ((start & 1) == 0) { return fingerprint(start, end, power, hashEven, count0, modulo); } else { return fingerprint(start, end, power, hashOdd, count0, modulo); } } private static long fingerprint(int start, int end, long[] power, long[][] hash, int[] count0, long modulo) { var len = 1 << (int) (Math.log(end - start + 1) / Math.log(2)); var fp = 0L; while (start <= end) { var cnt0 = count0[start + len] - count0[start]; fp = (fp * power[cnt0] + hash[len][start]) % modulo; if (fp < 0) { throw new RuntimeException("wtf"); } start += len; while (len > 0 && start + len - 1 > end) { len >>= 1; } } return fp; } public static class BufferedScanner { BufferedReader br; StringTokenizer st; public BufferedScanner(Reader reader) { br = new BufferedReader(reader); } public BufferedScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } static long gcd(long a, long b) { if (a < b) { return gcd(b, a); } while (b > 0) { long tmp = b; b = a % b; a = tmp; } return a; } static long inverse(long a, long m) { long[] ans = extgcd(a, m); return ans[0] == 1 ? (ans[1] + m) % m : -1; } private static long[] extgcd(long a, long m) { if (m == 0) { return new long[]{a, 1, 0}; } else { long[] ans = extgcd(m, a % m); long tmp = ans[1]; ans[1] = ans[2]; ans[2] = tmp; ans[2] -= ans[1] * (a / m); return ans; } } private static List<Integer> primes(double upperBound) { var limit = (int) Math.sqrt(upperBound); var isComposite = new boolean[limit + 1]; var primes = new ArrayList<Integer>(); for (int i = 2; i <= limit; i++) { if (isComposite[i]) { continue; } primes.add(i); int j = i + i; while (j <= limit) { isComposite[j] = true; j += i; } } return primes; } }
java
1315
A
A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6 8 8 0 0 1 10 0 3 17 31 10 4 2 1 0 0 5 10 3 9 10 10 4 8 OutputCopy56 6 442 1 45 80 NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.
[ "implementation" ]
/*============================================== Author : Shadman Shariar || Email : [email protected] || University : North South University (NSU) || Facebook : shadman.shahriar.007 || ==============================================*/ import java.io.*; import java.util.*; //import java.math.BigInteger; //import java.text.DecimalFormat; public class Main { public static Main obj = new Main(); public static int [] dx = {-1, 1, 0, 0, -1, -1, 1, 1}; public static int [] dy = {0, 0, -1, 1, -1, 1, -1, 1}; //public static FastReader fr = new FastReader(); public static Scanner input = new Scanner(System.in); //public static PrintWriter pw = new PrintWriter(System.out); //public static DecimalFormat df = new DecimalFormat(".000000000"); //public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main (String[] args) throws Exception { Scanner input = new Scanner (System.in); //BigInteger bi = new BigInteger("000"); //StringBuilder sb = new StringBuilder(); //StringBuffer sbf = new StringBuffer(); //StringTokenizer st = new StringTokenizer("String","Split"); //Vector vc = new Vector(); //ArrayList<Integer> al= new ArrayList<Integer>(); //LinkedList<Integer> ll= new LinkedList<Integer>(); //Stack <Integer> stk = new Stack <Integer>(); //Queue <Integer> q = new LinkedList<Integer>(); //ArrayDeque<Integer> ad = new ArrayDeque<Integer>(); //PriorityQueue <Integer> pq = new PriorityQueue<Integer>(); //PriorityQueue <Integer> pqr = new PriorityQueue<Integer>(Comparator.reverseOrder()); //HashSet<Integer> hs = new HashSet<Integer>(); //LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>(); //TreeSet<Integer> ts = new TreeSet<Integer>(); //TreeSet<Integer> tsr = new TreeSet<Integer>(Comparator.reverseOrder()); //HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(); //LinkedHashMap<Integer,Integer> lhm = new LinkedHashMap<Integer,Integer>(); //TreeMap<Integer,Integer> tm = new TreeMap<Integer,Integer>(); //TreeMap<Integer,Integer> tmr = new TreeMap<Integer,Integer>(Comparator.reverseOrder()); //LinkedList<Integer> adj[] = new LinkedList[size]; //=================CODE STARTS FROM HERE==================// long test = 1; test = input.nextLong(); for (long tc = 1; tc <= test; tc++) { int a = input.nextInt(); int b = input.nextInt(); int x = input.nextInt(); int y = input.nextInt(); System.out.println(Math.max(Math.max(x,a-1-x)*b,a*Math.max(y,b-1-y))); } //=====================CODE ENDS HERE=====================// //pw.close(); input.close(); System.exit(0); } public static class Node { Node left, right; int data; public Node(int data) { this.data = data; } } public static Node createTree() { Node root = null; System.out.println("Enter data: "); int data = input.nextInt(); if(data == -1) return null; root = new Node(data); System.out.println("Enter left for " + data); root.left = createTree(); System.out.println("Enter right for "+ data); root.right = createTree(); return root; } public static void inOrder(Node root) { if(root == null) return; inOrder(root.left); System.out.print(root.data+" "); inOrder(root.right); } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } public static long nCr(long n, long r) { return factorial(n) / (factorial(r) * factorial(n - r)); } public static long nPr(long n, long r) { return factorial(n) / factorial(n - r); } public static long countsubstring(String str) { long n = str.length(); return n * (n + 1) / 2; } public static boolean ispalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) { if (str.charAt(i) != str.charAt(j)) return false; i++; j--; } return true; } public static boolean perfectsquare(long x) { if (x >= 0) { long sr = (long)(Math.sqrt(x)); return ((sr * sr) == x); } return false; } public static boolean perfectcube(long N) { int cube; int c = 0; for (int i = 0; i <= N; i++) { cube = i * i * i; if (cube == N) { c=1; break; } else if (cube > N) { c=0 ; break ; } } if (c==1)return true; else return false; } public static int divcount(int n) { boolean hash[] = new boolean[n + 1]; Arrays.fill(hash, true); for (int p = 2; p * p < n; p++) if (hash[p] == true) for (int i = p * 2; i < n; i += p) hash[i] = false; int total = 1; for (int p = 2; p <= n; p++) { if (hash[p]) { int count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total; } public static void printdiv(int n) { for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i) System.out.print(" "+ i); else System.out.print(i+" " + n/i + " " ); } } } public static boolean[] sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } prime[1]=false; return prime; } public static int removeduplicateelements(int arr[], int n){ Arrays.sort(arr); if (n==0 || n==1){ return n; } int[] temp = new int[n]; int j = 0; for (int i=0; i<n-1; i++){ if (arr[i] != arr[i+1]){ temp[j++] = arr[i]; } } temp[j++] = arr[n-1]; for (int i=0; i<j; i++){ arr[i] = temp[i]; } return j; } public static int fibon(int n) { if (n <= 1) { return n; } int[] array = new int[n + 1]; array[0] = 0; array[1] = 1; for (int i = 2; i <= n; i++) { array[i] = array[i - 2] + array[i - 1]; } return array[n]; } public static long sumofdigits(long n) { long sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } public static int reversedigits(int num) { int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } public static int binarysearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarysearch(arr, l, mid - 1, x); return binarysearch(arr, mid + 1, r, x); } return -1; } public static void rangeofprimenumber(int a, int b) { int i, j, flag; for (i = a; i <= b; i++) { if (i == 1 || i == 0) continue; flag = 1; for (j = 2; j <= i / 2; ++j) { if (i % j == 0) { flag = 0; break; } } if (flag == 1) System.out.println(i); } } public static boolean isprime(long n) { if (n <= 1) return false; else if (n == 2) return true; else if (n % 2 == 0) return false; for (long i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } public static long factorial(long n) { return (n == 1 || n == 0) ? 1 : n * factorial(n - 1); } public static int[] reversearrayinrange(int arr[], int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } return arr; } public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
java
1296
D
D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3 7 10 50 12 1 8 OutputCopy5 InputCopy1 1 100 99 100 OutputCopy1 InputCopy7 4 2 1 1 3 5 4 2 7 6 OutputCopy6
[ "greedy", "sortings" ]
/* It's always like another kick for me to make sure I get what I want to get done, because honestly you never know. */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main extends PrintWriter { Main() { super(System.out); } static boolean cases = false; // Solution void solve() { int n = sc.nextInt(); long a = sc.nextLong(); long b = sc.nextLong(); long k = sc.nextLong(); long ar[] = sc.readLongArray(n); long ans = 0; long req = b / a; if (b % a != 0) req++; TreeMap<Long, Integer> map = new TreeMap<>(); for (long i : ar) { long last = i % (a + b); if (last > 0) { if (last <= a) { map.put(0l, map.getOrDefault(0l, 0) + 1); } else { long x = last - a; long r = x / a + (x % a != 0 ? 1 : 0); if (k >= r) { map.put(r, map.getOrDefault(r, 0) + 1); } } } else { if (k >= req) { map.put(req, map.getOrDefault(req, 0) + 1); } } } for (long key : map.keySet()) { for (int i = 0; i < map.get(key) && k >= key; i++) { k -= key; ans++; } } System.out.println(ans); } void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } public static void main(String[] args) { Main obj = new Main(); int c = 1; for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve(); obj.solve(); obj.flush(); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } char[] readCharArray(int n) { char a[] = new char[n]; String s = sc.next(); for (int i = 0; i < n; i++) { a[i] = s.charAt(i); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } final int ima = Integer.MAX_VALUE; final int imi = Integer.MIN_VALUE; final long lma = Long.MAX_VALUE; final long lmi = Long.MIN_VALUE; static final long mod = (long) 1e9 + 7; private static final FastScanner sc = new FastScanner(); private PrintWriter out = new PrintWriter(System.out); }
java
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
import java.util.Scanner; public class CF1809{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int firstArrayLength = scan.nextInt(); int secondArrayLength = scan.nextInt(); scan.nextLine(); // for eating String[] firstArray = scan.nextLine().split(" "); String[] secondArray = scan.nextLine().split(" "); int numberOfQueries = scan.nextInt(); for(int i=0; i<numberOfQueries; i++){ int year = scan.nextInt(); String firstYear; String secondYear; if(year%firstArray.length == 0){ firstYear = firstArray[firstArray.length-1]; }else{ firstYear = firstArray[year%firstArray.length-1]; } if(year%secondArray.length == 0){ secondYear = secondArray[secondArray.length-1]; }else{ secondYear = secondArray[year%secondArray.length-1]; } System.out.println(firstYear+secondYear); } } }
java
1287
B
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3 SET ETS TSE OutputCopy1InputCopy3 4 SETE ETSE TSES OutputCopy0InputCopy5 4 SETT TEST EEET ESTE STES OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES"
[ "brute force", "data structures", "implementation" ]
import jdk.dynalink.beans.StaticClass; import java.util.*; import java.io.*; public class Hyperset { PrintWriter out; StringTokenizer st; BufferedReader br; final int imax = Integer.MAX_VALUE, imin = Integer.MIN_VALUE; final int mod = 1000000007; void solve() throws Exception { int tt = 1; // t = ni(); // n<= 1500, k<= 30 //no of ways to select three cards that form a set. for (int ii = 0; ii < tt; ii++) { int n = ni(), k = ni(); String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = ns(); Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) map.put(arr[i], map.getOrDefault(arr[i], 0)+ 1); long ans= 0l; for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { char[] find= new char[k]; for (int l = 0; l < k; l++) { if(arr[i].charAt(l)== arr[j].charAt(l)) find[l]= arr[i].charAt(l); else find[l]= help(arr[i].charAt(l), arr[j].charAt(l)); } map.put(arr[i], map.get(arr[i])-1); map.put(arr[j], map.get(arr[j])-1); ans+= map.getOrDefault(new String(find), 0); map.put(arr[i], map.get(arr[i])+1); map.put(arr[j], map.get(arr[j])+1); } } out.println(ans/3); } } private char help(char a, char b) { return a!= 'S' && b!= 'S'? 'S': a!= 'E' && b!= 'E'? 'E': 'T'; } public static void main(String[] args) throws Exception { new Hyperset().run(); } void run() throws Exception { if (System.getProperty("ONLINE_JUDGE") == null) { File file = new File("./input.txt"); br = new BufferedReader(new FileReader(file)); out = new PrintWriter("./output.txt"); } else { out = new PrintWriter(System.out); br = new BufferedReader(new InputStreamReader(System.in)); } long ss = System.currentTimeMillis(); st = new StringTokenizer(""); while (true) { try { solve(); } catch (Exception e) { e.printStackTrace(out); } catch (StackOverflowError e) { e.printStackTrace(out); } String s = br.readLine(); if (s == null) break; else st = new StringTokenizer(s); } //out.println(System.currentTimeMillis()-ss+"ms"); out.flush(); } void read() throws Exception { st = new StringTokenizer(br.readLine()); } int ni() throws Exception { if (!st.hasMoreTokens()) read(); return Integer.parseInt(st.nextToken()); } char nc() throws Exception { if (!st.hasMoreTokens()) read(); return st.nextToken().charAt(0); } String nw() throws Exception { if (!st.hasMoreTokens()) read(); return st.nextToken(); } long nl() throws Exception { if (!st.hasMoreTokens()) read(); return Long.parseLong(st.nextToken()); } int[] ni(int n) throws Exception { int[] ret = new int[n]; for (int i = 0; i < n; i++) ret[i] = ni(); return ret; } long[] nl(int n) throws Exception { long[] ret = new long[n]; for (int i = 0; i < n; i++) ret[i] = nl(); return ret; } double nd() throws Exception { if (!st.hasMoreTokens()) read(); return Double.parseDouble(st.nextToken()); } String ns() throws Exception { String s = br.readLine(); return s.length() == 0 ? br.readLine() : s; } void print(int[] arr) { for (int i : arr) out.print(i + " "); out.println(); } void print(long[] arr) { for (long i : arr) out.print(i + " "); out.println(); } void print(int[][] arr) { for (int[] i : arr) { for (int j : i) out.print(j + " "); out.println(); } } void print(long[][] arr) { for (long[] i : arr) { for (long j : i) out.print(j + " "); out.println(); } } long add(long a, long b) { if (a + b >= mod) return (a + b) - mod; else return a + b >= 0 ? a + b : a + b + mod; } long mul(long a, long b) { return (a * b) % mod; } void print(boolean b) { if (b) out.println("YES"); else out.println("NO"); } long binExp(long base, long power) { long res = 1l; while (power != 0) { if ((power & 1) == 1) res = mul(res, base); base = mul(base, base); power >>= 1; } return res; } long gcd(long a, long b) { if (b == 0) return a; else return gcd(b, a % b); } // strictly smaller on left void stack_l(int[] arr, int[] left) { Stack<Integer> stack = new Stack<>(); for (int i = 0; i < arr.length; i++) { while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) stack.pop(); if (stack.isEmpty()) left[i] = -1; else left[i] = stack.peek(); stack.push(i); } } // strictly smaller on right void stack_r(int[] arr, int[] right) { Stack<Integer> stack = new Stack<>(); for (int i = arr.length - 1; i >= 0; i--) { while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) stack.pop(); if (stack.isEmpty()) right[i] = arr.length; else right[i] = stack.peek(); stack.push(i); } } private void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int i : arr) list.add(i); Collections.sort(list); for (int i = 0; i < arr.length; i++) arr[i] = list.get(i); } }
java
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0 2 4 20 OutputCopy3InputCopy1 1 2 3 1 0 15 27 26 OutputCopy2InputCopy1 1 2 3 1 0 2 2 1 OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
import java.util.*; import java.io.*; import static java.lang.Math.*; public class test { final static int MOD = 1000000007; final static int intMax = 1000000000; final static int intMin = -1000000000; final static int[] dx = { 0, 0, -1, 1 }; final static int[] dy = { -1, 1, 0, 0 }; static int add(int a, int b) { return (a + b) % MOD; } static int sub(int a, int b) { return (a - b + MOD) % MOD; } static int mult(int a, int b) { return (int)((((long)(a)) * b) % MOD); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[360]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static class Sb_Output implements Closeable, Flushable{ StringBuilder sb; OutputStream os; int BUFFER_SIZE; public Sb_Output(String s) throws Exception { os = new BufferedOutputStream(new FileOutputStream(new File(s))); BUFFER_SIZE = 1 << 16; sb = new StringBuilder(BUFFER_SIZE); } public void print(String s) { sb.append(s); if(sb.length() >= (BUFFER_SIZE>>1)) { flush(); } } public void println(String s) { print(s); print("\n"); } public void println(int i) { println("" + i); } public void println(long i) { println("" + i); } public void flush() { try { os.write(sb.toString().getBytes()); sb = new StringBuilder(BUFFER_SIZE); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } public static void main(String[] args) throws Exception { Reader in = new Reader(); // Reader in = new Reader("poetry.in"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // BufferedReader br = new BufferedReader(new FileReader("poetry.in")); StringTokenizer st = new StringTokenizer(br.readLine()); long x0 = Long.parseLong(st.nextToken()); long y0 = Long.parseLong(st.nextToken()); long ax = Long.parseLong(st.nextToken()); long ay = Long.parseLong(st.nextToken()); long bx = Long.parseLong(st.nextToken()); long by = Long.parseLong(st.nextToken()); st = new StringTokenizer(br.readLine()); long xs = Long.parseLong(st.nextToken()); long ys = Long.parseLong(st.nextToken()); long t = Long.parseLong(st.nextToken()); ArrayList<pair> points = new ArrayList<pair>(); long curx = x0, cury = y0; points.add(new pair(curx, cury)); while(true){ if(curx > 100000000000000000L / ax || cury > 100000000000000000L / ay) break; curx *= ax; cury *= ay; if(curx > 100000000000000000L - bx || cury > 100000000000000000L - by) break; curx += bx; cury += by; points.add(new pair(curx, cury)); }/* for(pair i : points){ System.out.println(i.x + " " + i.y); }*/ int sz = points.size(); int mx = 0; for(int i = 0; i < sz; ++i) { int cur = 0; long curt = t - Math.abs(xs - points.get(i).x) - Math.abs(ys - points.get(i).y); if(curt < 0) continue; //if(i == 0) System.out.println(curt); ++cur; curx = points.get(i).x; cury = points.get(i).y; for(int j = i - 1; j >= 0 && curt > 0; --j) { if(curt - Math.abs(curx - points.get(j).x) - Math.abs(cury - points.get(j).y) < 0) break; curt -= Math.abs(curx - points.get(j).x) + Math.abs(cury - points.get(j).y); curx = points.get(j).x; cury = points.get(j).y; ++cur; } for(int j = i + 1; j < sz; ++j){ if(curt - Math.abs(curx - points.get(j).x) - Math.abs(cury - points.get(j).y) < 0) break; curt -= Math.abs(curx - points.get(j).x) + Math.abs(cury - points.get(j).y); curx = points.get(j).x; cury = points.get(j).y; ++cur; } //System.out.println(cur); mx = max(mx, cur); } System.out.println(mx); in.close(); //out.close(); } static class pair{ long x, y; pair(long a, long b) { x = a; y = b; } } }
java