F1
stringlengths
8
8
F2
stringlengths
8
8
text_1
stringlengths
607
24.4k
text_2
stringlengths
591
24.4k
label
int64
0
1
7f42483d
c9a316ca
import java.io.*; import java.util.*; public class Main { static final boolean INPUT_FROM_FILE = false; static final String INPUT_FILE = "input/input.txt"; static final String OUTPUT_FILE = "input/output.txt"; static final long M = (long) 1e9 + 7; static FastReader in; static FastWriter out; static { try { in = new FastReader(); out = new FastWriter(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { int t = in.nextInt(); while (t-- > 0) solve(); out.close(); } static long[][] dp; static long dfs(List<List<Integer>> tree, int parent, int current, int parentState, int[][] vRange) { if(dp[current][parentState] != -1) { return dp[current][parentState]; } long left = Math.abs(vRange[current][0] - vRange[parent][parentState]); long right = Math.abs(vRange[current][1] - vRange[parent][parentState]); for(int child : tree.get(current)) { if(child != parent) { left += dfs(tree, current, child, 0, vRange); right += dfs(tree, current, child, 1, vRange); } } dp[current][parentState] = Math.max(left, right); return dp[current][parentState]; } private static void solve() { int n = in.nextInt(); int[][] vRange = new int[n+1][2]; for(int i=1; i<=n; i++) { int l = in.nextInt(), r = in.nextInt(); vRange[i][0] = l; vRange[i][1] = r; } List<List<Integer>> tree = new ArrayList<>(); for(int i=0; i<=n; i++) tree.add(new LinkedList<>()); for(int i=0; i<n-1; i++) { int u = in.nextInt(); int v = in.nextInt(); tree.get(u).add(v); tree.get(v).add(u); } dp = new long[n+1][2]; for(int i=0; i<=n; i++) { Arrays.fill(dp[i], -1); } long left = 0, right = 0; for(int v : tree.get(1)) { left += dfs(tree, 1, v, 0, vRange); right += dfs(tree, 1, v, 1, vRange); } out.println(Math.max(left, right)); } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br; public FastReader() throws FileNotFoundException { if (INPUT_FROM_FILE) { this.stream = new FileInputStream(INPUT_FILE); br = new BufferedReader(new FileReader(INPUT_FILE)); } else { this.stream = System.in; br = new BufferedReader(new InputStreamReader(System.in)); } } 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 String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } 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 long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long 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 double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } static class FastWriter { BufferedWriter writer; StringBuilder sb; public FastWriter() throws IOException { if (INPUT_FROM_FILE) writer = new BufferedWriter(new FileWriter(OUTPUT_FILE)); else writer = new BufferedWriter(new PrintWriter(System.out)); sb = new StringBuilder(); } public void print(Object obj) { sb.append(obj); } public void println(Object obj) { sb.append(obj).append('\n'); } public void close() throws IOException { writer.write(sb.toString()); writer.close(); } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import static javax.swing.UIManager.get; import static javax.swing.UIManager.getString; public class Main { static class Pair implements Comparable<Pair> { int x = 0; int y = 0; public Pair(int x1, int y1) { x = x1; y = y1; } @Override public int compareTo(Pair o) { return this.x - o.x; } } static boolean checkPallindrome(int n) { ArrayList<Integer> list = new ArrayList<>(); while (n > 0) { list.add(n % 10); n /= 10; } int low = 0, high = list.size() - 1; while (low <= high) { if (list.get(low) != list.get(high)) return false; low++; high--; } return true; } static boolean check(String s) { int low = 0, high = s.length() - 1; while (low <= high) { if (s.charAt(low) != s.charAt(high)) return false; low++; high--; } return true; } class Node implements Comparable<Node> { int x = 0, y = 0, z = 0; @Override public int compareTo(Node o) { return this.y - o.y; } } static int min = Integer.MAX_VALUE; public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); //(1)very very important**(never take the first problem for granted, always check the test cases) take 5 minutes more and check the edge cases // 5 minutes will not decreases rating as much as a wrong submission does it is easy u just think with an open mind and u will surely get the answer //(2)let ur brain consume the problem don't just jump to the solution. after reading the problem take a pause 1 minute //(3)go through the example test cases and also at least two of ur own test cases.Think of testcases which are difficult(edge cases).dry run ur concept //(4) sometimes if else condition is not required but due to if else you miss some points and get wrong answer int t = sc.nextInt(); while (t-- > 0) { int n =sc.nextInt(); ArrayList<ArrayList<Integer>> list = new ArrayList<>(); for(int i=0;i<n;i++) list.add(new ArrayList<Integer>()); ArrayList<Pair> list1 = new ArrayList<>(); for(int i=0;i<n;i++) list1.add(new Pair(sc.nextInt(),sc.nextInt())); for(int i=0;i<n-1;i++) { int a =sc.nextInt()-1,b=sc.nextInt()-1; list.get(a).add(b); list.get(b).add(a); } long[][] dp = new long[2][n]; dfs(0,-1,dp,list,list1); System.out.println(Math.max(dp[0][0],dp[1][0])); } } static void dfs(int u,int p,long[][] dp,ArrayList<ArrayList<Integer>> list,ArrayList<Pair> list1) { for(int v:list.get(u)) { if(v==p) continue; dfs(v,u,dp,list,list1); dp[1][u]+= Math.max(Math.abs(list1.get(u).y-list1.get(v).x)+dp[0][v],Math.abs(list1.get(u).y-list1.get(v).y)+dp[1][v]); dp[0][u]+=Math.max(Math.abs(list1.get(u).x-list1.get(v).x)+dp[0][v],Math.abs(list1.get(u).x-list1.get(v).y)+dp[1][v]); } } //static int lcs( int[] X, int[] Y, int m, int n ) //{ // int L[][] = new int[m+1][n+1]; // // /* Following steps build L[m+1][n+1] in bottom up fashion. Note // that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ // for (int i=0; i<=m; i++) // { // for (int j=0; j<=n; j++) // { // if (i == 0 || j == 0) // L[i][j] = 0; // else if (X[i-1] == Y[j-1]) // L[i][j] = L[i-1][j-1] + 1; // else // L[i][j] = Math.max(L[i-1][j], L[i][j-1]); // } // } // return L[m][n]; //} // syntax of conditional operator y=(x==1)?1:0; //Things to check when u r getting wrong answer // 1- check the flow of the code //2- If ur stuck read the problem once again //3- before submitting always check the output format of ur code //4- don't check standings until problem B is done //5- if u r thinking ur concept is correct but still u r getting wrong answer try to implement it in another way //6- By default, java interpret all numeral literals as 32-bit integer values. // If you want to explicitely specify that this is something bigger then 32-bit integer you should use suffix L for long values. example long a = 600851475143L //All the functions long pow(long a,long b,long m) { a%=m; long res=1L; while(b>0) { long temp=b&1; if(temp==1) res=(res*a)%m; a=(a*a)%m; b>>=1; } return res; } static class DisjointUnionSets { int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each void makeSet() { for (int i = 0; i < n; i++) { // Initially, all elements are in // their own set. parent[i] = i; } } // Returns representative of x's set int find(int x) { // Finds the representative of the set // that x is an element of if (parent[x] != x) { // if x is not the parent of itself // Then x is not the representative of // his set, parent[x] = find(parent[x]); // so we recursively call Find on its parent // and move i's node directly under the // representative of this set } return parent[x]; } // Unites the set that includes x and the set // that includes x void union(int x, int y) { // Find representatives of two sets int xRoot = find(x), yRoot = find(y); // Elements are in the same set, no need // to unite anything. if (xRoot == yRoot) return; // If x's rank is less than y's rank if (rank[xRoot] < rank[yRoot]) // Then move x under y so that depth // of tree remains less parent[xRoot] = yRoot; // Else if y's rank is less than x's rank else if (rank[yRoot] < rank[xRoot]) // Then move y under x so that depth of // tree remains less parent[yRoot] = xRoot; else // if ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + 1; } } } static void debug(String s) { System.out.println(s); } //collections.sort use merge sort instead of quick sort but arrays.sort use quicksort whose worst time complexity is O(n^2) static int[] sort(int[] a) { ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<a.length;i++) list.add(a[i]); Collections.sort(list); int ind=0; for(int x:list) a[ind++]=x; return a; } //function to print an array for debugging static void print(int[] a) { for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } static void printc(char[] a) { for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } //normal gcd function, always put the greater number as a and the smaller number as b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static int lcm(int a,int b) { return (a*b)/gcd(a,b); } //to find gcd and lcm for numbers of long data type static long gcdl(long a, long b) { if (b == 0) return a; return gcdl(b, a % b); } static long lcml(long a,long b) { return (a*b)/gcdl(a,b); } //Input Reader to read faster input static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) { int[] a = new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } } }
0
00c0b82a
1ea771ea
import java.util.*; public class E1547 { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int q = sc.nextInt(); for(int i = 0; i < q; i++){ int n = sc.nextInt(); int k = sc.nextInt(); int[][] t = new int[k][2]; for(int j = 0; j < k; j++){ t[j][0] = sc.nextInt();//room } for(int j = 0; j < k; j++){ t[j][1] = sc.nextInt();//air } long[] left = new long[n]; long[] right = new long[n]; long tmp = Integer.MAX_VALUE; long[] max =new long[n]; for(int j = 0; j < n; j++){ max[j] = Integer.MAX_VALUE; } for (int j = 0; j < k; j++) { max[t[j][0]-1] = t[j][1]; } for (int j = 1; j <= n; j++) { tmp = Math.min(tmp+1, max[j-1]); left[j-1] = tmp; } for(int j = n; j >= 1; j--){ tmp = Math.min(tmp+1, max[j-1]); right[j-1] = tmp; } for(int j = 0; j < n; j++){ System.out.print(Math.min(left[j], right[j]) + " "); } System.out.println(); } } }
import java.io.*; import java.util.*; public class CODECHEF { 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(); } String nextLine() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c != 10 && c != 13; c = scan()) { sb.append((char) c); } return sb.toString(); } char nextChar() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; return (char) c; } 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 long MOD=1000000000; static class Pair{ long a; int b; Pair(long i,int j){ a=i; b=j; } } static long[] solve(int[] pos,long[] arr,int n,int k){ long[] ans=new long[n]; long[] left=new long[n]; long[] right=new long[n]; long min=Integer.MAX_VALUE; for(int i=0;i<n;i++){ min=Math.min(min+1,arr[i]); left[i]=min; } min=Integer.MAX_VALUE; for(int i=n-1;i>=0;i--){ min=Math.min(min+1,arr[i]); right[i]=min; } for(int i=0;i<n;i++){ ans[i]=Math.min(left[i],right[i]); } return ans; } public static void main(String[] args) throws java.lang.Exception { FastReader fs=new FastReader(System.in); // StringBuilder sb=new StringBuilder(); // PrintWriter out=new PrintWriter(System.out); int t=fs.nextInt(); while (t-->0){ int n=fs.nextInt(); int k=fs.nextInt(); int[] pos=new int[k]; for(int i=0;i<k;i++) pos[i]=fs.nextInt()-1; long[] temp=new long[n]; int ptr=0; Arrays.fill(temp,Integer.MAX_VALUE); for(int i=0;i<k;i++) temp[pos[ptr++]]=fs.nextLong(); long[] ans=solve(pos,temp,n,k); for(int i=0;i<n;i++) System.out.print(ans[i]+" "); System.out.println(); } //out.close; } }
0
e6a6e318
fadc1365
//package codeforces; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class solution { public static void main(String args[]) throws java.lang.Exception{ FastScanner s=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int t=s.nextInt(); for(int tt=0;tt<t;tt++) { int n=s.nextInt(), k=s.nextInt(); int[] a=s.readArray(k), temp=s.readArray(k); long[] ans=new long[n]; Arrays.fill(ans, Integer.MAX_VALUE); for (int i=0; i<k; i++) { ans[a[i]-1]=temp[i]; } for (int i=1; i<n; i++) { ans[i]=Math.min(ans[i],ans[i-1]+1); } for (int i=n-2; i>=0; i--) { ans[i]=Math.min(ans[i],ans[i+1]+1); } for (int i=0; i<n; i++) { out.print(ans[i]+" "); } out.println(); } out.close(); } 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 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 int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b); } static void sortcol(int a[][],int c) { Arrays.sort(a, (x, y) -> { if(x[c]>y[c]) { return 1; }else { return -1; } }); } public static void printb(boolean ans) { if(ans) { System.out.println("Yes"); }else { System.out.println("No"); } } 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(); } double nextDouble() { return Double.parseDouble(next()); } 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()); } } static class Pair implements Comparable<Pair>{ int a , b; Pair(int x , int y){ a=x; b=y; } public int compareTo(Pair o) { return a != o.a ? a - o.a : b - o.b; } } }
import java.io.PrintWriter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class a{ public static void main(String args[]) throws java.lang.Exception{ FastScanner s=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int t=s.nextInt(); for(int tt=0;tt<t;tt++) { int n=s.nextInt(),k=s.nextInt(); int pos[]=s.readArray(k); int temp[]=s.readArray(k); long ans[]=new long[n]; Arrays.fill(ans,Integer.MAX_VALUE); for(int i=0;i<k;i++){ ans[pos[i]-1]=temp[i]; } for(int i=1;i<n;i++){ ans[i]=Math.min(ans[i-1]+1,ans[i]); } for(int i=n-2;i>=0;i--){ ans[i]=Math.min(ans[i],ans[i+1]+1); } for(int i=0;i<n;i++){ out.print(ans[i]+" "); } out.println(); } out.close(); } static boolean isPrime(int n){ if (n <= 1) return false; else if (n == 2) return true; else if (n % 2 == 0) return false; for (int i = 3; i <= Math.sqrt(n); i += 2){ if (n % i == 0) return false; } return true; } static 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 sort(char [] a) { ArrayList<Character> l=new ArrayList<>(); for (char i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } 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 int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b); } static void sortcol(int a[][],int c) { Arrays.sort(a, (x, y) -> { if(x[c]>y[c]) { return 1; }else { return -1; } }); } public static void printb(boolean ans) { if(ans) { System.out.println("Yes"); }else { System.out.println("No"); } } 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(); } double nextDouble() { return Double.parseDouble(next()); } 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()); } } static class Pair implements Comparable<Pair>{ int a , b; Pair(int x , int y){ a=x; b=y; } public int compareTo(Pair o) { return a != o.a ? a - o.a : b - o.b; } } }
1
4552d8a0
ec4c7e8e
import java.util.*; import java.io.*; ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** public class D_Blue_Red_Permutation{ public static void main(String[] args) { FastScanner s= new FastScanner(); // PrintWriter out=new PrintWriter(System.out); //end of program //out.println(answer); //out.close(); StringBuilder res = new StringBuilder(); int t=s.nextInt(); int p=0; while(p<t){ int n=s.nextInt(); long array[]= new long[n]; for(int i=0;i<n;i++){ array[i]=s.nextLong(); } String str=s.nextToken(); ArrayList<Long> red = new ArrayList<Long>(); ArrayList<Long> blue = new ArrayList<Long>(); for(int i=0;i<n;i++){ if(str.charAt(i)=='R'){ red.add(array[i]); } else{ blue.add(array[i]); } } Collections.sort(blue); int check1=0; for(int i=0;i<blue.size();i++){ int yo=i+1; if(blue.get(i)<yo){ check1=1; break; } } Collections.sort(red,Collections.reverseOrder()); int number=n; int check2=0; for(int i=0;i<red.size();i++){ if(red.get(i)>number){ check2=1; break; } number--; } if(check1==0 && check2==0){ res.append("YES\n"); } else{ res.append("NO\n"); } p++; } System.out.println(res); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { 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(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
import java.util.*; public class the_child_and_set { public static void main(String args[]) { Scanner in=new Scanner(System.in); int t=in.nextInt(); in.nextLine(); while(t--!=0) { int n=in.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=in.nextInt(); } in.nextLine(); String s=in.nextLine(); int rc=0; int bc=0; for(int i=0;i<n;i++) { if(s.charAt(i)=='B') bc++; else rc++; } int r[]=new int[rc]; int b[]=new int[bc]; int bi=0; int ri=0; for(int i=0;i<n;i++) { if(s.charAt(i)=='B') { b[bi]=arr[i]; bi++; } else { r[ri]=arr[i]; ri++; } } Arrays.sort(b); Arrays.sort(r); boolean flag=true; for(int i=0;i<bi;i++) { if(b[i]<(i+1)) { flag=false; break; } } if(flag) { for(int i=0;i<ri;i++) { if(r[i]>bi+(i+1)) { flag=false; break; } } } if(flag) System.out.println("YES"); else System.out.println("NO"); } } }
0
1410e423
da5cf40b
import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int t = Integer.parseInt(br.readLine()); while(t --> 0) { int n = Integer.parseInt(br.readLine()); char[] lineA = br.readLine().toCharArray(); char[] lineB = br.readLine().toCharArray(); boolean[] a = new boolean[n]; boolean[] b = new boolean[n]; int ac = 0; int aic = 0; int bc = 0; int stay = 0; int flip = 0; for(int i = 0; i < n; i++) { if(lineA[i] == '1') { ac++; a[i] = true; }else aic++; if(lineB[i] == '1') { bc++; b[i] = true; } if(a[i] == b[i]) stay++; else flip++; } if(ac != bc && aic + 1 != bc) { pw.println(-1); }else { if(ac == aic+1) pw.println(Math.min(stay, flip)); else if(ac == bc) pw.println(flip); else pw.println(stay); } } pw.close(); } }
/***** ---> :) Vijender Srivastava (: <--- *****/ import java.util.*; import java.lang.*; import java.io.*; public class Main { static FastReader sc =new FastReader(); static PrintWriter out=new PrintWriter(System.out); static long mod=(long)1e9+7; /* start */ public static void main(String [] args) { // int testcases = 1; int testcases = i(); while(testcases-->0) { solve(); } out.flush(); out.close(); } static void solve() { int n = i(); char c[] = inputC(); char d[] = inputC(); int x01=0,x10=0,x00=0,x11=0; for(int i=0;i<n;i++) { if(c[i]=='0'&&d[i]=='0')x00++; if(c[i]=='0'&&d[i]=='1')x01++; if(c[i]=='1'&&d[i]=='0')x10++; if(c[i]=='1'&&d[i]=='1')x11++; } int ans = Integer.MAX_VALUE; if(x01==0 && x10==0) { pl(0); return ; } if(x11==x00+1) { ans = min(x11+x00,ans); } if(x01==x10) { ans = min(x01+x10,ans); } if(ans == Integer.MAX_VALUE){ ans = -1; } pl(ans); } /* end */ 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 void p(Object o) { out.print(o); } static void pl(Object o) { out.println(o); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static char[] inputC() { String s = sc.nextLine(); return s.toCharArray(); } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static long[] putL(long a[]) { long A[]=new long[a.length]; for(int i=0;i<a.length;i++) { A[i]=a[i]; } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static String reverse(String s) { StringBuffer p=new StringBuffer(s); p.reverse(); return p.toString(); } static int min(int a,int b) { return Math.min(a, b); } static int min(int a,int b,int c) { return Math.min(a, Math.min(b, c)); } static int min(int a,int b,int c,int d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static int max(int a,int b) { return Math.max(a, b); } static int max(int a,int b,int c) { return Math.max(a, Math.max(b, c)); } static int max(int a,int b,int c,int d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long min(long a,long b) { return Math.min(a, b); } static long min(long a,long b,long c) { return Math.min(a, Math.min(b, c)); } static long min(long a,long b,long c,long d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static long max(long a,long b) { return Math.max(a, b); } static long max(long a,long b,long c) { return Math.max(a, Math.max(b, c)); } static long max(long a,long b,long c,long d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long sum(int A[]) { long sum=0; for(int i : A) { sum+=i; } return sum; } static long sum(long A[]) { long sum=0; for(long i : A) { sum+=i; } return sum; } static void print(int A[]) { for(int i : A) { System.out.print(i+" "); } System.out.println(); } static void print(long A[]) { for(long i : A) { System.out.print(i+" "); } System.out.println(); } static long mod(long x) { return ((x%mod + mod)%mod); } static long power(long x, long y) { if(y==0) return 1; if(x==0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x) ; y = y >> 1; x = (x * x); } return res; } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean prime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long[] sort(long a[]) { ArrayList<Long> arr = new ArrayList<>(); for(long i : a) { arr.add(i); } Collections.sort(arr); for(int i = 0; i < arr.size(); i++) { a[i] = arr.get(i); } return a; } static int[] sort(int a[]) { ArrayList<Integer> arr = new ArrayList<>(); for(Integer i : a) { arr.add(i); } Collections.sort(arr); for(int i = 0; i < arr.size(); i++) { a[i] = arr.get(i); } return a; } //pair class private static class Pair implements Comparable<Pair> { long first, second; public Pair(long f, long s) { first = f; second = s; } @Override public int compareTo(Pair p) { if (first > p.first) return 1; else if (first < p.first) return -1; else { if (second > p.second) return 1; else if (second < p.second) return -1; else return 0; } } } }
0
1c8bb204
7d7cf9a7
import javax.print.DocFlavor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class BST { static class pair implements Comparable{ int high; int idx; pair(int x , int y){ high = x; idx = y; } public String toString(){ return high + " " + idx; } @Override public int compareTo(Object o) { pair p = (pair)o; return high-p.high; } } 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){ int n = Integer.parseInt(br.readLine()); long [] arr = new long[n]; StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { long tmp = Long.parseLong(st.nextToken()); arr[i] = tmp; } int h = 1; int v = 1; long minHor = arr[0]; long minVir = arr[1]; long sum0 = arr[0]; long sum1 = arr[1]; long total = (arr[0] + arr[1])*n; for (int i = 2; i < n; i++) { if(i%2==0){ h++; sum0 += arr[i]; minHor = Math.min(arr[i] , minHor); total = Math.min(total , minHor*(n-h+1)+(sum0-minHor)+minVir*(n-v+1)+(sum1-minVir)); }else { v++; sum1 += arr[i]; minVir = Math.min(arr[i] , minVir); total = Math.min(total , minHor*(n-h+1)+(sum0-minHor)+minVir*(n-v+1)+(sum1-minVir)); } } System.out.println(total); } } }
import java.util.*; import java.io.*; import java.math.*; public class Coder { static int n; static long c[]; static StringBuilder str = new StringBuilder(""); static void solve() { long mne=c[0]; long mno=c[1]; long ans=(c[0]+c[1])*n; long se=c[0]; long so=c[1]; long ecnt=1,ocnt=1; for(int i=2;i<n;i++){ if(i%2==0){mne=Math.min(mne, c[i]);se+=c[i];ecnt++;} else{mno=Math.min(mno, c[i]);so+=c[i];ocnt++;} ans=Math.min(ans, se+mne*(n-ecnt)+so+mno*(n-ocnt)); } str.append(ans).append("\n"); } public static void main(String[] args) throws java.lang.Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int q = Integer.parseInt(bf.readLine().trim()); while(q-->0) { n=Integer.parseInt(bf.readLine().trim()); c=new long[n]; String s[]=bf.readLine().trim().split("\\s+"); for(int i=0;i<n;i++) c[i]=Long.parseLong(s[i]); solve(); } System.out.print(str); } }
0
6b83b22e
c59194c7
import java.util.Scanner; public class Subsequence { private static Scanner sc = new Scanner(System.in); public static void main(String args[]) { int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int a[] = new int[n]; int b[] = new int[n]; for(int i=0;i<n;i++) { a[i]= sc.nextInt(); } if(n%2==0) { calculateB(a,b,n); } else { calculateB(a,b,n-3); if (a[n - 2] + a[n - 3] != 0) { b[n - 3] = -a[n - 1]; b[n - 2] = -a[n - 1]; b[n - 1] = a[n - 2] + a[n - 3]; } else if (a[n - 2] + a[n - 1] != 0) { b[n - 3] = a[n - 2] + a[n - 1]; b[n - 2] = -a[n - 3]; b[n - 1] = -a[n - 3]; } else { b[n - 3] = -a[n - 2]; b[n - 2] = a[n - 3] + a[n - 1]; b[n - 1] = -a[n - 2]; } } for(int i=0;i<n;i++) { System.out.print(b[i] + " "); } System.out.println(); } } private static void calculateB(int[] a, int[] b, int n) { for(int i=0;i<n-1;i=i+2) { b[i] = -a[i+1]; b[i+1] = a[i]; } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; public class codeforcesB{ 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; } } public static void main(String args[]){ FastReader sc=new FastReader(); StringBuilder sb=new StringBuilder(); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int ar[]=new int[n]; int sum=0; for(int i=0;i<n;i++){ar[i]=sc.nextInt();} if(n%2==0){ for(int i=0;i<n;i++){ if(i%2==0){sb.append(-1*ar[i+1]+" ");} else{sb.append(ar[i-1]+" ");} } } else{ if(ar[1]+ar[0]!=0){ sb.append(ar[2]+" "+ar[2]+" "+-1*(ar[1]+ar[0])+" ");} else{ if(ar[2]+ar[1]!=0){ sb.append(-1*(ar[2]+ar[1])+" "+ar[0]+" "+ar[0]+" "); } else{ sb.append(ar[1]+" "+-1*(ar[2]+ar[0])+" "+ar[1]+" "); } } for(int i=3;i<n;i++){ if(i%2==1){sb.append(-1*ar[i+1]+" ");} else{sb.append(ar[i-1]+" ");} } } sb.append("\n"); } System.out.print(sb.toString()); } }
0
2b2d3b84
aaccc000
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; 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.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader in = new FastReader(); int t=in.nextInt(); while(t-->0) { int n=in.nextInt(); int k=in.nextInt(); int a[]=new int[k]; int ans[]=new int[n]; int tem[]=new int[k]; for(int i=0;i<k;i++) a[i]=in.nextInt(); for(int i=0;i<k;i++) tem[i]=in.nextInt(); long c[]=new long[n]; long l[]=new long[n]; long r[]=new long[n]; Arrays.fill(c,Integer.MAX_VALUE); Arrays.fill(l, Integer.MAX_VALUE); Arrays.fill(r,Integer.MAX_VALUE); long p=Integer.MAX_VALUE; for(int i=0;i<k;i++) c[a[i]-1]=tem[i]; for(int i=0;i<n;i++) { p=Math.min(p+1,c[i]); l[i]=p; } p=Integer.MAX_VALUE; for(int i=n-1;i>=0;i--) { p=Math.min(p+1,c[i]); r[i]=p; } for(int i=0;i<n;i++) System.out.print(Math.min(l[i],r[i])+" "); System.out.println(); } } }
import java.io.*; import java.util.*; public class GFG { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); int k = sc.nextInt(); int[] a = new int[k]; int[] temp = new int[k]; for(int i=0;i<k;i++){ a[i] = sc.nextInt(); } for(int i=0;i<k;i++){ temp[i] = sc.nextInt(); } long[] c = new long[n]; Arrays.fill(c,Integer.MAX_VALUE); for(int i=0;i<k;i++){ c[a[i]-1] = temp[i]; } long p = Integer.MAX_VALUE; long[] left = new long[n]; for(int i=0;i<n;i++){ p = (p+1<c[i])?p+1:c[i]; left[i] = p; } p = Integer.MAX_VALUE; long[] right = new long[n]; for(int i=n-1;i>=0;i--){ p = (p+1<c[i])?p+1:c[i]; right[i] = p; } for(int i=0;i<n;i++){ long kl = (left[i]>right[i])?right[i]:left[i]; System.out.print(kl+" "); } System.out.println(); } } }
1
968c1e7e
a4e1511a
import java.util.*; import java.io.*; public class E_Air_Conditioners{ public static void main(String[] args) { FastScanner s= new FastScanner(); StringBuilder res = new StringBuilder(); int t=s.nextInt(); int p=0; while(p<t){ int n=s.nextInt(); int k=s.nextInt(); int pos[]= new int[k]; int temp[]= new int[k]; int min=Integer.MAX_VALUE; int ans[]= new int[n]; HashMap<Integer,ArrayList<Integer>> map = new HashMap<Integer,ArrayList<Integer>>(); HashMap<Integer,Integer> count1 = new HashMap<Integer,Integer> (); for(int i=0;i<k;i++){ pos[i]=s.nextInt(); } for(int i=0;i<k;i++){ temp[i]=s.nextInt(); ans[pos[i]-1]=temp[i]; min=Math.min(temp[i],min); if(map.containsKey(temp[i])){ map.get(temp[i]).add(pos[i]-1); int a=count1.get(temp[i]); a++; count1.remove(temp[i]); count1.put(temp[i],a); } else{ ArrayList<Integer> obj = new ArrayList<Integer>(); obj.add(pos[i]-1); map.put(temp[i],obj); count1.put(temp[i],1); } } int num=min; while(true){ if(!map.containsKey(num)){ break; } ArrayList<Integer> obj2 = map.get(num); for(int i=0;i<obj2.size();i++){ int index=obj2.get(i); if(ans[index]!=0){ if(ans[index]<num){ if(index+1<n && (ans[index+1]>(num+1)|| ans[index+1]==0)){ ans[index+1]=num+1; if(map.containsKey(num+1)){ map.get(num+1).add(index+1); } else{ ArrayList<Integer> object = new ArrayList<Integer>(); object.add(index+1); map.put(num+1,object); } } if(index-1>=0 && (ans[index-1]>(num+1)|| ans[index-1]==0)){ ans[index-1]=num+1; if(map.containsKey(num+1)){ map.get(num+1).add(index-1); } else{ ArrayList<Integer> object = new ArrayList<Integer>(); object.add(index-1); map.put(num+1,object); } } } else if(ans[index]==num){ if(index+1<n && (ans[index+1]>(num+1)|| ans[index+1]==0)){ ans[index+1]=num+1; if(map.containsKey(num+1)){ map.get(num+1).add(index+1); } else{ ArrayList<Integer> object = new ArrayList<Integer>(); object.add(index+1); map.put(num+1,object); } } if(index-1>=0 && (ans[index-1]>(num+1)|| ans[index-1]==0)){ ans[index-1]=num+1; if(map.containsKey(num+1)){ map.get(num+1).add(index-1); } else{ ArrayList<Integer> object = new ArrayList<Integer>(); object.add(index-1); map.put(num+1,object); } } } } } num++; } for(int i=0;i<ans.length;i++){ res.append(ans[i]+" "); } res.append("\n"); p++; } System.out.println(res); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { 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(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
//package Practice; import java.io.*; import java.util.*; public class codefor { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc=new FastReader(); int T=sc.nextInt(); while(T-->0) { int n=sc.nextInt(),k=sc.nextInt(),i=0; long t[]=new long[n]; int a[]=new int[k]; for(i=0;i<k;i++) a[i]=sc.nextInt()-1; for(i=0;i<k;i++) t[a[i]]=sc.nextLong(); long ans[]=new long[n]; PriorityQueue<Long> pq=new PriorityQueue<>(); for(i=0;i<n;i++) { if(t[i]!=0) pq.add(t[i]-i); if(pq.size()!=0) { ans[i]=pq.peek()+i; } } pq.clear(); for(i=n-1;i>=0;i--) { if(t[i]!=0) pq.add(t[i]+i); if(pq.size()!=0) { long val=pq.peek()-i; if(ans[i]==0) ans[i]=val; else ans[i]=Math.min(val, ans[i]); } } pq.clear(); for(i=0;i<n;i++) System.out.print(ans[i]+" "); System.out.println(); } } }
0
d5dc6626
f59d9b6e
import java.util.*; import java.io.*; public class Main { // For fast input output static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { try { br = new BufferedReader( new FileReader("input.txt")); PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out); } catch (Exception e) { 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; } } // end of fast i/o code public static void main(String[] args) { FastReader reader = new FastReader(); StringBuilder sb = new StringBuilder(""); int t = reader.nextInt(); int ans = 0; while (t-- > 0) { int n = reader.nextInt(); int nodes[] = new int[n]; int edges[][] = new int[n-1][2]; ArrayList<Pair> graph[] = new ArrayList[n]; for(int i=0; i<n; i++){ graph[i] = new ArrayList<>(); } for(int i=0; i<n-1; i++){ int a = reader.nextInt()-1; int b = reader.nextInt()-1; graph[a].add(new Pair(b, i)); graph[b].add(new Pair(a, i)); nodes[a]++; nodes[b]++; } boolean possible = true; for(int i=0; i<n; i++){ if(nodes[i]>2){ possible = false; } } Arrays.fill(nodes, 0); int first = 2; int second = 5; if(possible){ int fill_ans[] = new int[n-1]; find(0, -1, graph, fill_ans, n, first, second, true); for(int i=0; i<n-1; i++){ sb.append(fill_ans[i]+" "); } }else{ sb.append("-1"); } sb.append("\n"); } System.out.println(sb); } static void find(int node, int par, ArrayList<Pair> graph[], int fill_ans[], int n, int first, int second, boolean first_fill){ for(Pair p: graph[node]){ if(p.a==par){ continue; } if(first_fill){ fill_ans[p.b] = first; }else{ fill_ans[p.b] = second; } find(p.a, node, graph, fill_ans, n, first, second, !first_fill); first_fill = !first_fill; } } static class Pair{ int a, b; Pair(int x, int y){ a = x; b = y; } } }
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef{ public static class Edge{ int node; int index; Edge(int node, int index){ this.node = node; this.index = index; } } static Scanner scn = new Scanner(System.in); public static void main (String[] args) throws java.lang.Exception{ int t = scn.nextInt(); while(t-->0){ solve(); } } public static void solve(){ int n = scn.nextInt(); ArrayList<Edge>[]graph = new ArrayList[n]; for(int i = 0; i < n; i++){ graph[i] = new ArrayList<>(); } for(int i = 0; i < n - 1; i++){ int u = scn.nextInt() - 1; int v = scn.nextInt() - 1; graph[u].add(new Edge(v, i)); graph[v].add(new Edge(u, i)); } int start = 0; for(int i = 0; i < n; i++){ if(graph[i].size() > 2){ System.out.println("-1"); return; }else if(graph[i].size() == 1){ start = i; } } int[]weight = new int[n - 1]; int prevNode = -1, curNode = start, curWeight = 2; while(true){ ArrayList<Edge>edges = graph[curNode]; Edge next = edges.get(0); if(next.node == prevNode){ if(edges.size() == 1){ break; }else{ next = edges.get(1); } } weight[next.index] = curWeight; prevNode = curNode; curNode = next.node; curWeight = 5 - curWeight; } for(int i = 0; i < n - 1; i++){ System.out.print(weight[i]); System.out.print(" "); } System.out.println(); } }
0
4e9c4bf9
f9e08a46
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class E1525D { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int[] arr = new int[n]; ArrayList<Integer> occupied = new ArrayList<>(); for (int i = 0; i < n; i++) { arr[i] = scn.nextInt(); if (arr[i] == 1) occupied.add(i); } int[][] dp = new int[n + 1][occupied.size() + 1]; for (int[] row : dp) Arrays.fill(row, (int) 1e9); dp[0][0] = 0; for (int i = 1; i <= n; i++) { dp[i][0] = 0; for (int j = 1; j <= occupied.size(); j++) { dp[i][j] = dp[i - 1][j]; if (arr[i - 1] == 0) dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + Math.abs(i - 1 - occupied.get(j - 1))); } } System.out.println(dp[n][occupied.size()]); } }
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Armchair { public static void main(String args[]){ Scanner in=new Scanner(System.in); int n=in.nextInt(); int arr[]=new int[n]; ArrayList<Integer> list1=new ArrayList<Integer>(); ArrayList<Integer> list2=new ArrayList<Integer>(); for(int i=0;i<n;i++) { int a=in.nextInt(); if(a==0) list2.add(i); else list1.add(i); } long dp[][]=new long[list1.size()+1][list2.size()+1]; solve(list1,list2,dp); System.out.println(dp[list1.size()][list2.size()]); } public static void solve( ArrayList<Integer> list1,ArrayList<Integer> list2,long dp[][]){ for(int i=1;i<=list1.size();i++) dp[i][0]=Integer.MAX_VALUE; for(int i=1;i<=list1.size();i++){ for(int j=1;j<=list2.size();j++){ dp[i][j]=Math.min(Math.abs(list1.get(i-1)-list2.get(j-1))+dp[i-1][j-1],dp[i][j-1]); } } } }
0
80881cae
f8e7b886
//package Codeforces; import java.io.*; import java.util.*; public class CP { static Scanner sc=new Scanner(System.in); public static void main(String[] args) throws IOException, CloneNotSupportedException { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int k[]=new int[n]; int h[]=new int[n]; for(int i=0;i<n;i++) k[i]=sc.nextInt(); for(int i=0;i<n;i++) h[i]=sc.nextInt(); ArrayList<Pair> interval=new ArrayList<Pair>(); ArrayList<Pair> act=new ArrayList<Pair>(); for(int i=0;i<n;i++) interval.add(new Pair(k[i]-h[i]+1,k[i])); Collections.sort(interval); // out.println(interval); act.add(interval.get(0).clone()); for(int i=1;i<n;i++) { Pair p=act.get(act.size()-1); if(p.y<interval.get(i).x) act.add(interval.get(i).clone()); else p.y=Math.max(p.y, interval.get(i).y); } // out.println(act); long mana=0; for(Pair p: act) { long x=p.y-p.x+1; mana+=(x*(x+1))/2; } System.out.println(mana); } } static class Pair implements Cloneable, Comparable<Pair> { int x,y; Pair(int a,int b) { this.x=a; this.y=b; } // @Override // public boolean equals(Object obj) // { // if(obj instanceof Pair) // { // Pair p=(Pair)obj; // return p.x==this.x && p.y==this.y; // } // return false; // } // @Override // public int hashCode() // { // return Math.abs(x)+500*Math.abs(y); // } // @Override // public String toString() // { // return "("+x+" "+y+")"; // } @Override protected Pair clone() throws CloneNotSupportedException { return new Pair(this.x,this.y); } @Override public int compareTo(Pair a) { long t=(this.x-a.x); if(t!=0) return t>0?1:-1; else return (int)(this.y-a.y); } // public void swap() // { // this.y=this.y+this.x; // this.x=this.y-this.x; // this.y=this.y-this.x; // } } }
import java.util.*; import java.io.*; import java.time.*; import static java.lang.Math.*; @SuppressWarnings("unused") public class C { static boolean DEBUG = false; static Reader fs; static PrintWriter pw; static void solve() { int n = fs.nextInt(), k[] = fs.readArray(n), h[] = fs.readArray(n); int prev_h = h[0], prev_k = k[0]; // int ans = 0; ArrayList<pair> intervals = new ArrayList<>(); for (int i = 0; i < n; i++) { int start = k[i] - h[i] + 1; int end = k[i]; intervals.add(new pair(start, end)); } // pw.println(intervals); Collections.sort(intervals); ArrayList<pair> merged = new ArrayList<>(); merge(intervals, merged); long ans = 0; for(int i = 0 ; i < merged.size() ; i++) { ans += sum(merged.get(i).len()); } pw.println(ans); } static void merge(ArrayList<pair>a1, ArrayList<pair>a2) { int n = a1.size(); int index = 0; for(int i =1 ; i < n ; i++) { if(a1.get(index).s >= a1.get(i).f) { a1.get(index).s = max(a1.get(index).s, a1.get(i).s); } else { index++; a1.set(index, a1.get(i)); } } for(int i = 0 ; i <= index ; i++) { a2.add(a1.get(i)); } // pw.println(a1); } // int index = 0; // Stores index of last element // // in output array (modified arr[]) // // // Traverse all input Intervals // for (int i=1; i<arr.length; i++) // { // // If this is not first Interval and overlaps // // with the previous one // if (arr[index].end >= arr[i].start) // { // // Merge previous and current Intervals // arr[index].end = Math.max(arr[index].end, arr[i].end); // } // else { // index++; // arr[index] = arr[i]; // } // } static boolean overlapping(pair p1, pair p2) { if((p2.f >= p1.f && p1.s >= p2.f) || (p2.s >= p1.f && p1.s >= p2.s)) { return true; } return false; } static pair merge(pair p1, pair p2) { return new pair(min(p1.f, p2.f), max(p1.s, p2.s)); } static long sum(long n) { return (n * (n + 1) / 2); } static class pair implements Comparable<pair>{ int f, s; pair(int f, int s) { this.f = f; this.s = s; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{" + f + "," + s + "}"); return sb.toString(); } @Override public int compareTo(pair o) { return f - o.f; } public int len() { return s - f + 1; } } public static void main(String[] args) throws IOException { Instant start = Instant.now(); if (args.length == 2) { System.setIn(new FileInputStream(new File("D:\\program\\javaCPEclipse\\CodeForces\\src\\input.txt"))); // System.setOut(new PrintStream(new File("output.txt"))); System.setErr(new PrintStream(new File("D:\\program\\javaCPEclipse\\CodeForces\\src\\error.txt"))); DEBUG = true; } fs = new Reader(); pw = new PrintWriter(System.out); int t = fs.nextInt(); while (t-- > 0) { solve(); } Instant end = Instant.now(); if (DEBUG) { pw.println(Duration.between(start, end)); } pw.close(); } static void sort(int a[]) { ArrayList<Integer> l = new ArrayList<Integer>(); for (int x : a) l.add(x); Collections.sort(l); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } } public static void print(long a, long b, long c, PrintWriter pw) { pw.println(a + " " + b + " " + c); return; } static class Reader { BufferedReader br; StringTokenizer st; public Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[][] read2Array(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; } } }
0
354d060f
e1c4f3db
import java.util.*; import java.io.*; public class CodeForces { // For fast input output static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { try { br = new BufferedReader( new FileReader("input.txt")); PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out); } catch (Exception e) { 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; } } // end of fast i/o code public static void main(String[] args) { FastReader in = new FastReader(); OutputStream op = System.out; PrintWriter out = new PrintWriter(op); int t = in.nextInt(); for (int i = 1; i <= t; i++) { int n=in.nextInt(); int arr[]=new int[n]; for(int j = 0; j < n; j++) arr[j]=in.nextInt(); helper(n,arr,out); out.println(); } out.close(); } public static void helper(int n,int arr[],PrintWriter o) { int max=Integer.MIN_VALUE; for(int i=2;i<n;i++) max=Math.max(max,arr[i]); int ans=1,low=1,high=max; while(low<=high) { int mid=low+(high-low)/2; if(canFit(mid,arr)) { ans=mid; low=mid+1; } else high=mid-1; } o.print(ans); } static boolean canFit(int mid,int arr[]) { int copy[]=Arrays.copyOf(arr, arr.length); for(int i=arr.length-1;i>=0;i--) { if(copy[i]<mid) return false; int min=Math.min(copy[i]-mid,arr[i])/3; if(i>=2){ copy[i-1]+=min; copy[i-2]+=2*min; }} return true; } }
import java.util.*; public class BalancedStoneHeaps { public static boolean check(int n, int x, int[] h) { int[] c_h = new int[n]; for (int i = 0; i < n; i++) c_h[i] = h[i]; for (int i = n - 1; i >= 2; i--) { if (c_h[i] < x) return false; int d = Math.min(h[i], c_h[i] - x) / 3; c_h[i - 1] += d; c_h[i - 2] += 2 * d; } return c_h[0] >= x && c_h[1] >= x; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] h = new int[n]; int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { h[i] = sc.nextInt(); if (h[i] > max) { max = h[i]; } } int l = 0; int r = max; while (l < r) { int mid = l + (r - l + 1) / 2; if (check(n, mid, h)) { l = mid; } else { r = mid - 1; } } System.out.println(l); } } }
0
6825260d
c972dd00
import java.awt.Container; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class Main { public static int check(String a,String b) { int zero1 = 0,one0 = 0; for (int i = 0; i <a.length(); i++) { if(a.charAt(i)=='1'&&a.charAt(i)!=b.charAt(i)) { one0++; } else if(a.charAt(i)=='0'&&a.charAt(i)!=b.charAt(i)) { zero1++; } } if(zero1!=one0) { return -1; } else return zero1+one0; } public static int changeandAns(String a ,String b,int index) { char newa[] = new char[a.length()]; for (int i = 0; i <a.length(); i++) { if(i!=index) { if(a.charAt(i)=='0') { newa[i]='1'; } else { newa[i]= '0'; } } else { newa[i]= a.charAt(i); } } String ra = new String(newa); return check(ra, b); } public static void main(String[] args) { FastScanner input = new FastScanner(); int tc = input.nextInt(); StringBuilder result = new StringBuilder(); work: while (tc-- > 0) { int n = input.nextInt(); String a = input.next(); String b = input.next(); int ans = Integer.MAX_VALUE; //no changes int noChange = check(a,b); if(noChange!=-1) { ans = Math.min(ans, noChange); } //1 - 1 boolean have = false; int index = -1; for (int i = 0; i <n; i++) { if(a.charAt(i)=='1'&&b.charAt(i)==a.charAt(i)) { have = true; index = i; break; } } if(have) { int onetone = changeandAns(a,b,index); if(onetone!=-1) { ans = Math.min(ans,1+ onetone); } } //1-0 have = false; index = -1; for (int i = 0; i <n; i++) { if(a.charAt(i)=='1'&&b.charAt(i)!=a.charAt(i)) { have = true; index = i; break; } } if(have) { int onetozero = changeandAns(a,b,index); if(onetozero!=-1) { ans = Math.min(ans, 1+onetozero); } } if(ans==Integer.MAX_VALUE) { result.append("-1\n"); } else { result.append(ans+"\n"); } } System.out.println(result); } 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) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
import java.awt.Container; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class Main { public static int check(String a,String b) { int zero1 = 0,one0 = 0; for (int i = 0; i <a.length(); i++) { if(a.charAt(i)=='1'&&a.charAt(i)!=b.charAt(i)) { one0++; } else if(a.charAt(i)=='0'&&a.charAt(i)!=b.charAt(i)) { zero1++; } } if(zero1!=one0) { return -1; } else return zero1+one0; } public static int changeandAns(String a ,String b,int index) { char newa[] = new char[a.length()]; for (int i = 0; i <a.length(); i++) { if(i!=index) { if(a.charAt(i)=='0') { newa[i]='1'; } else { newa[i]= '0'; } } else { newa[i]= a.charAt(i); } } String ra = new String(newa); return check(ra, b); } public static void main(String[] args) { FastScanner input = new FastScanner(); int tc = input.nextInt(); StringBuilder result = new StringBuilder(); work: while (tc-- > 0) { int n = input.nextInt(); String a = input.next(); String b = input.next(); int ans = Integer.MAX_VALUE; //no changes int noChange = check(a,b); if(noChange!=-1) { ans = Math.min(ans, noChange); } //1 - 1 boolean have = false; int index = -1; for (int i = 0; i <n; i++) { if(a.charAt(i)=='1'&&b.charAt(i)==a.charAt(i)) { have = true; index = i; break; } } if(have) { int onetone = changeandAns(a,b,index); if(onetone!=-1) { ans = Math.min(ans,1+ onetone); } } //1-0 have = false; index = -1; for (int i = 0; i <n; i++) { if(a.charAt(i)=='1'&&b.charAt(i)!=a.charAt(i)) { have = true; index = i; break; } } if(have) { int onetozero = changeandAns(a,b,index); if(onetozero!=-1) { ans = Math.min(ans, 1+onetozero); } } if(ans==Integer.MAX_VALUE) { result.append("-1\n"); } else { result.append(ans+"\n"); } } System.out.println(result); } 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) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
1
49e94e7e
f3d7ce08
import java.io.BufferedReader; import java.io.IOException; import java.lang.*; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.out; import java.util.*; import java.io.File; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigInteger; public class Main { /* 10^(7) = 1s. * ceilVal = (a+b-1) / b */ static final int mod = 1000000007; static final long temp = 998244353; static final long MOD = 1000000007; static final long M = (long)1e9+7; static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair ob) { return (int)(first - ob.first); } } static class Tuple implements Comparable<Tuple> { int first, second,third; public Tuple(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } public int compareTo(Tuple o) { return (int)(o.third - this.third); } } public static class DSU { int[] parent; int[] rank; //Size of the trees is used as the rank public DSU(int n) { parent = new int[n]; rank = new int[n]; Arrays.fill(parent, -1); Arrays.fill(rank, 1); } public int find(int i) //finding through path compression { return parent[i] < 0 ? i : (parent[i] = find(parent[i])); } public boolean union(int a, int b) //Union Find by Rank { a = find(a); b = find(b); if(a == b) return false; //if they are already connected we exit by returning false. // if a's parent is less than b's parent if(rank[a] < rank[b]) { //then move a under b parent[a] = b; } //else if rank of j's parent is less than i's parent else if(rank[a] > rank[b]) { //then move b under a parent[b] = a; } //if both have the same rank. else { //move a under b (it doesnt matter if its the other way around. parent[b] = a; rank[a] = 1 + rank[a]; } return true; } } static class Reader { 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) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] longReadArray(int n) throws IOException { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static long lcm(long a, long b) { return (a / LongGCD(a, b)) * b; } public static long LongGCD(long a, long b) { if(b == 0) return a; else return LongGCD(b,a%b); } public static long LongLCM(long a, long b) { return (a / LongGCD(a, b)) * b; } //Count the number of coprime's upto N public static long phi(long n) //euler totient/phi function { long ans = n; // for(long i = 2;i*i<=n;i++) // { // if(n%i == 0) // { // while(n%i == 0) n/=i; // ans -= (ans/i); // } // } // // if(n > 1) // { // ans -= (ans/n); // } for(long i = 2;i<=n;i++) { if(isPrime(i)) { ans -= (ans/i); } } return ans; } public static long fastPow(long x, long n) { if(n == 0) return 1; else if(n%2 == 0) return fastPow(x*x,n/2); else return x*fastPow(x*x,(n-1)/2); } public static long modPow(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return modPow(n, p - 2, p); } // Returns nCr % p using Fermat's little theorem. public static long nCrModP(long n, long r,long p) { if (n<r) return 0; if (r == 0) return 1; long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[(int)(n)] * modInverse(fac[(int)(r)], p) % p * modInverse(fac[(int)(n - r)], p) % p) % p; } public static long fact(long n) { long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (long i = 1; i <= n; i++) fac[(int)(i)] = fac[(int)(i - 1)] * i; return fac[(int)(n)]; } public static long nCr(long n, long k) { long ans = 1; for(long i = 0;i<k;i++) { ans *= (n-i); ans /= (i+1); } return ans; } //Modular Operations for Addition and Multiplication. public static long perfomMod(long x) { return ((x%M + M)%M); } public static long addMod(long a, long b) { return perfomMod(perfomMod(a)+perfomMod(b)); } public static long subMod(long a, long b) { return perfomMod(perfomMod(a)-perfomMod(b)); } public static long mulMod(long a, long b) { return perfomMod(perfomMod(a)*perfomMod(b)); } public static boolean isPrime(long n) { if(n == 1) { return false; } //check only for sqrt of the number as the divisors //keep repeating so only half of them are required. So,sqrt. for(int i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static List<Integer> SieveList(int n) { boolean prime[] = new boolean[(int)(n+1)]; Arrays.fill(prime, true); List<Integer> l = new ArrayList<>(); 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 p = 2; p<=n; p++) { if (prime[p] == true) { l.add(p); } } return l; } public static int countDivisors(int x) { int c = 0; for(int i = 1;i*i<=x;i++) { if(x%i == 0) { if(x/i != i) { c+=2; } else { c++; } } } return c; } public static long log2(long n) { long ans = (long)(log(n)/log(2)); return ans; } public static boolean isPow2(long n) { return (n != 0 && ((n & (n-1))) == 0); } public static boolean isSq(int x) { long s = (long)Math.round(Math.sqrt(x)); return s*s==x; } /* * * >= <= 0 1 2 3 4 5 6 7 5 5 5 6 6 6 7 7 lower_bound for 6 at index 3 (>=) upper_bound for 6 at index 6(To get six reduce by one) (<=) */ public 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; } public static int UpperBound(long a[], long x) { 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; } public static void Sort(long[] a) { List<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); // Collections.reverse(l); //Use to Sort decreasingly for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void ssort(char[] a) { List<Character> l = new ArrayList<>(); for (char 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) throws Exception { Reader sc = new Reader(); PrintWriter fout = new PrintWriter(System.out); int tt = sc.nextInt(); while(tt-- > 0) { int n = sc.nextInt(); char[] a = sc.next().toCharArray(), b = sc.next().toCharArray(); int c00 = 0, c01 = 0, c10 = 0, c11 = 0; for(int i = 0;i<n;i++) { if(a[i] == '0' && b[i] == '0') { c00++; } else if(a[i] == '0' && b[i] == '1') { c01++; } else if(a[i] == '1' && b[i] == '0') { c10++; } else if(a[i] == '1' && b[i] == '1') { c11++; } } int ans = mod; if(c01 == c10) ans = min(ans, c01 + c10); if(c11 == c00 + 1) ans = min(ans, c11 + c00); fout.println((ans == mod) ? -1 : ans); } fout.close(); } }
import javax.swing.plaf.IconUIResource; import java.lang.reflect.Array; import java.text.CollationElementIterator; import java.util.*; import java.io.*; //Timus judge id- 323935JJ public class Main { //---------------------------------------------------------------------------------------------- public static class Pair implements Comparable<Pair> { int x=0,y=0; int z=0; public Pair(int a, int b) { this.x=a; this.y=b; } public int compareTo(Pair o) { return this.x - o.x; } } public static int mod = (int) (1e9 + 7); static int ans = Integer.MAX_VALUE; public static void main(String hi[]) throws Exception { FastReader sc = new FastReader(); int t =sc.nextInt(); while(t-->0) { int n =sc.nextInt(); String a = sc.nextLine(),b=sc.nextLine(); int count1=0,count2=0,count3=0,count4=0; for(int i=0;i<n;i++) { if(a.charAt(i)=='0'&&b.charAt(i)=='0') count1++; else if(a.charAt(i)=='1'&&b.charAt(i)=='1') count2++; else if(a.charAt(i)=='1'&&b.charAt(i)=='0') count3++; else if(a.charAt(i)=='0'&&b.charAt(i)=='1') count4++; } int ans=Integer.MAX_VALUE; if(count3==count4) ans=Math.min(count3*2,ans); if(count2==count1+1) ans=Math.min(ans,2*count1+1); if(ans==Integer.MAX_VALUE) System.out.println(-1); else System.out.println(ans); } } static int find(int[] a,int x) { if(a[x]==-1) return x; else return find(a,a[x]); } static int gcd(int a, int 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 long gcdl(long a, long b) { if (a == 0) return b; return gcdl(b % a, a); } // method to return LCM of two numbers static long lcml(long a, long b) { return (a / gcdl(a, b)) * 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; } } }
0
372a4f50
e435b1ac
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main3 { public static void main(String[] args) { FastReader in = new FastReader(); int t = in.nextInt(); while(t-- > 0) { int n = in.nextInt(); int m = in.nextInt(); int x = in.nextInt(); List<Block> arr = new ArrayList<>(); for(int i = 0; i < n; i++) { arr.add(new Block(in.nextInt(), i)); } if(m == 1) { System.out.println("YES"); for(int i = 0; i < n; i++) { System.out.print(1 + " "); } System.out.println(); continue; } arr.sort(Comparator.reverseOrder()); long[] towers = new long[m]; int ind = 0; boolean right = true; int[] ans = new int[n]; for(int i = 0; i < n; i++) { int nextInd; if(right) { if(ind == m - 1) { right = false; nextInd = ind - 1; } else { nextInd = ind + 1; } } else { if(ind == 0) { right = true; nextInd = ind + 1; } else { nextInd = ind - 1; } } if(towers[ind] <= towers[nextInd]) { towers[ind] += arr.get(i).weight; ans[arr.get(i).index] = ind + 1; } else { towers[nextInd] += arr.get(i).weight; ans[arr.get(i).index] = nextInd + 1; ind = nextInd; } } boolean success = true; for(int i = 0; i < m - 1; i++) { if(Math.abs(towers[i] - towers[i + 1]) > x) { success = false; break; } } if(success) { System.out.println("YES"); for(int i = 0; i < n; i++) { System.out.print(ans[i] + " "); } System.out.println(); } else { System.out.println("NO"); } } } static class Block implements Comparable<Block> { int weight; int index; public Block(int weight, int index) { this.weight = weight; this.index = index; } @Override public int compareTo(Block o) { return Integer.compare(this.weight, o.weight); } } 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; } } }
import java.util.*; import java.io.*; public class C { public static void main(String[] args) { FastScanner sc = new FastScanner(); int T = sc.nextInt(); StringBuilder sb = new StringBuilder(); while(T-->0) { int n = sc.nextInt(); int m = sc.nextInt(); long x = sc.nextLong(); long[] arr = new long[n]; for(int i = 0; i < n; i++) { arr[i] = sc.nextLong(); } int[] res = new int[n]; PriorityQueue<Pair> q = new PriorityQueue<>(); for(int i = 0; i < m; i++) { q.add(new Pair(i+1, 0)); } for(int i = 0; i < n; i++) { Pair p = q.poll(); res[i] = p.i; q.add(new Pair(p.i, p.w + arr[i])); } sb.append("YES\n"); for(int i = 0; i < n; i++) { sb.append(res[i]+" "); } sb.replace(sb.length()-1, sb.length(), "\n"); } PrintWriter pw = new PrintWriter(System.out); pw.println(sb.toString().trim()); pw.flush(); } static class Pair implements Comparable<Pair>{ int i; long w; public Pair(int i, long w) { this.i = i; this.w = w; } public String toString() { return i+" "+w; } @Override public int compareTo(Pair p) { return Long.compare(w, p.w); } } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { 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 long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
0
1162c08f
f6ca6fc8
import java.util.*; public class CodeForces1525C{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); ArrayList<Integer> o=new ArrayList<Integer>(), e=new ArrayList<Integer>(); int n = sc.nextInt(),dp[][]=new int[n+1][n+1]; for(int i=1;i<=n;i++){ int x=sc.nextInt(); if(x==1)o.add(i); else e.add(i); } for(int i=1;i<=o.size();i++){ dp[i][i]=dp[i-1][i-1]+Math.abs(o.get(i-1)-e.get(i-1)); for(int j=i+1;j<=e.size();j++) dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(o.get(i-1)-e.get(j-1))); } System.out.println(dp[o.size()][e.size()]); } }
import java.util.*; import java.io.*; public class D { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n = sc.nextInt(); ArrayList<Integer> o=new ArrayList<Integer>(); ArrayList<Integer> e=new ArrayList<Integer>(); for(int i=1;i<=n;i++){ int x=sc.nextInt(); if(x==1)o.add(i); else e.add(i); } int dp[][]=new int[o.size()+1][e.size()+1]; for(int i=1;i<=o.size();i++){ dp[i][i]=dp[i-1][i-1]+Math.abs(o.get(i-1)-e.get(i-1)); for(int j=i+1;j<=e.size();j++){ dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(o.get(i-1)-e.get(j-1))); } } System.out.println(dp[o.size()][e.size()]); } }
1
4e87c35b
f1f600d9
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } long ans = Long.MAX_VALUE; // sum so far + min*(n-k) long[] evenSum = new long[n]; long[] oddSum = new long[n]; int[] evenMin = new int[n]; int[] oddMin = new int[n]; evenSum[0] = arr[0]; oddSum[1] = arr[1]; evenMin[0] = arr[0]; oddMin[1] = arr[1]; for (int i = 2; i < n; i++) { if (i % 2 == 0) { evenSum[i] = evenSum[i - 2] + arr[i]; evenMin[i] = Math.min(evenMin[i - 2], arr[i]); } else { oddSum[i] = oddSum[i - 2] + arr[i]; oddMin[i] = Math.min(oddMin[i - 2], arr[i]); } } for (int i = 1; i < n; i++) { ans = Math.min(ans, compute(arr, i, evenSum, oddSum, evenMin, oddMin)); } out.println(ans); } private long compute(int[] arr, int i, long[] evenSum, long[] oddSum, int[] evenMin, int[] oddMin) { if (i % 2 == 0) { return evenSum[i] + (arr.length - (i / 2) - 1) * (long) evenMin[i] + oddSum[i - 1] + (arr.length - (i / 2)) * (long) oddMin[i - 1]; } else { return evenSum[i - 1] + (arr.length - (i / 2) - 1) * (long) evenMin[i - 1] + oddSum[i] + (arr.length - (i / 2) - 1) * (long) oddMin[i]; } } } }
// import java.util.Vector; import java.util.*; import java.lang.Math; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.management.Query; import java.io.*; import java.math.BigInteger; public class Main { static int mod = 1000000007; /* ======================DSU===================== */ static class dsu { static int parent[], n;// min[],value[]; static long size[]; dsu(int n) { parent = new int[n + 1]; size = new long[n + 1]; // min=new int[n+1]; // value=new int[n+1]; this.n = n; makeSet(); } static void makeSet() { for (int i = 1; i <= n; i++) { parent[i] = i; size[i] = 1; // min[i]=i; } } static int find(int a) { if (parent[a] == a) return a; else { return parent[a] = find(parent[a]);// Path Compression } } static void union(int a, int b) { int setA = find(a); int setB = find(b); if (setA == setB) return; if (size[setA] >= size[setB]) { parent[setB] = setA; size[setA] += size[setB]; } else { parent[setA] = setB; size[setB] += size[setA]; } } } /* ======================================================== */ static class Pair implements Comparator<Pair> { long x; long y; // Constructor public Pair(long x, long y) { this.x = x; this.y = y; } public Pair() { } @Override public int compare(Main.Pair o1, Main.Pair o2) { return ((int) (o1.x - o2.x)); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] intArr(int n) { int res[] = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] longArr(int n) { long res[] = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } } static FastReader f = new FastReader(); static BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out)); 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 (long i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } 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(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 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 * b) / gcd(a, b); } static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long power(long x, long y) { long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y >>= 1; x = (x * x); } return res; } static int power(int x, int y) { int res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y >>= 1; x = (x * x); } return res; } static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } /* * ===========Modular Operations================== */ static long modInverse(long n, long p) { return power(n, p - 2, p); } static long modAdd(long a, long b) { return (a % mod + b % mod) % mod; } static long modMul(long a, long b) { return ((a % mod) * (b % mod)) % mod; } static long nCrModPFermat(int n, int r) { long p = 1000000007; if (r == 0) return 1; long[] fac = new long[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } /* * =============================================== */ static List<Character> removeDup(ArrayList<Character> list) { List<Character> newList = list.stream().distinct().collect(Collectors.toList()); return newList; } static void ruffleSort(long[] a) { int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n); long temp = a[i]; a[i] = a[oi]; a[oi] = temp; } Arrays.sort(a); } static void ruffleSort(int[] a) { int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n); int temp = a[i]; a[i] = a[oi]; a[oi] = temp; } Arrays.sort(a); } /* * ===========Dynamic prog Recur Section=========== */ static int DP[][]; static ArrayList<ArrayList<Integer>> g; static int count = 0; static ArrayList<Long> bitMask(ArrayList<Long> ar, int n) { ArrayList<Long> ans = new ArrayList<>(); for (int mask = 0; mask <= Math.pow(2, n) - 1; mask++) { long sum = 0; for (int i = 0; i < n; i++) { if (((1 << i) & mask) > 0) { sum += ar.get(i); } } ans.add(sum); } return ans; } /* * ====================================Main================================= */ public static void main(String args[]) throws Exception { // File file = new File("D:\\VS Code\\Java\\Output.txt"); // FileWriter fw = new FileWriter("D:\\VS Code\\Java\\Output.txt"); Random rand = new Random(); int t = 1; t = f.nextInt(); int tc = 1; while (t-- != 0) { int n = f.nextInt(); int c[] = new int[n]; long minOdd = 0, minEven = 0; long sumEven = 0, sumOdd = 0; for (int i = 0; i < n ; i++) { c[i] = f.nextInt(); // if (i % 2 == 0) { // minEven = (c[minEven] > c[i]) ? i : minEven; // sumEven += c[i]; // } else { // minOdd = (minOdd > c[i]) ? i : minOdd; // sumOdd += c[i]; // } } minEven = c[0]; minOdd = c[1]; sumEven=c[0]; sumOdd=c[1]; long min=minEven*n + minOdd*n;//for k=2 int even=1,odd=1; for (int k = 3; k <= n; k++) { if(k%2==1){ sumEven+=c[k-1]; minEven=Math.min(minEven, c[k-1]); even++; }else{ sumOdd+=c[k-1]; minOdd=Math.min(minOdd, c[k-1]); odd++; } min=Math.min(min, sumEven-minEven+minEven*(n-even+1) + sumOdd-minOdd+minOdd*(n-odd+1)); } w.write(min+"\n"); } w.flush(); } }
0
05ca89ed
5b9a0551
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; public class er106c { //By shwetank_verma public static void main(String[] args) { FastReader sc=new FastReader(); try{ int t=1; t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); long o=n,e=n; long maxo=Integer.MAX_VALUE; long maxe=Integer.MAX_VALUE; long ans=Long.MAX_VALUE; long temp=0; int a[]=new int[n]; for(int i=0;i<n;i++){ a[i]=sc.nextInt(); } for(int i=0;i<n;i++) { if(i%2==1) { temp+=a[i]; e--; maxe=Long.min(maxe, a[i]); ans=Long.min(ans,temp+(o*maxo)+(e*maxe)); } else { temp+=a[i]; o--; maxo=Long.min(maxo, a[i]); ans=Long.min(ans,temp+(o*maxo)+(e*maxe)); } } System.out.println(ans); } }catch(Exception e){ return; } } 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 int mod=1000000007; static boolean primes[]=new boolean[1000007]; static ArrayList<Integer> b=new ArrayList<>(); static boolean seive(int n){ Arrays.fill(primes,true); primes[0]=primes[1]=false; for(int i=2;i*i<=n;i++){ if(primes[i]==true){ for(int p=i*i;p<=n;p+=i){ primes[p]=false; } } } if(n<1000007){ for(int i=2;i<=n;i++) { if(primes[i]) b.add(i); } return primes[n]; } return false; } static int gcd(int a,int b){ if(b==0) return a; return gcd(b,a%b); } static long GCD(long a,long b){ if(b==0) return a; return GCD(b,a%b); } static ArrayList<Integer> segseive(int l,int r){ ArrayList<Integer> isprime=new ArrayList<Integer>(); boolean p[]=new boolean[r-l+1]; Arrays.fill(p, true); for(int i=0;b.get(i)*b.get(i)<=r;i++) { int currprime=b.get(i); int base=(l/currprime)*currprime; if(base<l) { base+=currprime; } for(int j=base;j<=r;j+=currprime) { p[j-l]=false; } if(base==currprime) { p[base-l]=true; } } for(int i=0;i<=r-l;i++) { if(p[i]) isprime.add(i+l); } return isprime; } 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(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; } }
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Main { public static void main(String[] args) { FastScanner in=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int t=in.nextInt(); while(t-->0) solve(in,out); out.close(); } static void solve(FastScanner in,PrintWriter out){ int n=in.nextInt(); long a[]=new long[n]; for (int i = 0; i < n; i++) { a[i]=in.nextLong(); } long odd=Integer.MAX_VALUE,even=Integer.MAX_VALUE; even=a[0]; long sum=a[0]; long ans=Long.MAX_VALUE; for (int i = 1; i < n; i++) { if(i%2==0) { ans=Math.min(ans,(n-i/2)*a[i] + odd*(n-i/2) +sum); even=Math.min(even,a[i]); } else { ans=Math.min(ans,(n-i/2)*a[i] + even*(n-i/2-1) +sum); odd=Math.min(odd,a[i]); } sum+=a[i]; } out.println(ans); } static class pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<pair<U, V>> { public U x; public V y; public pair(U x, V y) { this.x = x; this.y = y; } public int compareTo(pair<U, V> other) { int i = x.compareTo(other.x); if (i != 0) return i; return y.compareTo(other.y); } public String toString() { return x.toString() + " " + y.toString(); } public boolean equals(Object obj) { if (this.getClass() != obj.getClass()) return false; pair<U, V> other = (pair<U, V>) obj; return x.equals(other.x) && y.equals(other.y); } public int hashCode() { return 31 * x.hashCode() + y.hashCode(); } } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
0
565f77b7
856a8eda
import java.util.*; import java.io.*; public class Solution { static Scanner scn = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); static StringBuilder sb = new StringBuilder(); public static void main(String[] HastaLaVistaLa) { int t = scn.nextInt(); while(t-- > 0) solve(); out.println(sb); out.close(); } public static void solve() { // Road To Specialist Day 3 int n = scn.nextInt(), m = scn.nextInt(), x = scn.nextInt(); int[] a = new int[n], ans = new int[n]; for(int i = 0; i < n; i++) a[i] = scn.nextInt(); PriorityQueue<Pair> pq = new PriorityQueue<>(); for(int i = 0; i < m; i++) pq.add(new Pair(0L, i)); for(int i = 0; i < n; i++) { int e = a[i]; Pair p = pq.poll(); p.value += e; pq.add(p); ans[i] = p.id + 1; } boolean check = false; long prev = pq.poll().value; while(!pq.isEmpty()) { long cur = pq.poll().value; if(Math.abs(cur - prev) > x) check = true; prev = cur; } if(check) sb.append("NO"); else { sb.append("YES\n"); for(int i : ans) sb.append(i + " "); } sb.append("\n"); } static class Pair implements Comparable<Pair> { int id; long value; public Pair(long value, int id) { this.id = id; this.value = value; } public int compareTo(Pair o) { return Long.compare(value, o.value); } } }
/*input 2 5 2 3 1 2 3 1 2 4 3 3 1 1 2 3 */ import java.io.*; import java.util.*; public class three{ public static class Pair implements Comparable<Pair>{ int min; int idx; @Override public int compareTo(Pair o) { return min - o.min; } } public static void main(String[] args) throws Exception { MyScanner scn = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); /* int n = sc.nextInt(); // read input as integer long k = sc.nextLong(); // read input as long double d = sc.nextDouble(); // read input as double String str = sc.next(); // read input as String String s = sc.nextLine(); // read whole line as String int result = 3*n; out.println(result); // print via PrintWriter */ //The Code Starts here int t = scn.nextInt(); while(t-- > 0){ int n = scn.nextInt(); int m = scn.nextInt(); int x = scn.nextInt(); int arr[] = scn.nextIntArray(n); PriorityQueue<Pair> pq = new PriorityQueue<>(); System.out.println("YES"); for(int i=0;i<m;i++){ Pair p = new Pair(); p.min = arr[i]; p.idx = i+1; pq.add(p); System.out.print(p.idx + " "); } for(int i=m;i<n;i++){ Pair p = pq.peek(); int mini = p.min; int index = p.idx; System.out.print(index + " "); pq.remove(); Pair np = new Pair(); np.min = arr[i] + mini; np.idx = index; pq.add(np); } System.out.println(); } //The Code Ends here out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } 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 int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public int[][] nextInt2DArray(int m, int n) { int[][] arr = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) arr[i][j] = nextInt(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } // public static class Pair implements Comparable<Pair> { // long u; // long v; // public Pair(long u, long v) { // this.u = u; // this.v = v; // } // public int hashCode() { // int hu = (int) (u ^ (u >>> 32)); // int hv = (int) (v ^ (v >>> 32)); // return 31 * hu + hv; // } // public boolean equals(Object o) { // Pair other = (Pair) o; // return u == other.u && v == other.v; // } // public int compareTo(Pair other) { // return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v); // } // public String toString() { // return "[u=" + u + ", v=" + v + "]"; // } // } //-------------------------------------------------------- }
0
b9595381
c4ca2ff3
import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main{ static int dest1; static int dest2; public static void main(String args[]){ FastScanner in = new FastScanner(); int test=in.nextInt(); while(test-->0){ int n=in.nextInt(); int count[][]=new int[n][5]; int total[]=new int[n]; String words[]=new String[n]; for(int i=0;i<n;i++){ words[i]=in.next(); for(int j=0;j<words[i].length();j++) count[i][words[i].charAt(j)-'a']++; total[i]=words[i].length(); } int max=Integer.MIN_VALUE; for(int i=0;i<5;i++){ Integer ans[]=new Integer[n]; for(int j=0;j<n;j++){ ans[j]=count[j][i]-(total[j]-count[j][i]); } Arrays.sort(ans,Collections.reverseOrder()); int j=0; int r=0; while(j<n && r+ans[j]>0){ r+=ans[j]; j++; } max=Math.max(j,max); } System.out.println(max); } } public static int solve(int start[], int end[], int n) { int distance[][]=new int[n][n]; int r=n; int c=n; boolean visited[][]=new boolean[n][n]; int startx=start[0]; int starty=start[1]; int endx=end[0]; int endy=end[1]; Pair tmp=new Pair(startx,starty); Queue<Pair> q=new LinkedList<>(); q.add(tmp); visited[startx][starty]=true; distance[startx][starty]=0; int dx[]={-2,-1,1,2,2,1,-1,-2}; int dy[]={1,2,2,1,-1,-2,-2,-1}; while(!q.isEmpty()) { Pair cell=q.poll(); int x=cell.x; int y=cell.y; int d=distance[x][y]; for(int i=0;i<8;i++) { int childx=x+dx[i]; int childy=y+dy[i]; if(valid(childx,childy,r,c,visited)) { visited[childx][childy]=true; distance[childx][childy]=d+1; q.add(new Pair(childx,childy)); } } } return distance[endx][endy]; } public static boolean valid(int x,int y,int r,int c,boolean visited[][]) { if(x<0||y<0||x>=r||y>=c) return false; if(visited[x][y]) return false; return true; } public static int knight(int i,int j){ if(i==dest1 && j==dest2) return 0; if(i<1 || j<1) return 0; if(i>8 || j>8) return 0; if(i<1 || j>8) return 0; if(i>8 || j<1) return 0; int min=0; if(i-1>=1 && j-2>=1) min+=1+knight(i-1,j-2); if(i-1>=1 && j+2<=8) min+=1+knight(i-1,j+2); if(i-2>=1 && j-1>=1) min+=1+knight(i-2,j-1); if(i-2>=1 && j+1<=8) min+=1+knight(i-2,j+1); if(i+1<=8 && j-2>=1) min+=1+knight(i+1,j-2); if(i+1<=8 && j+2<=8) min+=1+knight(i+1,j+2); if(i+2<=8 && j-1>=1) min+=1+knight(i+2,j-1); if(i+2<=8 && j+1<=8) min+=1+knight(i+2,j+1); return min; } } class FastScanner { java.io.BufferedReader br = new java.io.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()); } } class Pair { int x; int y; Pair(int i,int j) { x=i; y=j; } }
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc=new Scanner(System.in); int t=sc.nextInt(); PrintWriter out=new PrintWriter(System.out); while(t-->0) { int n=sc.nextInt(); int freq[][]=new int[n][5]; int rem[][]=new int[n][5]; for(int i=0;i<n;i++) { String str=sc.next(); for(int j=0;j<str.length();j++) { freq[i][str.charAt(j)-'a']++; } for(int k=0;k<5;k++) { rem[i][k]=str.length()-freq[i][k]; } } int ans=0; for(int i=0;i<5;i++) { int arr[]=new int[n]; for(int j=0;j<n;j++) arr[j]=freq[j][i]-rem[j][i]; Arrays.sort(arr); int total=0; int sum=0; for(int k=n-1;k>=0;k--) { if(sum+arr[k]>0) { sum=sum+arr[k]; total++; } else { break; } } ans=Math.max(ans,total); } out.println(ans); } out.flush(); out.close(); } }
0
9291ca83
d6fb3b9e
import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Practice { static HashMap<String, Integer> map = new HashMap<>(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-->0) { int n = sc.nextInt(); int[][] occurances = new int[5][n]; for(int i=0;i<n;i++){ String s = sc.next(); int[] count = new int[5]; int len = s.length(); for(int j=0;j<s.length();j++){ count[s.charAt(j)-'a']++; } for(int j=0;j<5;j++){ occurances[j][i] = count[j] - (len-count[j]); } } int ans = 0; for(int i=0;i<5;i++){ Arrays.sort(occurances[i]); int tmpAns = 0; int tmpSum=0; for(int j=n-1;j>=0;j--){ tmpSum+=occurances[i][j]; if(tmpSum>0) tmpAns++; else break; } ans = Math.max(ans, tmpAns); } System.out.println(ans); } } }
import java.util.*; public class Sol { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int a[][]=new int[n][5]; int tot[]=new int[n]; for(int i=0;i<n;i++) { String x = sc.next(); for(int j=0;j<x.length();j++) a[i][x.charAt(j)-'a'] += 1; tot[i]=x.length(); } int max=Integer.MIN_VALUE; for(int i=0;i<5;i++) max=Math.max(max,function(a,n,i,tot)); System.out.println(max); } } static int function(int a[][],int n,int i,int tot[]) { Integer ans[] = new Integer[n]; for(int j=0;j<n;j++) ans[j]=a[j][i]-(tot[j]-a[j][i]); int res=0,j=0; Arrays.sort(ans,Collections.reverseOrder()); while(j<n&&res+ans[j]>0) res+=ans[j++]; return j; } }
0
6f393cfe
7a9c69d8
import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); try{ int t = Integer.parseInt(br.readLine()); while(t-->0){ int n = Integer.parseInt(br.readLine()); int lst[][] = new int[n][5]; for(int i=0; i<n; i++){ String s = br.readLine(); for(int j=0; j<s.length(); j++){ lst[i][s.charAt(j)-'a']++; } } int fans = Integer.MIN_VALUE; for(int i=0; i<5; i++){ int val[] = new int[n]; for(int k=0; k<n; k++){ int sum = 0; for(int j=0; j<5; j++){ if(i==j){ sum += lst[k][j]; }else{ sum -= lst[k][j]; } } val[k] = sum; } Arrays.sort(val); int sum = 0; int ans = 0; for(int x = n-1; x>=0; x--){ sum+=val[x]; if(sum>0){ ans++; }else{ break; } } fans = Math.max(fans, ans); } bw.write(fans+"\n"); } bw.flush(); }catch(Exception e){ return; } } }
import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); try{ int t = Integer.parseInt(br.readLine()); while(t-->0){ int n = Integer.parseInt(br.readLine()); int lst[][] = new int[n][5]; for(int i=0; i<n; i++){ String s = br.readLine(); for(int j=0; j<s.length(); j++){ lst[i][s.charAt(j)-'a']++; } } int fans = Integer.MIN_VALUE; for(int i=0; i<5; i++){ int val[] = new int[n]; for(int k=0; k<n; k++){ int sum = 0; for(int j=0; j<5; j++){ if(i==j){ sum += lst[k][j]; }else{ sum -= lst[k][j]; } } val[k] = sum; } Arrays.sort(val); int sum = 0; int ans = 0; for(int x = n-1; x>=0; x--){ sum+=val[x]; if(sum>0){ ans++; }else{ break; } } fans = Math.max(fans, ans); } bw.write(fans+"\n"); } bw.flush(); }catch(Exception e){ return; } } }
1
2ff0355e
83935617
import java.io.*; import java.util.*; public class PhoenixAndTowers { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static class Pair implements Comparable<Pair> { int val, idx; Pair (int val, int idx) { this.val = val; this.idx = idx; } public int compareTo(Pair p) { if (val == p.val) return Integer.compare(idx, p.idx); return Integer.compare(val, p.val); } } public static void main(String[] args) throws IOException { int T = readInt(); for (int t = 0; t < T; t ++) { int n = readInt(), m = readInt(), x = readInt(); Pair[] h = new Pair[n + 1]; h[0] = new Pair(100000, 0); for (int i = 1; i <= n; i ++) h[i] = new Pair(readInt(), i); Arrays.sort(h, Collections.reverseOrder()); int[] ans = new int[n + 1], sum = new int[m + 1]; PriorityQueue<Pair> q = new PriorityQueue<Pair>(); for (int i = 1; i <= m; i ++) q.add(new Pair(0, i)); for (int i = 1; i <= n; i ++) { Pair p = q.poll(); sum[p.idx] += h[i].val; ans[h[i].idx] = p.idx; q.add(new Pair(p.val + h[i].val, p.idx)); } int max = 0, min = Integer.MAX_VALUE; for (int i = 1; i <= m; i ++) { max = Math.max(max, sum[i]); min = Math.min(min, sum[i]); } if (max - min > x) System.out.println("NO"); else { System.out.println("YES"); for (int i = 1; i < n; i ++) System.out.print(ans[i] + " "); System.out.println(ans[n]); } } } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine().trim()); return st.nextToken(); } static long readLong() throws IOException { return Long.parseLong(next()); } static int readInt() throws IOException { return Integer.parseInt(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readCharacter() throws IOException { return next().charAt(0); } static String readLine() throws IOException { return br.readLine().trim(); } }
import java.util.*; import java.lang.*; import java.io.*; // Created by @thesupremeone on 02/05/21 public class C { static class Tower implements Comparable<Tower>{ int index; int height = 0; LinkedList<Integer> blocks; public Tower(int index) { this.index = index; blocks = new LinkedList<>(); } void addBlock(int block){ blocks.add(block); height += block; } @Override public int compareTo(Tower tower) { if(height!=tower.height) return Integer.compare(height, tower.height); return Integer.compare(index, tower.index); } } void solve() throws IOException { int ts = getInt(); for (int t = 1; t <= ts; t++){ int n = getInt(); int m = getInt(); int x = getInt(); Integer[] h = new Integer[n]; Integer[] org = new Integer[n]; for (int i = 0; i < n; i++){ h[i] = getInt(); org[i] = h[i]; } if(m==1){ println("YES"); for (int i = 0; i < n; i++) { print("1 "); } println(""); continue; } TreeSet<Tower> towers = new TreeSet<>(); for (int i = 0; i < m; i++){ Tower tower = new Tower(i+1); towers.add(tower); } Arrays.sort(h, Comparator.reverseOrder()); for (int i = 0; i < n; i++) { Tower tower = towers.pollFirst(); if(tower!=null){ tower.addBlock(h[i]); towers.add(tower); } } Tower first = towers.first(); Tower last = towers.last(); int diff = Math.abs(first.height-last.height); if(diff<=x){ println("YES"); HashMap<Integer, LinkedList<Integer>> map = new HashMap<>(); for (Tower tower : towers){ for(int block : tower.blocks){ LinkedList<Integer> list; if(map.containsKey(block)){ list = map.get(block); }else { list = new LinkedList<>(); map.put(block, list); } list.add(tower.index); } } for (int i = 0; i < n; i++) { int block = org[i]; LinkedList<Integer> list = map.get(block); if(!list.isEmpty()){ int e = list.pollFirst();; print(e+" "); } } println(""); }else { println("NO"); } } } public static void main(String[] args) throws Exception { if (isOnlineJudge()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); new C().solve(); out.flush(); } else { Thread judge = new Thread(); in = new BufferedReader(new FileReader("input.txt")); out = new BufferedWriter(new FileWriter("output.txt")); judge.start(); new C().solve(); out.flush(); judge.suspend(); } } static boolean isOnlineJudge(){ try { return System.getProperty("ONLINE_JUDGE")!=null || System.getProperty("LOCAL")==null; }catch (Exception e){ return true; } } // Fast Input & Output static BufferedReader in; static StringTokenizer st; static BufferedWriter out; static String getLine() throws IOException{ return in.readLine(); } static String getToken() throws IOException{ if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(getLine()); return st.nextToken(); } static int getInt() throws IOException { return Integer.parseInt(getToken()); } static long getLong() throws IOException { return Long.parseLong(getToken()); } static void print(Object s) throws IOException{ out.write(String.valueOf(s)); } static void println(Object s) throws IOException{ out.write(String.valueOf(s)); out.newLine(); } }
0
0fdc80c5
28c2d81a
import java.io.*; import java.util.*; public class E { public static void main(String[] args) { FastScanner scan = new FastScanner(); int t = scan.nextInt(); for(int tt = 0;tt<t;tt++) { int n = scan.nextInt(), k = scan.nextInt(); int a[] = scan.readArray(k); int temp[] = scan.readArray(k); int l[] = new int[n]; int r[] = new int[n]; Arrays.fill(l, Integer.MAX_VALUE/2); Arrays.fill(r, Integer.MAX_VALUE/2); for(int i = 0;i<k;i++) l[a[i]-1] = temp[i]; for(int i = 0;i<k;i++) r[a[i]-1] = temp[i]; for(int i = 1;i<n;i++) l[i] = Math.min(l[i], l[i-1]+1); for(int i = n-2;i>=0;i--) r[i] = Math.min(r[i], r[i+1]+1); StringBuilder s = new StringBuilder(); for(int i = 0;i<n;i++) s.append(Math.min(l[i], r[i])+" "); System.out.println(s); } } 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()); } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class D { public static void main(String[] args) { FastScanner fs = new FastScanner(); int cases = fs.nextInt(); while(cases-->0){ int n = fs.nextInt(), k = fs.nextInt(); int[] positions = fs.readArray(k), temps = fs.readArray(k); int[] forced = new int[n]; Arrays.fill(forced, Integer.MAX_VALUE/2); for(int i=0; i<k; i++) forced[positions[i]-1] = temps[i]; for(int i=1; i<n; i++) forced[i] = Math.min(forced[i],forced[i-1]+1); for(int i=n-2; i>=0; i--) forced[i] = Math.min(forced[i], forced[i+1]+1); for(int i=0; i<n; i++) System.out.print(forced[i] + " "); System.out.println(); } } //----------------------------------------------------------------------------------// 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()); } char nextChar(){ return next().charAt(0); } 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()); } } static class Debug{ public static void debug(long a){ System.out.println("--> "+a); } public static void debug(long a, long b){ System.out.println("--> "+ a +" + " + b); } public static void debug(char a, char b){ System.out.println("--> "+ a +" + " + b); } public static void debug(int[] array){ System.out.print("Array--> "); System.out.println(Arrays.toString(array)); } public static void debug(char[] array){ System.out.print("Array--> "); System.out.println(Arrays.toString(array)); } public static void debug(HashMap<Integer,Integer> map){ System.out.print("Map--> "+map.toString()); } } }
1
39210347
68dff461
//#Rohitpratap311 //Keep_Calm_And_Stay_Happy import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=input.nextInt(); while(T-->0) { int n=input.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=input.nextInt(); } int b[]=new int[n]; if(n%2==0) { for(int i=0;i<n;i+=2) { int v1=Math.abs(a[i]),v2=Math.abs(a[i+1]); int l=lcm(v1,v2); int x=l/v1,y=l/v2; if((a[i]>=0 && a[i+1]<0) || (a[i]<0 && a[i+1]>=0)) { b[i]=x; b[i+1]=y; } else { b[i]=x; b[i+1]=-y; } } for(int i=0;i<n;i++) { out.print(b[i]+" "); } out.println(); } else { for(int i=0;i<n-3;i+=2) { int v1=Math.abs(a[i]),v2=Math.abs(a[i+1]); int l=lcm(v1,v2); int x=l/v1,y=l/v2; if((a[i]>=0 && a[i+1]<0) || (a[i]<0 && a[i+1]>=0)) { b[i]=x; b[i+1]=y; } else { b[i]=x; b[i+1]=-y; } } int l1=lcm(Math.abs(a[n-3]),Math.abs(a[n-2])); int x=l1/Math.abs(a[n-3]),y=l1/Math.abs(a[n-2]); int l2=lcm(Math.abs(a[n-3]),Math.abs(a[n-1])); int z=l2/Math.abs(a[n-3]); if((a[n-3]>=0 && a[n-2]<0) || (a[n-3]<0 && a[n-2]>=0)) { } else { y=-y; } x+=z; int sum=a[n-3]*x+a[n-2]*y; sum=-sum; z=sum/a[n-1]; b[n-3]=x; b[n-2]=y; b[n-1]=z; for(int i=0;i<n;i++) { out.print(b[i]+" "); } out.println(); } } out.close(); } public static int gcd(int a, int b) { if(a==0) { return b; } else { return gcd(b%a,a); } } public static int lcm(int a, int b) { return (a/gcd(a,b))*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; } } }
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=input.nextInt(); while(T-->0) { int n=input.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=input.nextInt(); } int b[]=new int[n]; if(n%2==0) { for(int i=0;i<n;i+=2) { int v1=Math.abs(a[i]),v2=Math.abs(a[i+1]); int l=lcm(v1,v2); int x=l/v1,y=l/v2; if((a[i]>=0 && a[i+1]<0) || (a[i]<0 && a[i+1]>=0)) { b[i]=x; b[i+1]=y; } else { b[i]=x; b[i+1]=-y; } } for(int i=0;i<n;i++) { out.print(b[i]+" "); } out.println(); } else { for(int i=0;i<n-3;i+=2) { int v1=Math.abs(a[i]),v2=Math.abs(a[i+1]); int l=lcm(v1,v2); int x=l/v1,y=l/v2; if((a[i]>=0 && a[i+1]<0) || (a[i]<0 && a[i+1]>=0)) { b[i]=x; b[i+1]=y; } else { b[i]=x; b[i+1]=-y; } } int l1=lcm(Math.abs(a[n-3]),Math.abs(a[n-2])); int x=l1/Math.abs(a[n-3]),y=l1/Math.abs(a[n-2]); int l2=lcm(Math.abs(a[n-3]),Math.abs(a[n-1])); int z=l2/Math.abs(a[n-3]); if((a[n-3]>=0 && a[n-2]<0) || (a[n-3]<0 && a[n-2]>=0)) { } else { y=-y; } x+=z; int sum=a[n-3]*x+a[n-2]*y; sum=-sum; z=sum/a[n-1]; b[n-3]=x; b[n-2]=y; b[n-1]=z; for(int i=0;i<n;i++) { out.print(b[i]+" "); } out.println(); } } out.close(); } public static int gcd(int a, int b) { if(a==0) { return b; } else { return gcd(b%a,a); } } public static int lcm(int a, int b) { return (a/gcd(a,b))*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; } } }
1
701c3f35
d56bcb0c
import java.util.*; import java.io.*; public class Menorah { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(f.readLine()); while(t-->0) { int n=Integer.parseInt(f.readLine()); String s=f.readLine(); String s2=f.readLine(); int[] arr=new int[4]; //0 00 1 01 2 10 3 11 for(int i=0;i<n;i++) { if(s.charAt(i)=='0') { if(s2.charAt(i)=='0') { arr[0]++; } else { arr[1]++; } } else { if(s2.charAt(i)=='0') { arr[2]++; } else { arr[3]++; } } } int min=Integer.MAX_VALUE; if(arr[1]==arr[2]) { min=arr[1]*2; } int temp=arr[1]; arr[1]=arr[3]; arr[3]=temp; temp=arr[0]; arr[0]=arr[2]; arr[2]=temp; arr[3]++; arr[1]--; if(arr[1]==arr[2]) { min=Math.min(min, arr[1]*2+1); } System.out.println(min!=Integer.MAX_VALUE?min:-1); } } }
import java.util.*; import java.lang.*; import java.io.*; public class Main { static int func(char a[],char b[]){ int n=a.length; int a1=0,b1=0; for(int i=0;i<n;i++){ if(a[i]=='1')a1++; if(b[i]=='1')b1++; } if(a1!=b1)return 100000000; int cnt=0; for(int i=0;i<n;i++){ if(a[i]=='1'&&b[i]!='1')cnt++; } return cnt*2; } public static void main (String[] args) throws java.lang.Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //int t=1; int t=Integer.parseInt(br.readLine()); while(--t>=0){ int n=Integer.parseInt(br.readLine()); char a[]=br.readLine().toCharArray(); char b[]=br.readLine().toCharArray(); int x=func(a,b); int ind=-1; for(int i=0;i<n;i++){ if(a[i]==b[i]&&a[i]=='1'){ ind=i; break; } } int y=100000000; if(ind>=0){ for(int i=0;i<n;i++){ if(i==ind)continue; if(a[i]=='1')a[i]='0'; else a[i]='1'; } y=func(a,b)+1; } if(x>=1000000&&y>=1000000){ System.out.println(-1); } else System.out.println(Math.min(x,y)); } } }
0
31f29772
d04e5afb
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.io.*; public class PhoenixTow { private static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static class Pair implements Comparable<Pair> { int x; int y; Pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(Pair p) { return ((Integer)this.x).compareTo(p.x); } } public static void solution(int[] arr, int n, int m, int x) { ArrayList<Pair> list = new ArrayList<>(); for(int i = 0; i<n; i++) { list.add(new Pair(arr[i], i)); } Collections.sort(list); long[] sum = new long[m]; int[] ans = new int[n]; int k = 1; for(int i = 0; i<list.size(); i++) { if(k<m) { if(sum[k-1]+list.get(i).x - sum[k]>x) {out.println("NO"); return; } } sum[k-1]+=list.get(i).x; ans[list.get(i).y] = k; k++; if(k==(m+1)) k=1; } out.println("YES"); for(int i = 0; i<n; i++) out.print(ans[i]+" "); out.println(); } private static PrintWriter out = new PrintWriter(System.out); public static void main (String[] args) { MyScanner s = new MyScanner(); int t = s.nextInt(); for(int j = 0; j<t ; j++) { int n = s.nextInt(); int m = s.nextInt(); int x = s.nextInt(); int[] arr = new int[n]; for(int i =0; i<n; i++) arr[i] = s.nextInt(); solution(arr,n,m,x); } out.flush(); out.close(); } }
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.Objects; import java.util.Collections; import java.io.InputStream; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CPhoenixAndTowers solver = new CPhoenixAndTowers(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class CPhoenixAndTowers { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(); ArrayList<Pair<Integer, Integer>> a = new ArrayList<>(); for (int i = 0; i < n; ++i) { a.add(new Pair<>(in.nextInt(), i)); } Collections.sort(a); int[] ans = new int[n]; int[] sum = new int[m]; int j = 1; for (int i = 0; i < n; ++i) { ans[a.get(i).y] = j; sum[j - 1] += a.get(i).x; j++; if (j == m + 1) j = 1; } for (int i = 1; i < m; ++i) { if (Math.abs(sum[i - 1] - sum[i]) > k) { out.println("NO"); } } out.println("YES"); for (int e : ans) { out.print(e + " "); } out.println(); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class Pair<U, V> implements Comparable<Pair<U, V>> { public U x; public V y; public Pair(U x, V y) { this.x = x; this.y = y; } public int compareTo(Pair<U, V> o) { int value = ((Comparable<U>) x).compareTo(o.x); if (value != 0) return value; return ((Comparable<V>) y).compareTo(o.y); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return x.equals(pair.x) && y.equals(pair.y); } public int hashCode() { return Objects.hash(x, y); } } }
0
2695ce73
ac8acb97
import java.io.*; import java.util.*; public class c { /* 3 2 13 88 3 2 3 1 5 4 3 2 1 4 202 13 19 + - + - + 1, 2 2, 1 3, 3 */ public static void main(String args[]) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); for ( ; t > 0; t--) { int n = in.nextInt(); long[] vals = new long[n]; for (int i = 0; i < n; i++) vals[i] = in.nextInt(); // System.out.println(Arrays.toString(pre)); // sSystem.out.println(Arrays.toString(pre1)); long oo = (long)(1e18); long[] min = {oo, oo}; long[] sub = {n, n}; long sum = 0; long max = oo; for (int i = 0; i < n; i++) { min[i % 2] = Math.min(min[i % 2], vals[i]); sub[i % 2]--; sum += vals[i]; if (i > 0) { max = Math.min(max, sum + min[0] * sub[0] + min[1] * sub[1]); } } out.println(max); } out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = new StringTokenizer(""); } public String next() throws IOException { if(st.hasMoreTokens()) return st.nextToken(); else st = new StringTokenizer(br.readLine()); return next(); } 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()); } //$ } }
import java.util.Scanner; public class C1499 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); // int[] arr = new int[n]; long[] mn = { Long.MAX_VALUE, Long.MAX_VALUE }; long[] rem = { n, n }; long sum = 0; long ans = Long.MAX_VALUE; for (int i = 0; i < n; i++) { int temp = in.nextInt(); mn[i % 2] = Math.min(mn[i % 2], temp); rem[i % 2]--; sum += temp; if (i > 0) { long cur = sum + rem[0] * mn[0] + rem[1] * mn[1]; ans = Math.min(ans, cur); } } System.out.println(ans); // int a = Integer.MAX_VALUE; // int aIndex = -1; // int b = Integer.MAX_VALUE; // int bIndex = -1; // // for (int i = 0; i < n; i++) { // arr[i] = in.nextInt(); // if (i % 2 == 0) { // if (arr[i] < a) { // a = arr[i]; // aIndex = i; // } // } else { // if (arr[i] < b) { // b = arr[i]; // bIndex = i; // } // } // } // int sum = 0; // for (int i = 0; i < Math.max(bIndex, aIndex) + 1; i++) { // if (i % 2 == 0) { // if (i == aIndex) { // if (aIndex < bIndex) { // sum += (n - (i / 2) - ((bIndex - aIndex) / 2)) * arr[i]; // } else { // sum += (n - (i / 2)) * arr[i]; // } // } else { // sum += arr[i]; // } // } else { // if (i == bIndex) { // if (bIndex < aIndex) { // sum += (n - (i / 2) - ((aIndex - bIndex) / 2)) * arr[i]; // } else { // sum += (n - (i / 2)) * arr[i]; // } // } else { // sum += arr[i]; // } // } // // } // System.out.println(sum); // for (int i = 0; i < n; i++) { // arr[i] = in.nextInt(); // if (arr[i] < a) { // a = arr[i]; // aIndex = i; // // } // // } // if (aIndex == 0) { // // for (int i = 1; i < n; i++) { // if (arr[i] < b) { // b = arr[i]; // bIndex = i; // } // } // System.out.println(aIndex + " " + bIndex); // System.out.println(a + " " + b); // int sum = 0; // for (int i = 1; i < bIndex; i++) { // sum += arr[i]; // } // sum += b * (n - bIndex + 1); // sum += a * n; // System.out.println(sum); // } else { // int b = Integer.MAX_VALUE; // int bIndex = -1; // for (int i = 0; i < aIndex; i++) { // if (arr[i] < b) { // b = arr[i]; // bIndex = i; // } // } // System.out.println(aIndex + " " + bIndex); // System.out.println(a + " " + b); // int sum = 0; // for (int i = 0; i < bIndex; i++) { // sum += arr[i]; // } // sum += b * (n - bIndex); // sum += a * n; // System.out.println(sum); // } } } }
1
8f6421f3
bdfe8110
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Arrays; public class Main{ public static void main (String[] args){ FastReader s = new FastReader(); int t=1;t=s.ni(); for(int test=1;test<=t;test++){ int n=s.ni(),k=s.ni(); int position[]=s.readArray(k),temp[]=s.readArray(k); int ans[]=new int[n]; Arrays.fill(ans,Integer.MAX_VALUE/2); for(int i=0;i<k;i++){ ans[position[i]-1]=temp[i]; } for(int i=1;i<n;i++){ ans[i]=Math.min(ans[i-1]+1,ans[i]); } for(int i=n-2;i>=0;i--){ ans[i]=Math.min(ans[i],ans[i+1]+1); } for(int i=0;i<n;i++) System.out.print(ans[i]+" "); System.out.println(); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in));} int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } int[] readArray(int n){ int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] =Integer.parseInt(next()); return a; } String next(){ while (st == null || !st.hasMoreElements()) {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;} } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class E { public static void main(String[] args) { FastScanner fs=new FastScanner(); int T=fs.nextInt(); PrintWriter out=new PrintWriter(System.out); for (int tt=0; tt<T; tt++) { int n=fs.nextInt(), k=fs.nextInt(); int[] positions=fs.readArray(k), temps=fs.readArray(k); int[] forced=new int[n]; Arrays.fill(forced, Integer.MAX_VALUE/2); for (int i=0; i<k; i++) forced[positions[i]-1]=temps[i]; for (int i=1; i<n; i++) forced[i]=Math.min(forced[i], forced[i-1]+1); for (int i=n-2; i>=0; i--) forced[i]=Math.min(forced[i], forced[i+1]+1); for (int i=0; i<n; i++) out.print(forced[i]+" "); out.println(); } out.close(); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
1
d3a96420
ff34fab2
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); String x=sc.next(); Vector<Integer> R=new Vector<>(); Vector<Integer> B=new Vector<>(); for(int i=0;i<n;i++){ if(x.charAt(i)=='B') R.add(a[i]); else B.add(a[i]); } Collections.sort(R); Collections.sort(B); boolean yes=true; for(int i=0;i<R.size();i++){ if(R.get(i)-i<1){System.out.println("NO");yes=false;break;} } if(yes) { int s=B.size(); for(int j=0;j<s;j++){ if(B.get(j)+s-j>n+1){System.out.println("NO");yes=false;break;} } } if(yes)System.out.println("YES"); } sc.close(); } }
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.io.*; public class Div2 { private static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static String solution(int [] arr, int n, String st) { ArrayList<Integer> red = new ArrayList<>(); ArrayList<Integer> blue = new ArrayList<>(); for(int i = 0; i<n; i++) { if(st.charAt(i)=='R') red.add(arr[i]); else blue.add(arr[i]); } Collections.sort(red); Collections.sort(blue); int cb = 1; for(int j = 0; j<blue.size(); j++) { if(blue.get(j)<cb) return "NO"; cb++; } int cr = n; for(int j = red.size()-1; j>=0; j--) { if(red.get(j)>cr) return "NO"; cr--; } return "YES"; } private static PrintWriter out = new PrintWriter(System.out); public static void main (String[] args) { MyScanner s = new MyScanner(); int t = s.nextInt(); for(int j = 0; j<t ; j++) { int n = s.nextInt(); int[] arr = new int[n]; for(int i =0; i<n; i++) arr[i] = s.nextInt(); String st = s.next(); out.println(solution(arr,n, st)); } out.flush(); out.close(); } }
0
6f02c6d9
c2242c42
import java.io.*; import java.util.*; public class Main { static long mod = 1000000007; static long inv(long a, long b) { return 1 < a ? b - inv(b % a, a) * b / a : 1; } static long mi(long a) { return inv(a, mod); } static InputReader sc = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] A = new int[n]; for (int i = 0; i < A.length; i++) { A[i] = sc.nextInt(); } String word = sc.next(); ArrayList<Integer> blue = new ArrayList<>(); ArrayList<Integer> red = new ArrayList<>(); for (int i = 0; i < word.length(); i++) { if (word.charAt(i) == 'R') { red.add(A[i]); } else { blue.add(A[i]); } } Collections.sort(blue); Collections.sort(red); boolean possible = true; int a = 1; for (int i = 0; i < blue.size(); i++, a++) { if (blue.get(i) < a) { possible = false; break; } } for (int i = 0; i < red.size(); i++, a++) { if (red.get(i) > a) { possible = false; break; } } if (possible) out.println("YES"); else out.println("NO"); } out.flush(); out.close(); } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.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 = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return str; } } public static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } public static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } }
// package codechef; import java.io.*; import java.util.*; public class cp_2 { static int mod=998244353; // static Reader sc=new Reader(); static FastReader sc=new FastReader(System.in); static int[] sp; static int size=(int)1e6; public static void main(String[] args) throws IOException { long tc=sc.nextLong(); // Scanner sc=new Scanner(System.in); // int tc=1; // primeSet=new HashSet<>(); // sieveOfEratosthenes((int)1e5); while(tc-->0) { int n=sc.nextInt(); int arr[]=new int[n]; for (int i = 0; i < arr.length; i++) { arr[i]=sc.nextInt(); } String s=sc.next(); ArrayList<Integer> blue=new ArrayList<>(); ArrayList<Integer> red=new ArrayList<>(); for(int i=0;i<n;i++) { if(s.charAt(i)=='B') blue.add(arr[i]); else { red.add(arr[i]); } } Collections.sort(blue); Collections.sort(red,Collections.reverseOrder()); boolean flag=true; for(int i=0;i<blue.size();i++) { if(blue.get(i)<i+1) flag=false; } for(int i=0;i<red.size();i++) { if(red.get(i)>n-i) flag=false; } printYesNo(flag); } out.flush(); out.close(); System.gc(); } /* ...SOLUTION ENDS HERE...........SOLUTION ENDS HERE... */ static int N = 501; // Array to store inverse of 1 to N static long[] factorialNumInverse = new long[N + 1]; // Array to precompute inverse of 1! to N! static long[] naturalNumInverse = new long[N + 1]; // Array to store factorial of first N numbers static long[] fact = new long[N + 1]; // Function to precompute inverse of numbers public static void InverseofNumber(int p) { naturalNumInverse[0] = naturalNumInverse[1] = 1; for(int i = 2; i <= N; i++) naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p; } // Function to precompute inverse of factorials public static void InverseofFactorial(int p) { factorialNumInverse[0] = factorialNumInverse[1] = 1; // Precompute inverse of natural numbers for(int i = 2; i <= N; i++) factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p; } // Function to calculate factorial of 1 to N public static void factorial(int p) { fact[0] = 1; // Precompute factorials for(int i = 1; i <= N; i++) { fact[i] = (fact[i - 1] * (long)i) % p; } } // Function to return nCr % p in O(1) time public static long Binomial(int N, int R, int p) { // n C r = n!*inverse(r!)*inverse((n-r)!) long ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p; return ans; } static String tr(String s) { int now = 0; while (now + 1 < s.length() && s.charAt(now)== '0') ++now; return s.substring(now); } static ArrayList<Integer> ans; static void dfs(int node,Graph gg,int cnt,int k,ArrayList<Integer> temp) { if(cnt==k) return; for(Integer each:gg.list[node]) { if(each==0) { temp.add(each); ans=new ArrayList<>(temp); temp.remove(temp.size()-1); continue; } temp.add(each); dfs(each,gg,cnt+1,k,temp); temp.remove(temp.size()-1); } return; } static HashSet<Integer> factors(int x) { HashSet<Integer> a=new HashSet<Integer>(); for(int i=2;i*i<=x;i++) { if(x%i==0) { a.add(i); a.add(x/i); } } return a; } static class Node { int vertex; HashSet<Node> adj; boolean rem; Node(int ver) { vertex=ver; rem=false; adj=new HashSet<Node>(); } @Override public String toString() { return vertex+" "; } } static class Tuple{ int a; int b; int c; public Tuple(int a,int b,int c) { this.a=a; this.b=b; this.c=c; } } //function to find prime factors of n static HashMap<Integer,Integer> findFactors(int n) { HashMap<Integer,Integer> ans=new HashMap<>(); if(n%2==0) { ans.put(2, 0); while((n&1)==0) { n=n>>1; ans.put(2, ans.get(2)+1); } } for(int i=3;i*i<=n;i+=2) { if(n%i==0) { ans.put(i, 0); while(n%i==0) { n=n/i; ans.put(i, ans.get(i)+1); } } } if(n!=1) ans.put(n, ans.getOrDefault(n, 0)+1); return ans; } //fenwick tree implementaion static class fwt { int n; long BITree[]; fwt(int n) { this.n=n; BITree=new long[n+1]; } fwt(int arr[], int n) { this.n=n; BITree=new long[n+1]; for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); } long getSum(int index) { long sum = 0; index = index + 1; while(index>0) { sum += BITree[index]; index -= index & (-index); } return sum; } void updateBIT(int n, int index,int val) { index = index + 1; while(index <= n) { BITree[index] += val; index += index & (-index); } } void print() { for(int i=0;i<n;i++) out.print(getSum(i)+" "); out.println(); } } //Function to find number of set bits static int setBitNumber(long n) { if (n == 0) return 0; int msb = 0; n = n / 2; while (n != 0) { n = n / 2; msb++; } return msb; } static int getFirstSetBitPos(long n) { return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1; } static ArrayList<Integer> primes; static HashSet<Integer> primeSet; static boolean prime[]; static void sieveOfEratosthenes(int n) { // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. prime= new boolean[n + 1]; for (int i = 2; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) primeSet.add(i); } } static long mod(long a, long b) { long c = a % b; return (c < 0) ? c + b : c; } static void swap(long arr[],int i,int j) { long temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } static boolean util(int a,int b,int c) { if(b>a)util(b, a, c); while(c>=a) { c-=a; if(c%b==0) return true; } return (c%b==0); } static void flag(boolean flag) { out.println(flag ? "YES" : "NO"); out.flush(); } static void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print_int(ArrayList<Integer> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void print_long(ArrayList<Long> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void printYesNo(boolean condition) { if (condition) { out.println("Yes"); } else { out.println("No"); } } static int LowerBound(int a[], int x) { // x is the target value or key int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } static int lowerIndex(int arr[], int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y static int upperIndex(int arr[], int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } static int upperIndex(long arr[], int n, long y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } static int UpperBound(int a[], int x) {// x is the key or target value int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } static int UpperBound(long a[], long x) {// x is the key or target value int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } static class DisjointUnionSets { int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each void makeSet() { for (int i = 0; i < n; i++) parent[i] = i; } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } // Unites the set that includes x and the set // that includes x void union(int x, int y) { int xRoot = find(x), yRoot = find(y); if (xRoot == yRoot) return; if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else // if ranks are the same { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + 1; } // if(xRoot!=yRoot) // parent[y]=x; } int connectedComponents() { int cnt=0; for(int i=0;i<n;i++) { if(parent[i]==i) cnt++; } return cnt; } } static class Graph { int v; ArrayList<Integer> list[]; Graph(int v) { this.v=v; list=new ArrayList[v+1]; for(int i=1;i<=v;i++) list[i]=new ArrayList<Integer>(); } void addEdge(int a, int b) { this.list[a].add(b); } } // static class GraphMap{ // Map<String,ArrayList<String>> graph; // GraphMap() { // // TODO Auto-generated constructor stub // graph=new HashMap<String,ArrayList<String>>(); // // } // void addEdge(String a,String b) // { // if(graph.containsKey(a)) // this.graph.get(a).add(b); // else { // this.graph.put(a, new ArrayList<>()); // this.graph.get(a).add(b); // } // } // } // static void dfsMap(GraphMap g,HashSet<String> vis,String src,int ok) // { // vis.add(src); // // if(g.graph.get(src)!=null) // { // for(String each:g.graph.get(src)) // { // if(!vis.contains(each)) // { // dfsMap(g, vis, each, ok+1); // } // } // } // // cnt=Math.max(cnt, ok); // } static double sum[]; static long cnt; static void DFS(Graph g, boolean[] visited, int u) { visited[u]=true; for(int i=0;i<g.list[u].size();i++) { int v=g.list[u].get(i); if(!visited[v]) { cnt=cnt*2; DFS(g, visited, v); } } } static class Pair implements Comparable<Pair> { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return this.x-o.x; } } static long sum_array(int a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static long sum_array(long a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void reverse_array(int a[]) { int n=a.length; int i,t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static void reverse_array(long a[]) { int n=a.length; int i; long t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // static long modInverse(long a, long m) // { // long g = gcd(a, m); // // return power(a, m - 2, m); // // } static long power(long x, long y) { long res = 1; x = x % mod; if (x == 0) return 0; while (y > 0) { if ((y & 1) != 0) res = (res * x) % mod; y = y >> 1; // y = y/2 x = (x * x) % mod; } return res; } static long gcd(long a, long b) { if (a == 0) return b; //cnt+=a/b; return gcd(b%a,a); } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } static class FastReader{ byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static PrintWriter out=new PrintWriter(System.out); static int int_max=Integer.MAX_VALUE; static int int_min=Integer.MIN_VALUE; static long long_max=Long.MAX_VALUE; static long long_min=Long.MIN_VALUE; }
1
2acaa7df
46e9aed4
import java.io.*; import java.util.*; public class Ishu { static Scanner scan = new Scanner(System.in); static BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); static void tc() throws Exception { int n = scan.nextInt(); int[] a = new int[n]; int one = 0; int i,j; for(i=0;i<n;++i) { a[i] = scan.nextInt(); one += a[i]; } int[] pos = new int[one]; one = 0; for(i=0;i<n;++i) if(a[i] == 1) pos[one++] = i; long[][] dp = new long[one][n]; if(one == 0) { output.write("0\n"); output.flush(); return; } if(a[0] == 0) dp[0][0] = pos[0]; else dp[0][0] = Integer.MAX_VALUE; for(j=1;j<n;++j) { if(a[j] == 1) { dp[0][j] = dp[0][j-1]; continue; } dp[0][j] = Math.abs(pos[0] - j); dp[0][j] = Math.min(dp[0][j], dp[0][j-1]); } for(i=1;i<one;++i) { int cnt = 0; for(j=0;j<n;++j) { if(a[j] == 0) ++cnt; if(cnt == i + 1) break; dp[i][j] = Integer.MAX_VALUE; } for(;j<n;++j) { if(a[j] == 1) { dp[i][j] = dp[i][j-1]; continue; } dp[i][j] = Math.abs(pos[i] - j) + dp[i-1][j-1]; dp[i][j] = Math.min(dp[i][j], dp[i][j-1]); } } // for(i=0;i<one;++i) // { // for(j=0;j<n;++j) // output.write(dp[i][j] + " "); // output.write("\n"); // } long ans = dp[one-1][n-1]; output.write(ans + "\n"); output.flush(); } public static void main(String[] args) throws Exception { int t = 1; //t = scan.nextInt(); while(t-- > 0) tc(); } }
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public final class Solution { public static void main(String[] args) throws Exception { Reader sc = new Reader(); BufferedWriter op = new BufferedWriter(new OutputStreamWriter(System.out)); int n=sc.nextInt(); ArrayList<Integer> fill= new ArrayList<Integer>(); ArrayList<Integer> unfilled= new ArrayList<>(); for(int i=0;i<n;i++){ int x =sc.nextInt(); if(x==1){ fill.add(i); }else{ unfilled.add(i); } } Collections.sort(fill); Collections.sort(unfilled); long[][] dp =new long[fill.size()+1][unfilled.size()+1]; for(int i=0;i<fill.size()+1;i++){ for(int j=0;j<unfilled.size()+1;j++){ dp[i][j]=Integer.MAX_VALUE; } } for(int i=0;i<unfilled.size()+1;i++){ dp[0][i]=0; } // for(int j=0;j<fill.size()+1;j++){ // dp[j][0]=0; // } for(int i=1;i<fill.size()+1;i++){ for(int j=1;j<unfilled.size()+1;j++){ dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(fill.get(i-1)-unfilled.get(j-1))); } } System.out.println(dp[fill.size()][unfilled.size()]); // for(int i=0;i<fill.size()+1;i++){ // for(int j=0;j<unfilled.size()+1;j++) // { // System.out.print(dp[i][j]+" "); // } // System.out.println(); // } } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
0
2bd5c798
317baeaf
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.*; /** * * @Har_Har_Mahadev */ /** * Main , Solution , Remove Public */ public class A { public static void process() throws IOException { int n = sc.nextInt(); String s = sc.next(),t = sc.next(); int zs = 0, zt = 0; for(int i = 0; i<n; i++) { if(s.charAt(i) == '0')zs++; if(t.charAt(i) == '0')zt++; } int ans = n+1; if(zs == zt) { int min = 0; for(int i = 0; i<n; i++)if(s.charAt(i) != t.charAt(i))min++; ans = min(ans, min); } if(n-zs-1 == zt) { int min = 0; for(int i = 0; i<n; i++)if(s.charAt(i) == t.charAt(i))min++; ans = min(ans, min); } if(ans == n+1)ans = -1; System.out.println(ans); } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; private static void google(int tt) { System.out.print("Case #" + (tt) + ": "); } static FastScanner sc; static FastWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new FastWriter(System.out); } else { sc = new FastScanner("input.txt"); out = new FastWriter("output.txt"); } long s = System.currentTimeMillis(); int t = 1; t = sc.nextInt(); int TTT = 1; while (t-- > 0) { // google(TTT++); process(); } out.flush(); // tr(System.currentTimeMillis()-s+"ms"); } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.err.println(Arrays.deepToString(o)); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } /* @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair key = (Pair) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } */ } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long sqrt(long z) { long sqz = (long) Math.sqrt(z); while (sqz * 1L * sqz < z) { sqz++; } while (sqz * 1L * sqz > z) { sqz--; } return sqz; } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } public static long gcd(long a, long b) { if (a > b) a = (a + b) - (b = a); if (a == 0L) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = -1; while (low <= high) { mid = (low + high) / 2; if (arr[mid] > x) { high = mid - 1; } else { ans = mid; low = mid + 1; } } return ans; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = arr.length; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) { ans = mid; high = mid - 1; } else { low = mid + 1; } } return ans; } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void reverseArray(int[] a) { int n = a.length; int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long arr[] = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } //custom multiset (replace with HashMap if needed) public static void push(TreeMap<Integer, Integer> map, int k, int v) { //map[k] += v; if (!map.containsKey(k)) map.put(k, v); else map.put(k, map.get(k) + v); } public static void pull(TreeMap<Integer, Integer> map, int k, int v) { //assumes map[k] >= v //map[k] -= v int lol = map.get(k); if (lol == v) map.remove(k); else map.put(k, lol - v); } // compress Big value to Time Limit public static int[] compress(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int boof = 1; //min value for (int x : ls) if (!map.containsKey(x)) map.put(x, boof++); int[] brr = new int[arr.length]; for (int i = 0; i < arr.length; i++) brr[i] = map.get(arr[i]); return brr; } // Fast Writer public static class FastWriter { private static final int BUF_SIZE = 1 << 13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter() { out = null; } public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) innerflush(); return this; } public FastWriter write(char c) { return write((byte) c); } public FastWriter write(char[] s) { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if (x == Integer.MIN_VALUE) { return write((long) x); } if (ptr + 12 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if (x == Long.MIN_VALUE) { return write("" + x); } if (ptr + 21 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if (x < 0) { write('-'); x = -x; } x += Math.pow(10, -precision) / 2; // if(x < 0){ x = 0; } write((long) x).write("."); x -= (long) x; for (int i = 0; i < precision; i++) { x *= 10; write((char) ('0' + (int) x)); x -= (int) x; } return this; } public FastWriter writeln(char c) { return write(c).writeln(); } public FastWriter writeln(int x) { return write(x).writeln(); } public FastWriter writeln(long x) { return write(x).writeln(); } public FastWriter writeln(double x, int precision) { return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for (int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for (long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte) '\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for (char[] line : map) write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c) { return writeln(c); } public FastWriter println(int x) { return writeln(x); } public FastWriter println(long x) { return writeln(x); } public FastWriter println(double x, int precision) { return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } // Fast Inputs static class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] readArray(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readArrayLong(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public int[][] readArrayMatrix(int N, int M, int Index) { if (Index == 0) { int[][] res = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = (int) nextLong(); } return res; } int[][] res = new int[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = (int) nextLong(); } return res; } public long[][] readArrayMatrixLong(int N, int M, int Index) { if (Index == 0) { long[][] res = new long[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = nextLong(); } return res; } long[][] res = new long[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] readArrayDouble(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } }
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st; int t = Integer.parseInt(br.readLine()); while (t --> 0) { int n = Integer.parseInt(br.readLine()); String a = br.readLine(); String b = br.readLine(); int alit = 0; int blit = 0; int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { if (a.charAt(i) == '1') alit++; if (b.charAt(i) == '1') blit++; } if (alit == blit) { int count = 0; for (int i = 0; i < n; i++) if (a.charAt(i) != b.charAt(i)) count++; ans = Math.min(count, ans); } if (alit == n - blit + 1) { int count = 0; for (int i = 0; i < n; i++) if (a.charAt(i) == b.charAt(i)) count++; ans = Math.min(ans, count); } if (ans == Integer.MAX_VALUE) { pw.println("-1"); } else { pw.println(ans); } } pw.close(); } }
1
ec607ca1
ed37ba7d
/* TO LEARN 1-segment trees 2-euler tour 3-fenwick tree and interval tree */ /* TO SOLVE uva 1103 program codeforces edu 102 D */ /* bit manipulation shit 1-Computer Systems: A Programmer's Perspective 2-hacker's delight 3-(02-03-bits-ints) 4-machine-basics 5-Bits Manipulation tutorialspoint */ /* TO WATCH 1-what is bitmasking by kartik arora youtube */ import java.util.*; import java.math.*; import java.io.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; public class A{ static InputStream inputStream = System.in; static FastScanner scan=new FastScanner(); public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static boolean vis[]=new boolean[26]; static LinkedList<Integer>edges[]; static int cnt=0; static ArrayList<Integer>arr=new ArrayList(); static void dfs(int c,boolean vis2[]) { vis[c]=true; // vis2[c]=true; arr.add(c); for(int v:edges[c]) { if(!vis[v]) { dfs(v,vis2); } } } public static void main(String[] args) throws Exception { // scan=new FastScanner("lifeguards.in"); //out = new PrintWriter("lifeguards.out"); /* currently doing 1-digit dp 2-ds like fenwick and interval tree and sparse table */ /* READING 1-Everything About Dynamic Programming codeforces 2-DYNAMIC PROGRAMMING: FROM NOVICE TO ADVANCED topcoder 3-Introduction to DP with Bitmasking codefoces 4-Bit Manipulation hackerearth */ int tt=1; //System.out.println(2&0); /*for(int i=0;i<=70;i++) for(int j=0;j<=70;j++){ if((i&j)==i) System.out.println(i+" "+j+" "+(i&j)); }*/ //System.out.println(1^14); //System.out.println(15&6); tt=scan.nextInt(); outer:while(tt-->0) { int l=scan.nextInt(),n=scan.nextInt(); int arr[]=new int[n]; long t[]=new long[n]; int pos[]=new int[l+1]; Arrays.fill(pos,-1); TreeSet<Integer>tree=new TreeSet<Integer>(); for(int i=0;i<n;i++){ arr[i]=scan.nextInt(); tree.add(arr[i]); pos[arr[i]]=i; } for(int i=0;i<n;i++) t[i]=scan.nextLong(); long L[]=new long[l+5]; long R[]=new long[l+5]; Arrays.fill(L,Integer.MAX_VALUE); Arrays.fill(R,Integer.MAX_VALUE); for(int i=1;i<=l;i++) { if(pos[i]!=-1) { L[i]=t[pos[i]]; } L[i]=Math.min(L[i],L[i-1]+1); } for(int i=l;i>=1;i--) { if(pos[i]!=-1) { R[i]=t[pos[i]]; } R[i]=Math.min(R[i],R[i+1]+1); } for(int i=1;i<=l;i++) out.print(Math.min(L[i],R[i])+" "); out.println(); } out.close(); } static class special{ long x1,y1,x2,y2; //int id; special(long x1,long y1,long x2,long y2) { this.x1=x1; this.y1=y1; this.x2=x2; this.y2=y2; //this.id=id; } @Override public int hashCode() { int hash = 7; hash = 31 * hash + (int) x1; hash = 31 * hash + (int)x2; hash = 31 * hash + (int)y1; hash = 31 * hash + (int)y2; return hash; } @Override public boolean equals(Object o){ if (o == this) return true; if (o.getClass() != getClass()) return false; special t = (special)o; return t.x1 == x1 && t.y1 == y1&&t.x2==x2&&t.y2==y2; } } static long binexp(long a,long n) { if(n==0) return 1; long res=binexp(a,n/2); if(n%2==1) return res*res*a; else return res*res; } static long powMod(long base, long exp, long mod) { if (base == 0 || base == 1) return base; if (exp == 0) return 1; if (exp == 1) return (base % mod+mod)%mod; long R = (powMod(base, exp/2, mod) % mod+mod)%mod; R *= R; R %= mod; if ((exp & 1) == 1) { return (base * R % mod+mod)%mod; } else return (R %mod+mod)%mod; } static double dis(double x1,double y1,double x2,double y2) { return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } static long mod(long x,long y) { if(x<0) x=x+(-x/y+1)*y; return x%y; } public static long pow(long b, long e) { long r = 1; while (e > 0) { if (e % 2 == 1) r = r * b ; b = b * b; e >>= 1; } return r; } private static void sort(long[] arr) { List<Long> list = new ArrayList<>(); for (long object : arr) list.add(object); Collections.sort(list); //Collections.reverse(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } private static void sort2(long[] arr) { List<Long> list = new ArrayList<>(); for (Long object : arr) list.add(object); Collections.sort(list); Collections.reverse(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static class Pair implements Comparable<Pair>{ public long x, y,z; public Pair(long x1, long y1,long z1) { x=x1; y=y1; z=z1; } public Pair(long x1, long y1) { x=x1; y=y1; } @Override public int hashCode() { return (int)(x + 31 * y); } public String toString() { return x + " " + y+" "+z; } @Override public boolean equals(Object o){ if (o == this) return true; if (o.getClass() != getClass()) return false; Pair t = (Pair)o; return t.x == x && t.y == y&&t.z==z; } public int compareTo(Pair o) { return (int)(x-o.x); } } }
import java.io.*; import java.util.*; import java.lang.*; public class codeforces { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; if (System.getProperty("ONLINE_JUDGE") == null) { long startTime = System.currentTimeMillis(); try { sc = new InputReader(new FileInputStream("input.txt")); out = new PrintWriter(new FileOutputStream("output.txt")); pr = new PrintWriter(new FileOutputStream("error.txt")); } catch (Exception ignored) { } int t = 1; int tt = t; t = sc.nextInt(); while (t-- > 0) { solve(); } long endTime = System.currentTimeMillis(); System.out.println("Time: " + (endTime - startTime) / tt + " ms"); out.flush(); pr.flush(); } else { sc = new InputReader(inputStream); out = new PrintWriter(outputStream); pr = new PrintWriter(outputStream); int t = 1; t = sc.nextInt(); while (t-- > 0) { solve(); } out.flush(); } } public static void solve() { n = sc.nextInt(); for (int i = 0; i < n; i++) { dp[i] = inf; ans[i] = inf; } m = sc.nextInt(); for (int i = 0; i < m; i++) arr[i] = sc.nextInt() - 1; for (int i = 0; i < m; i++) { arr2[i] = sc.nextInt(); dp[(int)arr[i]] = arr2[i]; } temp = inf; for (int i = 0; i < n; i++) { temp = Math.min(temp, dp[i]); ans[i] = Math.min(ans[i], temp); temp++; } temp = inf; for (int i = (int)n - 1; i > -1; i--) { temp = Math.min(temp, dp[i]); ans[i] = Math.min(ans[i], temp); temp++; } for (int i = 0; i < n; i++) out.print(ans[i] + " "); out.println(""); } /* * Set Iterator Iterator value = set.iterator(); Displaying the values after * iterating through the iterator * System.out.println("The iterator values are: "); while (value.hasNext()) { * System.out.println(value.next()); } */ /* * Map Iterator: for (Map.Entry<Integer, Integer> entry : map.entrySet()){ * System.out.println("Key => " + entry.getKey() + ", Value => " + * entry.getValue());} */ // Globals public static long n, m, temp; public static int template_array_size = (int) 1e6 + 16813; public static long[] arr = new long[template_array_size]; public static long[] arr2 = new long[template_array_size]; public static long[] dp = new long[template_array_size]; public static long[] ans = new long[template_array_size]; public static int inf = Integer.MAX_VALUE; public static int minf = Integer.MIN_VALUE; public static int mod = 1000000007; public static int ml = (int) 1e9; public static String s = ""; public static InputReader sc; public static PrintWriter out; public static PrintWriter pr; // Pair static class Pair { int first, second; Pair(int x, int y) { this.first = x; this.second = y; } } // FastReader Class 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()); } } // Req Functions public static void fill(int[][] dp, int x) { for (int i = 0; i < dp.length; ++i) { for (int j = 0; j < dp[0].length; ++j) { dp[i][j] = x; } } } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } public static long nCr(int n, int k) { long ans = 1L; k = k > n - k ? n - k : k; int j = 1; for (; j <= k; j++, n--) { if (n % j == 0) { ans *= n / j; } else if (ans % j == 0) { ans = ans / j * n; } else { ans = (ans * n) / j; } } return ans; } public static String reverseString(String input) { StringBuilder str = new StringBuilder(""); for (int i = input.length() - 1; i >= 0; i--) { str.append(input.charAt(i)); } return str.toString(); } public static int maxOf3(int x, int y, int z) { return Math.max(x, Math.max(y, z)); } public static int minof3(int x, int y, int z) { return Math.min(x, Math.min(y, z)); } public static long maxOf3(long x, long y, long z) { return Math.max(x, Math.max(y, z)); } public static long minof3(long x, long y, long z) { return Math.min(x, Math.min(y, z)); } public static void arrInput(int[] arr, int n) { for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); } public static void arrInput(long[] arr, int n) { for (int i = 0; i < n; i++) arr[i] = sc.nextLong(); } public static void arrInput(Pair[] pair, int n) { for (int i = 0; i < n; i++) pair[i] = new Pair(sc.nextInt(), sc.nextInt()); } public static int maxarrInput(int[] arr, int n) { int max = minf; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); max = Math.max(max, arr[i]); } return max; } public static long maxarrInput(long[] arr, int n) { long max = minf; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); max = Math.max(max, arr[i]); } return max; } public static int minarrInput(int[] arr, int n) { int min = inf; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); min = Math.max(min, arr[i]); } return min; } public static long minarrInput(long[] arr, int n) { long min = inf; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); min = Math.max(min, arr[i]); } return min; } public static int lowerBound(int[] arr, int x) { int l = -1, r = arr.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (arr[m] >= x) r = m; else l = m; } return r; } public static int upperBound(int[] arr, int x) { int l = -1, r = arr.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (arr[m] <= x) l = m; else r = m; } return l + 1; } public static void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int[n1]; int R[] = new int[n2]; for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] >= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void reversesort(int arr[], int l, int r) { if (l < r) { int m = l + (r - l) / 2; reversesort(arr, l, m); reversesort(arr, m + 1, r); merge(arr, l, m, r); } } public static void merge(long arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; long L[] = new long[n1]; long R[] = new long[n2]; for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] >= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void reversesort(long arr[], int l, int r) { if (l < r) { int m = l + (r - l) / 2; reversesort(arr, l, m); reversesort(arr, m + 1, r); merge(arr, l, m, r); } } // debug public static boolean sysFlag = System.getProperty("ONLINE_JUDGE") == null; public static void debug(int[][] dp) { if (sysFlag) { for (int i = 0; i < dp.length; ++i) { pr.print(i + "--> "); for (int j = 0; j < dp[0].length; ++j) { pr.print(dp[i][j] + " "); } pr.println(""); } } } public static void debug(long[][] dp) { if (sysFlag) { for (int i = 0; i < dp.length; ++i) { pr.print(i + "--> "); for (int j = 0; j < dp[0].length; ++j) { pr.print(dp[i][j] + " "); } pr.println(""); } } } public static void debug(int x) { if (sysFlag) pr.println("Int-Ele: " + x); } public static void debug(String x) { if (sysFlag) pr.println("String: " + x); } public static void debug(char x) { if (sysFlag) pr.println("Char: " + x); } public static void debug(long x) { if (sysFlag) pr.println("Long-Ele: " + x); } public static void debug(int[] arr, int n) { if (sysFlag) { for (int i = 0; i < n; ++i) { pr.println(i + " -> " + arr[i]); } } } public static void debug(char[] arr) { if (sysFlag) { for (int i = 0; i < arr.length; ++i) { pr.println(i + " -> " + arr[i]); } } } public static void debug(long[] arr, int n) { if (sysFlag) { for (int i = 0; i < n; ++i) { pr.println(i + " -> " + arr[i]); } } } public static void debug(ArrayList<Integer> list) { if (sysFlag) { for (int i = 0; i < list.size(); ++i) { pr.println(i + " -> " + list.get(i)); } } } public static void Ldebug(ArrayList<Long> list) { if (sysFlag) { for (int i = 0; i < list.size(); ++i) { pr.println(i + " -> " + list.get(i)); } } } public static void debugmapII(HashMap<Integer, Integer> map) { if (sysFlag) { for (Map.Entry<Integer, Integer> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapLI(HashMap<Long, Integer> map) { if (sysFlag) { for (Map.Entry<Long, Integer> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapLL(HashMap<Long, Long> map) { if (sysFlag) { for (Map.Entry<Long, Long> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapIL(HashMap<Integer, Long> map) { if (sysFlag) { for (Map.Entry<Integer, Long> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapSL(HashMap<String, Long> map) { if (sysFlag) { for (Map.Entry<String, Long> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapCL(HashMap<Character, Long> map) { if (sysFlag) { for (Map.Entry<Character, Long> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapSI(HashMap<String, Integer> map) { if (sysFlag) { for (Map.Entry<String, Integer> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapCI(HashMap<Character, Integer> map) { if (sysFlag) { for (Map.Entry<Character, Integer> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debug(Set<Integer> set) { if (sysFlag) { Iterator value = set.iterator(); int i = 1; while (value.hasNext()) { pr.println((i++) + "-> " + value.next()); } } } }
0
26e699de
f229aa7f
//package Task1; import java.util.Scanner; public class Menorah { static int MOD9= 1000000000; public static void main(String[] args){ Scanner sc= new Scanner(System.in); int numberTest=sc.nextInt(); while(numberTest-->0){ int n=sc.nextInt(); char[] s=new char[n+5]; char[] t=new char[n+5]; String ss=sc.next(); String tt=sc.next(); s=ss.toCharArray(); t=tt.toCharArray(); int cntax = 0, cntbx = 0, same = 0; int ans=MOD9; for(int i=0; i<n; i++){ if(s[i]=='1')cntax++; if(t[i]=='1')cntbx++; if(s[i]==t[i])same++; } if(same==n){ System.out.println(0); continue; } else if (cntax==0){ System.out.println(-1); continue; } if(cntax==cntbx){ ans=Math.min(ans,n-same); } if(n-cntax+1==cntbx)ans=Math.min(ans,same); if(ans<MOD9) System.out.println(ans); else System.out.println(-1); } } }
import java.util.*; import java.io.*; import java.math.*; public class cf { static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException, InterruptedException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); char[] a = sc.next().toCharArray(); char[] b = sc.next().toCharArray(); int x = 0, y = 0, lit = 0,lit2 = 0; for (int i = 0; i < n; i++) { if (a[i] == '1') lit++; if (b[i] == '1') lit2++; if (a[i] == b[i]) x++; else y++; } if(lit == lit2 || n - lit + 1 == lit2) { if (lit == lit2 && n - lit + 1 == lit2) { pw.println(Math.min(x,y)); }else if(lit == lit2) { pw.println(y); }else { pw.println(x); } }else { pw.println(-1); } } pw.close(); } public static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) return this.z - other.z; return this.y - other.y; } else { return this.x - other.x; } } } public static class pair implements Comparable<pair> { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Integer(x).hashCode() * 31 + new Integer(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
0
169e34bf
609af028
import java.util.*; public class D{ static Scanner sc; public static void solve(){ int n=sc.nextInt(); Integer a[]=new Integer[n]; int flag; for(int i=0;i<n;i++) a[i]=sc.nextInt(); String s=sc.next(); ArrayList<Integer> x=new ArrayList<>(); ArrayList<Integer> y=new ArrayList<>(); for(int i=0;i<n;i++){ if(s.charAt(i)=='B') x.add(a[i]); else y.add(a[i]); } Collections.sort(x); Collections.sort(y); int p=n; int q=1; for(int i=y.size()-1;i>=0;i--){ if(y.get(i)>p){System.out.println("NO"); return;} p-=1; } for(int i=0;i<x.size();i++){ if(x.get(i)<q){System.out.println("NO"); return;} q+=1; } System.out.println("YES"); } public static void main(String args[]){ sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) solve(); } }
import java.io.*; import java.util.*; public class new1{ public static void main(String[] args) throws IOException{ FastReader s = new FastReader(); //long l1 = System.currentTimeMillis(); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); int t = s.nextInt(); for(int z = 0; z < t; z++) { int n = s.nextInt(); int[] arr = new int[n]; ArrayList<Integer> blue = new ArrayList<Integer>(); ArrayList<Integer> red = new ArrayList<Integer>(); for(int i = 0; i < n; i++) { arr[i] = s.nextInt(); } String str = s.next(); for(int i = 0; i < n; i++) { if(str.charAt(i) == 'B') blue.add(arr[i]); else red.add(arr[i]); } red.sort(null); blue.sort(null); int j = red.size() - 1; int k = blue.size() - 1; while(j >= 0 && red.get(j) > n) j--; boolean ans = true; // System.out.println(blue.toString()); // System.out.println(red.toString()); for(int m = n; m >= 1; m--) { if(j >= 0) j--; else if(k >= 0 && blue.get(k) >= m) k--; else ans = false; //System.out.println(m + " " + j + " " + k); while(j >= 0 && red.get(j) > m - 1) j--; } if(ans) System.out.println("YES"); else System.out.println("NO"); } //output.write((System.currentTimeMillis() - l1) + "\n"); //output.flush(); } } 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(); } public 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; }}
0
3ff60986
d0b4b96c
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.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 N = (int)2e5 +10; static ArrayList<ArrayList<Integer>> adj= new ArrayList<>(N); static { for(int i=0; i<N; i++) { adj.add(new ArrayList<>()); } } static int[][] a = new int[2][N]; static long[][] dp = new long[2][N]; static void dfs(int v, int p){ dp[0][v] = 0; dp[1][v]=0; for(int u: adj.get(v)) { if(u!=p) { dfs(u, v); dp[0][v] += Math.max(Math.abs(a[0][v] - a[1][u]) + dp[1][u], Math.abs(a[0][v] - a[0][u]) + dp[0][u]); dp[1][v] += Math.max(Math.abs(a[1][v] - a[1][u]) + dp[1][u], Math.abs(a[1][v] - a[0][u]) + dp[0][u]); } } } public static void main(String[] args) throws IOException{ // write your code here FastReader sc = new FastReader(); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); for(int i=1; i<=n; i++) { a[0][i] = sc.nextInt(); a[1][i] = sc.nextInt(); adj.set(i, new ArrayList<>()); } for(int i=1; i<n; i++) { int u = sc.nextInt(); int v = sc.nextInt(); adj.get(u).add(v); adj.get(v).add(u); } dfs(1, 0); System.out.println(Math.max(dp[0][1], dp[1][1])); } } }
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.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 N = (int)2e5 +10; static ArrayList<ArrayList<Integer>> adj= new ArrayList<>(N); static { for(int i=0; i<N; i++) { adj.add(new ArrayList<>()); } } static int[][] a = new int[2][N]; static long[][] dp = new long[2][N]; static void dfs(int v, int p){ dp[0][v] = 0; dp[1][v]=0; for(int u: adj.get(v)) { if(u!=p) { dfs(u, v); dp[0][v] += Math.max(Math.abs(a[0][v] - a[1][u]) + dp[1][u], Math.abs(a[0][v] - a[0][u]) + dp[0][u]); dp[1][v] += Math.max(Math.abs(a[1][v] - a[1][u]) + dp[1][u], Math.abs(a[1][v] - a[0][u]) + dp[0][u]); } } } public static void main(String[] args) throws IOException{ // write your code here FastReader sc = new FastReader(); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); for(int i=1; i<=n; i++) { a[0][i] = sc.nextInt(); a[1][i] = sc.nextInt(); adj.set(i, new ArrayList<>()); } for(int i=1; i<n; i++) { int u = sc.nextInt(); int v = sc.nextInt(); adj.get(u).add(v); adj.get(v).add(u); } dfs(1, 0); System.out.println(Math.max(dp[0][1], dp[1][1])); } } }
1
722e318f
b790ef12
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; public class TaskB { static long mod = 1000000007; static FastScanner scanner; static final StringBuilder result = new StringBuilder(); public static void main(String[] args) { // 2 : 1000000000 scanner = new FastScanner(); int T = scanner.nextInt(); for (int t = 0; t < T; t++) { solve(t + 1); result.append("\n"); } System.out.println(result); } static void solve(int t) { int n = scanner.nextInt(); int[] a = scanner.nextIntArray(n); String s = scanner.nextToken(); List<Integer> blue = new ArrayList<>(); List<Integer> red = new ArrayList<>(); for (int i = 0; i < n; i++) { if (s.charAt(i) == 'B') { blue.add(a[i]); } else { red.add(a[i]); } } Collections.sort(blue); Collections.sort(red); for (int i = 0; i < blue.size(); i++) { if (blue.get(i) < i + 1) { result.append("NO"); return; } } for (int i = 0; i < red.size(); i++) { if (red.get(i) > i + 1 + blue.size()) { result.append("NO"); return; } } result.append("YES"); } static class WithIdx implements Comparable<WithIdx> { int val, idx; public WithIdx(int val, int idx) { this.val = val; this.idx = idx; } @Override public int compareTo(WithIdx o) { if (val == o.val) { return Integer.compare(idx, o.idx); } return Integer.compare(val, o.val); } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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(); } String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] nextLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } String[] nextStringArray(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = nextToken(); return res; } } static class PrefixSums { long[] sums; public PrefixSums(long[] sums) { this.sums = sums; } public long sum(int fromInclusive, int toExclusive) { if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value"); return sums[toExclusive] - sums[fromInclusive]; } public static PrefixSums of(int[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } public static PrefixSums of(long[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } } static class ADUtils { static void sort(int[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } static void reverse(int[] arr) { int last = arr.length / 2; for (int i = 0; i < last; i++) { int tmp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = tmp; } } static void sort(long[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap long a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } } static class MathUtils { static long[] FIRST_PRIMES = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051}; static long[] primes(int to) { long[] all = new long[to + 1]; long[] primes = new long[to + 1]; all[1] = 1; int primesLength = 0; for (int i = 2; i <= to; i++) { if (all[i] == 0) { primes[primesLength++] = i; all[i] = i; } for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j]; j++) { all[(int) (i * primes[j])] = primes[j]; } } return Arrays.copyOf(primes, primesLength); } static long modpow(long b, long e, long m) { long result = 1; while (e > 0) { if ((e & 1) == 1) { /* multiply in this bit's contribution while using modulus to keep * result small */ result = (result * b) % m; } b = (b * b) % m; e >>= 1; } return result; } static long submod(long x, long y, long m) { return (x - y + m) % m; } static long modInverse(long a, long m) { long g = gcdF(a, m); if (g != 1) { throw new IllegalArgumentException("Inverse doesn't exist"); } else { // If a and m are relatively prime, then modulo // inverse is a^(m-2) mode m return modpow(a, m - 2, m); } } static public long gcdF(long a, long b) { while (b != 0) { long na = b; long nb = a % b; a = na; b = nb; } return a; } } } /* 5 3 2 3 8 8 2 8 5 10 1 */
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.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader obj = new FastReader(); PrintWriter out = new PrintWriter(System.out); int l = obj.nextInt(); while (l-- != 0) { int n = obj.nextInt(); int[] num = new int[n]; for (int i = 0; i < n; i++) num[i] = obj.nextInt(); Vector<Integer> red = new Vector<>(); Vector<Integer> blue = new Vector<>(); String s = obj.next(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 'R') red.add(num[i]); else blue.add(num[i]); } Collections.sort(blue); Collections.sort(red); int c = 1, f = 0; for (int i = 0; i < blue.size(); i++) { if (blue.get(i) < c) { f = 1; break; } c++; } for (int i = 0; i < red.size(); i++) { if (red.get(i) > c) { f = 1; break; } c++; } if (f == 0) out.println("YES"); else out.println("NO"); } out.flush(); } }
1
7814575b
8cfe3ee0
import java.io.*; import java.util.*; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; public class C { static int fval(String s, char x){ int fx = 0, oth = 0; for(int i = 0; i<s.length(); i++){ if(x == s.charAt(i)) fx++; else oth++; } return fx-oth; } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); //int tst = 1; int tst = Integer.parseInt(br.readLine()); long mod = (long)1e9+7; while(tst-->0){ int n = Integer.parseInt(br.readLine()); ArrayList<String> lst = new ArrayList<>(); for(int i = 0; i<n; i++){ lst.add(br.readLine()); } int ans = 0; for(int i = 0; i<5; i++){ char x = (char)(97+i); ArrayList<Integer> vals = new ArrayList<>(); for(int j = 0; j<n; j++){ vals.add(fval(lst.get(j), x)); } Collections.sort(vals, Collections.reverseOrder()); int pt = -1, sum = 0; while(pt+1<n && sum+vals.get(pt+1)>0){ sum+=vals.get(++pt); } ans = max(ans, pt+1); } sb.append(ans).append('\n'); } System.out.println(sb); } } /** * min deletions * for each letter calc max len of words * Its desirable to add someting that has more of x and less of other letters -> f(x, s)=>fx-sum(fz) */
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class Comprog { static FastReader fr = new FastReader(); private static void testCase() { int n = fr.nextInt(); int [][] scoreChanges = new int [5][n]; int [] totalScores = new int [5]; // initialize for (int i = 0; i < 5; i++) totalScores[i] = 0; for (int i = 0; i < 5; i++) for (int j = 0; j < n; j++) scoreChanges[i][j] = 0; for (int wordIndex = 0; wordIndex < n; wordIndex++) { String nextWord = fr.nextLine(); for (int charIndex = 0; charIndex < 5; charIndex++) { // How many more of the current char ('a' or 'b' or etc.) are in nextWord than // the total number of chars in it int change = 2 * countCharsInString(nextWord, (char) ('a' + charIndex)) - nextWord.length(); totalScores[charIndex] += change; scoreChanges[charIndex][wordIndex] = change; } } for (int charIndex = 0; charIndex < 5; charIndex++) Arrays.sort(scoreChanges[charIndex]); int round = 0; boolean done = false; while (round < n && !done) { for (int charIndex = 0; charIndex < 5; charIndex++) { if (totalScores[charIndex] > 0) { System.out.println(n - round); done = true; break; } totalScores[charIndex] -= scoreChanges[charIndex][round]; } round++; } if (!done) System.out.println(0); } public static int countCharsInString(String str, char c) { int cnt = 0; for (int i = 0; i < str.length(); i++) if (str.charAt(i) == c) cnt++; return cnt; } public static void main(String[] args) { int t; t = fr.nextInt(); for (int i = 0; i < t; i++) testCase(); } static class NumberFrequency { int number; int frequency; public NumberFrequency(int number, int frequency) { this.number = number; this.frequency = frequency; } public void incrementFrequency() { this.frequency++; } } static class SortByFrequency implements Comparator<NumberFrequency> { public int compare(NumberFrequency nf1, NumberFrequency nf2) { return nf2.frequency - nf1.frequency; } } 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; } } }
0
b5da712b
dd994c01
import java.io.*; import java.util.*; public class codeforces2 { static List<Integer> primes; static final long X = 10000000000L; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); // primes = sieveOfEratosthenes(100_000); // System.out.println(primes.toString()); int tc = sc.ni(); // int tc = 1; for (int rep = 0; rep < tc; rep++) { int N = sc.ni(); int[][] edges= new int[N-1][]; for (int i = 0; i < edges.length; i++) { edges[i] = new int[] {sc.ni() - 1, sc.ni() - 1}; } pw.println(solve(edges, N)); } pw.close(); } public static String solve(int[][] edges, int N) { Map<Integer, Set<Integer>> graph = new HashMap(); Map<Long, Integer> hash = new HashMap(); int idx = 0; for (int[] e : edges) { graph.putIfAbsent(e[0], new HashSet()); graph.get(e[0]).add(e[1]); graph.putIfAbsent(e[1], new HashSet()); graph.get(e[1]).add(e[0]); hash.put(getHash(e[0], e[1]), idx); idx++; } Queue<int[]> q = new LinkedList(); //node, previous weight int[] initial = new int[2]; for (int node : graph.keySet()) { int len = graph.get(node).size(); if (len > 2) return "-1"; if (len == 2) initial = new int[] {node, -1}; } q.offer(initial); int rotate = 0; // System.out.println(graph.toString()); int[] ret = new int[edges.length]; boolean[] vis = new boolean[N]; vis[initial[0]] = true; while (!q.isEmpty()) { int[] temp = q.poll(); int node = temp[0]; int old_color = temp[1]; if (old_color == -1) { int[] arr = new int[] {2, 11}; int p = 0; for (int neighbor : graph.get(node)) { ret[hash.get( getHash(node,neighbor) )] = arr[p]; q.offer(new int[] {neighbor, arr[p]}); p++; // System.out.println(); // System.out.println(neighbor + " " + graph.toString()); // System.out.println(Arrays.deepToString(edges)); vis[neighbor] = true; } } else if (old_color == 2) { int amt = 0; for (int neighbor : graph.get(node)) { if (vis[neighbor] == true) continue; vis[neighbor] = true; ret[hash.get( getHash(node,neighbor) )] = 11; q.offer(new int[] {neighbor, 11}); amt++; } if (amt >= 2) return "-1"; } else { int amt = 0; for (int neighbor : graph.get(node)) { if (vis[neighbor] == true) continue; vis[neighbor] = true; ret[hash.get( getHash(node,neighbor) )] = 2; q.offer(new int[] {neighbor, 2}); amt++; } if (amt >= 2) return "-1"; } } StringBuilder sb = new StringBuilder(); for (int x : ret) sb.append(x + " "); return sb.substring(0, sb.length() -1); } static long getHash(int u, int v) { if (u > v) { int temp = u; u = v; v = temp; } return u*X+v; } static boolean isSet(long n, int bit) { if (((1 << bit) & n) > 0) return true; return false; } static long nextPrime(long input){ long counter; input++; while(true){ int l = (int) Math.sqrt(input); counter = 0; for(long i = 2; i <= l; i ++){ if(input % i == 0) counter++; } if(counter == 0) return input; else{ input++; continue; } } } public static List<Integer> sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { if (prime[p]) { for (int i = p * 2; i <= n; i += p) { prime[i] = false; } } } List<Integer> primeNumbers = new LinkedList<>(); for (int i = 2; i <= n; i++) { if (prime[i]) { primeNumbers.add(i); } } return primeNumbers; } public static boolean perfectSquare(long n) { long lo = 0; long hi = n; while (lo < hi) { long k = (lo + hi) / 2; if (k * k < n) lo = k + 1; else hi = k; } return (lo * lo == n); } static Set<Integer> divisors(int n) { Set<Integer> set = new HashSet(); for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { // If divisors are equal, print only one if (n/i == i) set.add(i); else {// Otherwise print both set.add(i); set.add(n / i); } } } return set; } static Map<Integer, Integer> primeFactorization(int x) { //first divide by 2 Map<Integer, Integer> map = new HashMap(); if (x == 0) return map; int count = 0; while (x % 2 == 0) { x /=2; count++; } //insert 2 if (count > 0) map.put(2, count); for (int divisor = 3; divisor * divisor <= x; divisor += 2) { int cnt = 0; while (x % divisor == 0) { x /= divisor; cnt++; } if (cnt > 0) map.put(divisor, cnt); } if (x > 1) { map.put(x, 1); } return map; } static boolean isPrime(int n) { // Check if number is less than // equal to 1 if (n <= 1) return false; // Check if number is 2 else if (n == 2) return true; // Check if n is a multiple of 2 else if (n % 2 == 0) return false; // If not, then just check the odds for (int i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } // method to return LCM of two numbers static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } public static void sort(int[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); int temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } public static void sort(long[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); long temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } /* */ //printing methods /* */ //WOW! /* */ public static void printArr(PrintWriter pw, int[] arr) { StringBuilder sb = new StringBuilder(); for (int x : arr) { sb.append(x + ""); } sb.setLength(sb.length() - 1); pw.println(sb.toString()); } public static void printArr2d(PrintWriter pw, int[][] arr) { StringBuilder sb = new StringBuilder(); for (int[] row : arr) { for (int x : row) { sb.append(x + " "); } sb.setLength(sb.length() - 1); sb.append("\n"); } sb.setLength(sb.length() - 1); pw.println(sb.toString()); } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[] intArray(int N) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = ni(); return ret; } long nl() { return Long.parseLong(next()); } long[] longArray(int N) { long[] ret = new long[N]; for (int i = 0; i < N; i++) ret[i] = nl(); return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } class UnionFind { int size; private int[] id; public UnionFind(int size) { this.size = size; id = new int[size]; for (int i = 0; i < id.length; i++) { id[i] = i; } } public int find(int a) { if (id[a] != a) { id[a] = find(id[a]); } return id[a]; } public void union(int a, int b) { int r1 = find(a); int r2 = find(b); if (r1 == r2) return; size--; id[r1] = r2; } @Override public String toString() { return Arrays.toString(id); } } class isSame { private long[] arr; TreeMap<Integer, Integer> map = new TreeMap(); public isSame(long[] in) { arr = in; int prev = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] == arr[i-1]) { } else { map.put(prev, i-1); prev = i; } } map.put(prev, arr.length - 1); } public boolean query(int l, int r) { Integer lower = map.floorKey(l); //should never happen i think if (lower == null) return false; return map.get(lower) >= r; } @Override public String toString() { return map.toString(); } }
//package codeforces.round766div2; import java.io.*; import java.util.*; import static java.lang.Math.*; public class C { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); solve(in.nextInt()); //solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static int n; static List<int[]>[] adj; static int[] ans; static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { n = in.nextInt(); adj = new List[n + 1]; for(int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } ans = new int[n - 1]; for(int i = 0; i < n - 1; i++) { int u = in.nextInt(), v = in.nextInt(); adj[u].add(new int[]{v, i}); adj[v].add(new int[]{u, i}); } if(adj[1].size() > 2) out.println(-1); else { boolean can = false; if(adj[1].size() == 1) { ans[adj[1].get(0)[1]] = 2; if(dfs(adj[1].get(0)[0], 1, 2)) { can = true; } } else { ans[adj[1].get(0)[1]] = 2; ans[adj[1].get(1)[1]] = 3; if(dfs(adj[1].get(0)[0] ,1, 2) && dfs(adj[1].get(1)[0], 1, 3)) { can = true; } } if(can) { for(int v : ans) out.print(v + " "); out.println(); } else out.println(-1); } } out.close(); } static boolean dfs(int curr, int par, int prev) { if(adj[curr].size() - 1 > 1) return false; for(int[] next : adj[curr]) { if(next[0] == par) continue; ans[next[1]] = prev == 2 ? 3 : 2; if(!dfs(next[0], curr, prev == 2 ? 3 : 2)) { return false; } } return true; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } 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(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<Integer>[] readGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } } }
0
624b8db5
eacc407e
//created by Whiplash99 import java.io.*; import java.util.*; public class C { private static ArrayDeque<Integer>[] edge; private static HashMap<String,Integer> map; private static String getHash(int u, int v) { if(u>v) { int tmp=u; u=v; v=tmp; } return u+" "+v; } private static void DFS(int u, int p, int[] ans, int val) { for(int v:edge[u]) { if(v==p) continue; ans[map.get(getHash(u,v))]=val; DFS(v,u,ans,5-val); val=5-val; } } public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,N; int T=Integer.parseInt(br.readLine().trim()); StringBuilder sb=new StringBuilder(); while (T-->0) { N=Integer.parseInt(br.readLine().trim()); edge=new ArrayDeque[N]; for(i=0;i<N;i++) edge[i]=new ArrayDeque<>(); map=new HashMap<>(); int[] ans=new int[N-1]; int[] deg=new int[N]; for(i=0;i<N-1;i++) { String[] 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); deg[u]++; deg[v]++; map.put(getHash(u,v),i); } for(i=0;i<N;i++) if(deg[i]>2) break; if(i<N) { sb.append(-1).append("\n"); continue; } DFS(0,0,ans,2); for(int x:ans) sb.append(x).append(" "); sb.append("\n"); } System.out.println(sb); } }
import java.io.*; import java.util.*; public class A { static ArrayList<int[]>[] adj; static int[] vals = { 2, 11 }; static int[] res; static void dfs(int u, int p, int par) { for (int[] nxt : adj[u]) { int v = nxt[0]; int idx = nxt[1]; if (v != p) { res[idx] = vals[par]; dfs(v, u, 1 ^ par); } } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); res = new int[n - 1]; adj = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<int[]>(); } for (int i = 0; i < n - 1; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; adj[u].add(new int[] { v, i }); adj[v].add(new int[] { u, i }); } boolean valid = true; int start = 0; for (int i = 0; i < n; i++) { if (adj[i].size() == 1) start = i; valid &= adj[i].size() <= 2; } dfs(start, -1, 0); if (valid) { for (int x : res) pw.print(x + " "); } else { pw.print(-1); } pw.println(); } pw.flush(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
0
375489f2
a4c98ae1
import java.io.*; import java.util.*; public class Main { static class FastInput { BufferedReader br; StringTokenizer st; public FastInput() { 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 long gcd(long a, long b) { if (b > a) return gcd(b, a); if (b == 0) return a; return gcd(b, a % b); } public static void plist(ArrayList<Integer> arr) { for (int i = 0; i < arr.size(); i++) { System.out.print(arr.get(i) + " "); } System.out.println(); } static long[][] dp = new long[5005][5005]; static ArrayList<Integer> filled = new ArrayList<>(); static ArrayList<Integer> vacant = new ArrayList<>(); public static long calc(int i, int j){ if(i >= filled.size()) return 0; if(j >= vacant.size()) return Integer.MAX_VALUE; if(dp[i][j] != -1) return dp[i][j]; dp[i][j] = Math.min(Math.abs(filled.get(i) - vacant.get(j)) + calc(i+1, j+1), calc(i, j+1)); return dp[i][j]; } public static void run_case(FastInput s) { int n = s.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++){ arr[i] = s.nextInt(); if(arr[i] == 1){ filled.add(i); } else { vacant.add(i); } } for(int i = 0; i < filled.size(); i++){ for(int j = 0; j < vacant.size(); j++) dp[i][j] = -1; } System.out.println(calc(0, 0)); } public static void main(String[] args) { FastInput s = new FastInput(); run_case(s); } }
import java.io.*; import java.util.*; public class Main { static ArrayList<Integer> one=new ArrayList<>(); static ArrayList<Integer> zero=new ArrayList<>(); static long dp[][]= new long[5001][5001]; static long solve(int i,int j){ if (i==one.size())return 0; if (j==zero.size())return Integer.MAX_VALUE; if (dp[i][j]!=-1){ return dp[i][j]; } return dp[i][j]=Math.min(solve(i+1,j+1)+Math.abs(one.get(i)-zero.get(j)),solve(i,j+1)); } public static void main(String[] args) { FastScanner sc = new FastScanner(); // int t=sc.nextInt(); // while (t-->=1){ int n=sc.nextInt(); int a[]=sc.readArray(n); for (long i[]:dp){ Arrays.fill(i,-1); } for (int i=0;i<n;i++){ if (a[i]==1)one.add(i); else zero.add(i); } Collections.sort(one); Collections.sort(zero); System.out.println(solve(0,0)); } // out.flush(); //------------------------------------if------------------------------------------------------------------------------------------------------------------------------------------------- //sieve static void primeSieve(int a[]){ //mark all odd number as prime for (int i=3;i<a.length;i+=2){ a[i]=1; } for (long i=3;i<a.length;i+=2){ //if the number is marked then it is prime if (a[(int) i]==1){ //mark all muliple of the number as not prime for (long j=i*i;j<a.length;j+=i){ a[(int)j]=0; } } } a[2]=1; a[1]=a[0]=0; } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static String sortString(String s) { char temp[] = s.toCharArray(); Arrays.sort(temp); return new String(temp); } static class Pair implements Comparable<Pair> { String a; int b; public Pair(String a, int b) { this.a = a; this.b = b; } // to sort first part // public int compareTo(Pair other) { // if (this.a == other.a) return other.b > this.b ? -1 : 1; // else if (this.a > other.a) return 1; // else return -1; // } public int compareTo(Pair other) { // if (this.b == other.b) return 0; if (this.b > other.b) return 1; else return -1; } //sort on the basis of first part only // public int compareTo(Pair other) { // if (this.a == other.a) return 0; // else if (this.a > other.a) return 1; // else return -1; // } } static int[] frequency(String s){ int fre[]= new int[26]; for (int i=0;i<s.length();i++){ fre[s.charAt(i)-'a']++; } return fre; } static long LOWERBOUND(long a[],long k){ int s=0,e=a.length-1; long ans=-1; while (s<=e){ int mid=(s+e)/2; if (a[mid]<=k){ ans=mid; s=mid+1; } else { e=mid-1; } } return ans; } static long mod =(long)(1e9+7); static long mod(long x) { return ((x % mod + mod) % mod); } static long div(long a,long b){ return ((a/b)%mod+mod)%mod; } static long add(long x, long y) { return mod(mod(x) + mod(y)); } static long mul(long x, long y) { return mod(mod(x) * mod(y)); } //Fast Power(logN) static int fastPower(long a,long n){ int ans=1; while (n>0){ long lastBit=n&1; if (lastBit==1){ ans=(int)mul(ans,a); } a=(int)mul(a,a); n>>=1; } return ans; } static int[] find(int n, int start, int diff) { int a[] = new int[n]; a[0] = start; for (int i = 1; i < n; i++) a[i] = a[i - 1] + diff; return a; } static void swap(int a, int b) { int c = a; a = b; b = c; } static void printArray(int a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } static boolean sorted(int a[]) { int n = a.length; boolean flag = true; for (int i = 0; i < n - 1; i++) { if (a[i] > a[i + 1]) flag = false; } if (flag) return true; else return false; } public static int findlog(long n) { if (n == 0) return 0; if (n == 1) return 0; if (n == 2) return 1; double num = Math.log(n); double den = Math.log(2); if (den == 0) return 0; return (int) (num / den); } public static long gcd(long a, long b) { if (b % a == 0) return a; return gcd(b % a, a); } public static int gcdInt(int a, int b) { if (b % a == 0) return a; return gcdInt(b % a, a); } static void sortReverse(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); // Collections.sort.(l); Collections.sort(l, Collections.reverseOrder()); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readArrayLong(long n) { long[] a = new long[(int) n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } }
0
7d9b95c0
9d33ca79
import java.util.*; import java.math.*; public class Main { public static class Edge{ int u; int v; // int wt; Edge(int u, int v){ this.u = u; this.v = v; // this.wt = wt; } } public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); StringBuilder sb = new StringBuilder(""); for(int A=0 ; A<t ; A++) { int n = scn.nextInt(); List<Edge>[] graph = new ArrayList[n]; for(int i=0 ; i<n ; i++) { graph[i] = new ArrayList<>(); } String[] arr = new String[n-1]; for(int i=0 ; i<n-1 ; i++) { int u = scn.nextInt(); int v = scn.nextInt(); arr[i] = (u-1) + " " + (v-1); graph[u-1].add(new Edge(u-1, v-1)); graph[v-1].add(new Edge(v-1, u-1)); } boolean flag = false; int src = 0; for(int i=0 ; i<n ; i++) { if(graph[i].size() > 2) { flag = true; }else if(graph[i].size() == 1) src = i; } if(flag) { sb.append(-1 + "\n"); }else { Map<String, Integer> hm = new HashMap<>(); int count = 0; int val = 2; // System.out.println(src); while(count < n) { List<Edge> e = graph[src]; int i=0; while(i < e.size() && hm.containsKey(src + " " + e.get(i).v)) i++; if(i < e.size()) { int nbr = e.get(i).v; // System.out.println(src + " " + nbr); hm.put(src + " " + nbr, val); hm.put(nbr + " " + src, val); val = 5 - val; src = nbr; } count++; } for(int i=0 ; i<arr.length ; i++) { int wt = hm.get(arr[i]); sb.append(wt + " "); } sb.append("\n"); } } System.out.println(sb); } }
import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; import java.util.TreeMap; public class NotAssigning { static ArrayList<Integer>[]adj; static boolean vis []; static int edges[]; // we need to check that every path of length 1 or 2 must be a prime number // Idea--> we will only use 2 , 3 for the weight assignment // no assignment will be valid if there exists a node connected to 3 others public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); vis= new boolean [n]; adj= new ArrayList[n]; TreeMap<Integer,Pair> idx = new TreeMap<>(); TreeMap<Pair,Integer> w= new TreeMap<>(); boolean notValid = false; for(int i =0;i<n;i++){ adj[i]= new ArrayList<>(); } for(int i =1;i<n;i++){ int u = sc.nextInt()-1; int v = sc.nextInt()-1; int max = Math.max(u,v); int min = Math.min(u,v); idx.put(i,new Pair(min , max)); adj[u].add(v); adj[v].add(u); if(adj[u].size()>2||adj[v].size()>2)notValid=true; } if(notValid){ pw.println(-1); continue; } dfs(0,2,w); // vis[0]=true; // dfs(adj[0].get(0),2,w); // if(adj[0].size()==2)dfs(adj[0].get(1),3,w); for(int i =1;i<n;i++){ pw.print(w.get(idx.get(i))+" "); } pw.println(); } pw.close(); } static void dfs(int node , int w , TreeMap<Pair , Integer>weight){ vis[node]=true; int i =0; for(int x : adj[node]){ if(!vis[x]) { int min = Math.min(x , node); int max = Math.max(x , node); if(i%2==0){ weight.put(new Pair(min , max),w); dfs(x, 5-w,weight); } else{ weight.put(new Pair(min , max),5-w); dfs(x, w, weight); } i++; } } } static class Pair implements Comparable<Pair>{ int x; int y ; Pair(int x , int y ){ this.x=x; this.y=y; } @Override public int compareTo(Pair o) { if(this.x==o.x)return this.y-o.y; return this.x-o.x; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } }
0
08cf0478
0f14b12d
import java.util.*; import java.io.*; public class Main { static class Pair { int fi; int se; public Pair(int fi, int se) { this.fi = fi; this.se = se; } } public static void main(final String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int[][] arr = new int[5][n]; for(int i = 0; i < n; i++) { char[] s = sc.next().toCharArray(); int[] cnt = new int[5]; for(int j = 0; j < s.length; j++) { cnt[s[j]-'a']++; } for(int j = 0; j < 5; j++) arr[j][i] = cnt[j]-(s.length-cnt[j]); } int ans = 0; for(int i = 0; i < 5; i++) { Arrays.sort(arr[i]); int maxSum = 0; int words = 0; for(int j = arr[i].length-1; j >=0; j--) { maxSum += arr[i][j]; if(maxSum > 0) words++; } ans = Math.max(ans, words); } System.out.println(ans); } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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;} } }
//import jdk.nashorn.internal.parser.Scanner; import java.io.BufferedReader; import java.io.IOException; import java.io.*; import java.util.*; import javax.management.Query; public class Test{ public static void main(String[] args) throws IOException, InterruptedException{ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); String [] words = new String[n]; int [] occ = new int[5]; int [] occWord = new int [5]; boolean [] found ; for(int i =0;i<n;i++){ words[i] = sc.nextLine(); found = new boolean[5]; for(int j=0 ; j<words[i].length();j++){ occ[words[i].charAt(j)-'a']++; if(!found[words[i].charAt(j)-'a']){ found[words[i].charAt(j)-'a']=true; occWord[words[i].charAt(j)-'a'] ++; } } } int maxRes =0; for(int i =0;i<5;i++){ int maxChar = 'a' +i; PriorityQueue<Pair> pq = new PriorityQueue<>(); for (String word : words){ pq.add(new Pair(word,occOfMaxChar(word, maxChar)-occOfOtherChar(word, maxChar))); } int res = 0; int curr = 0; int maxCharCount = 0; int otherCharCount =0; while(!pq.isEmpty()){ String word = pq.poll().x; maxCharCount +=occOfMaxChar(word, maxChar); otherCharCount += occOfOtherChar(word, maxChar); curr ++; if(maxCharCount >otherCharCount){ res = curr; } } maxRes = Math.max(maxRes, res); } System.out.println(maxRes);} } public static int occOfMaxChar (String s, int maxChar){ int occ = 0; for(int i =0 ;i<s.length();i++){ if(s.charAt(i)==maxChar){ occ++; } } return occ; } public static int occOfOtherChar (String s, int maxChar){ int occ = 0; for(int i =0 ;i<s.length();i++){ if(s.charAt(i)!=maxChar){ occ++; } } return occ; } static int w; static int n; static long [][] memo; static int [] depth ; static long[] values; static ArrayList<Pair> gold ; public static long dp (int idx,int time){ if ( idx == n){ return 0; } if (memo[idx][time] != -1){ return memo[idx][time]; } long take = 0; if (3 * w*depth[idx] <= time){ take = values[idx]+ dp(idx+1, time-3*w*depth[idx]); } long leave = dp(idx+1, time); return memo[idx][time]=Math.max(take, leave); } static class Pair implements Comparable { String x; int y; public Pair (String x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Object o){ Pair p = (Pair) o; return p.y -y; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public boolean hasNext() { // TODO Auto-generated method stub return false; } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
0
856a8eda
a3e272af
/*input 2 5 2 3 1 2 3 1 2 4 3 3 1 1 2 3 */ import java.io.*; import java.util.*; public class three{ public static class Pair implements Comparable<Pair>{ int min; int idx; @Override public int compareTo(Pair o) { return min - o.min; } } public static void main(String[] args) throws Exception { MyScanner scn = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); /* int n = sc.nextInt(); // read input as integer long k = sc.nextLong(); // read input as long double d = sc.nextDouble(); // read input as double String str = sc.next(); // read input as String String s = sc.nextLine(); // read whole line as String int result = 3*n; out.println(result); // print via PrintWriter */ //The Code Starts here int t = scn.nextInt(); while(t-- > 0){ int n = scn.nextInt(); int m = scn.nextInt(); int x = scn.nextInt(); int arr[] = scn.nextIntArray(n); PriorityQueue<Pair> pq = new PriorityQueue<>(); System.out.println("YES"); for(int i=0;i<m;i++){ Pair p = new Pair(); p.min = arr[i]; p.idx = i+1; pq.add(p); System.out.print(p.idx + " "); } for(int i=m;i<n;i++){ Pair p = pq.peek(); int mini = p.min; int index = p.idx; System.out.print(index + " "); pq.remove(); Pair np = new Pair(); np.min = arr[i] + mini; np.idx = index; pq.add(np); } System.out.println(); } //The Code Ends here out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } 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 int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public int[][] nextInt2DArray(int m, int n) { int[][] arr = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) arr[i][j] = nextInt(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } // public static class Pair implements Comparable<Pair> { // long u; // long v; // public Pair(long u, long v) { // this.u = u; // this.v = v; // } // public int hashCode() { // int hu = (int) (u ^ (u >>> 32)); // int hv = (int) (v ^ (v >>> 32)); // return 31 * hu + hv; // } // public boolean equals(Object o) { // Pair other = (Pair) o; // return u == other.u && v == other.v; // } // public int compareTo(Pair other) { // return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v); // } // public String toString() { // return "[u=" + u + ", v=" + v + "]"; // } // } //-------------------------------------------------------- }
import java.io.*; import java.util.*; public class Asd { static PrintWriter w = new PrintWriter(System.out); static FastScanner s = new FastScanner(); static boolean sd = false; public static void main(String[] args) { int t = s.nextInt(); //int t=1; while (t-- > 0) { solve(); } w.close(); } public static class Student { public int i1; public int value; // A parameterized student constructor public Student(int i1,int i2) { this.i1 = i1; this.value=i2; } public int getkey() { return i1; } public int getValue() { return value; } } static class StudentComparator implements Comparator<Student>{ // Overriding compare()method of Comparator // for descending order of cgpa @Override public int compare(Student s1, Student s2) { if (s1.i1 < s2.i1) return -1; else if (s1.i1 >s2.i1) return 1; return 0; } } /* Function to print all the permutations of the string static String swap(String str, int i, int j) { char ch; char[] array = str.toCharArray(); ch = array[i]; array[i] = array[j]; array[j] = ch; return String.valueOf(array); } static void permute(String str,int low,int high) { if(low == high) list.add(Long.parseLong(str)); int i; for(i = low; i<=high; i++){ str = swap(str,low,i); permute(str, low+1,high); str = swap(str,low,i); } } use permute(str2,0,str2.length()-1); to perform combinations */ public static void solve() { int n=s.nextInt(); int m=s.nextInt(); int x=s.nextInt(); int arr[]=new int[n];int res[]=new int[n]; for(int i=0;i<n;i++) arr[i]=s.nextInt(); PriorityQueue<Student> pq=new PriorityQueue<Student>(new StudentComparator()); for(int i=0;i<m;i++){ pq.add(new Student(arr[i],i));res[i]=i;} for(int i=m;i<n;i++) { Student s1=pq.poll(); int k2=s1.getkey()+arr[i]; int v2=s1.getValue();res[i]=v2; pq.add(new Student(k2,v2)); } w.println("YES"); for(int i=0;i<n;i++) w.print(res[i]+1+" "); w.println(); } static void call(ArrayList<Integer> t, ArrayList<Integer> m) { if (t.size() == 0 && m.size() == 0) { sd = true; return; } t.remove(0); t.remove(t.size() - 1); call(t, new ArrayList<Integer>(m.subList(0, m.size() - 1))); call(t, new ArrayList<Integer>(m.subList(1, m.size()))); } static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } static int noofdivisors(int n) { //it counts no of divisors of every number upto number n int arr[] = new int[n + 1]; for (int i = 1; i <= (n); i++) { for (int j = i; j <= (n); j = j + i) { arr[j]++; } } return arr[0]; } static char[] reverse(char arr[]) { char[] b = new char[arr.length]; int j = arr.length; for (int i = 0; i < arr.length; i++) { b[j - 1] = arr[i]; j = j - 1; } return b; } static long factorial(int n) { long su = 1; for (int i = 1; i <= n; i++) { su *= (long) i; } return su; } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } long[] readArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
0
4a570de6
9852706b
import java.io.*; import java.lang.*; import java.util.*; public class c { static class FastScanner { InputStreamReader is; BufferedReader br; StringTokenizer st; public FastScanner() { is = new InputStreamReader(System.in); br = new BufferedReader(is); } String next() throws Exception { while (st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int ni() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } int[] readArray(int num) throws Exception { int arr[]=new int[num]; for(int i=0;i<num;i++) arr[i]=ni(); return arr; } String nextLine() throws Exception { return br.readLine(); } } public static boolean power_of_two(int a) { if((a&(a-1))==0) { return true; } return false; } static boolean PS(double x) { if (x >= 0) { double i= Math.sqrt(x); if(i%1!=0) { return false; } return ((i * i) == x); } return false; } public static int[] ia(int n) { int ar[]=new int[n]; return ar; } public static long[] la(int n) { long ar[]=new long[n]; return ar; } static class pair implements Comparable<pair>{ int ht; int id; pair(int ht, int id) { this.ht=ht; this.id=id; } public int compareTo(pair p) { return this.ht-p.ht; } } public static void main(String args[]) throws java.lang.Exception { FastScanner sc=new FastScanner(); int t=sc.ni(); while(t-->0) { int n=sc.ni(); int m=sc.ni(); int x=sc.ni(); int ar[]=ia(n); for(int i=0;i<n;i++) { ar[i]=sc.ni(); } System.out.println("YES"); PriorityQueue<pair> pq=new PriorityQueue<>(); for(int i=0;i<m;i++) { pq.add(new pair(0,i+1)); } int i=0; while(i<n) { pair pp=pq.remove(); pp.ht+=ar[i]; System.out.print(pp.id+" "); pq.add(pp); i++; } System.out.println(); } } }
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { static int modulo=998244353; public static void main(String[] args) { FastScanner in = new FastScanner(); int test=in.nextInt(); while(test-->0){ int n=in.nextInt(); int m=in.nextInt(); int x=in.nextInt(); PriorityQueue<pair> pq=new PriorityQueue<>(); int arr[]=new int[n]; for(int i=1;i<=m;i++){ pq.add(new pair(i,0)); } System.out.println("YES"); for(int i=0;i<n;i++){ pair p=pq.poll(); int a=in.nextInt(); p.y+=a; pq.add(p); System.out.print(p.x+" "); } System.out.println(); } // int sum=in.nextInt(); // // boolean dp[][]=new boolean[n+1][sum+1]; // // for(int i=0;i<=n;i++){ // for(int j=0;j<=sum;j++){ // if(i==0) // dp[i][j]=false; // if(j==0) // dp[i][j]=true; // // } // } // // for(int i=1;i<=n;i++){ // for(int j=1;j<=sum;j++){ // if(arr[i-1]<=j) // dp[i][j]=(dp[i-1][j])||(dp[i-1][j-arr[i-1]]); // else // dp[i][j]=dp[i-1][j]; // // } // } // boolean flag=false; // for(int i=0;i<=n;i++){ // if(dp[i][sum]==true){ // flag=true; // System.out.println(1); // break; // } // // } // if(!flag) // System.out.println(0); } public static void solve1(int n,int arr[]){ int b[]=new int[2*n+1]; for(int i=0;i<n;i++){ b[arr[i]]=i+1; } int count=0; for(int i=3;i<2*n;i++){ for(int j=1;j*j<i;j++){ if(i%j==0 && i!=j*j){ if(b[j]+b[i/j]==i){ count++; } } } } System.out.println(count); } public static long modpow(long a, long b){ if(b==0){ return 1; } long x = modpow(a, b/2); x = (x*x)%modulo; if(b%2==1){ return (x*a)%modulo; } return x; } public static long factorial(long n){ if(n==1) return 1; if(n==2) return 2; if(n==3) return 6; return n*factorial(n-1); } public static long benches(int n){ return ncr(n,5)*n*(n-1)*(n-2)*(n-3)*(n-4); } public static long ncr(int n,int r){ long dp[][]=new long[n+1][r+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=Math.min(i,r);j++){ if(j==0 ||j==i) dp[i][j]=1; else{ dp[i][j]=dp[i-1][j]+dp[i-1][j-1]; } } } return dp[n][r]; } public static long select(int n){ return ncr(n,5)+ncr(n,6)+ncr(n,7); } public static long ncr1(int n,int r){ long k=Math.max(r,n-r); long num=1; long den=1; long j=1; for(long i=n;i>k;i--){ num*=i; den*=j; j++; } return num/den; } public static int countDiff(int arr[],int n,int diff){ int sum=0; for(int i=0;i<n;i++){ sum+=arr[i]; } int max=sum/2; boolean dp[][]=new boolean[n+1][max+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=max;j++){ if(i==0) dp[i][j]=false; if(j==0) dp[i][j]=true; } } for(int i=1;i<=n;i++){ for(int j=1;j<=max;j++){ if(arr[i-1]<=j) dp[i][j]=dp[i-1][j]||dp[i-1][j-arr[i-1]]; else dp[i][j]=dp[i-1][j]; } } int min=0; int count=0; for(int j=0;j<=max;j++){ min=0; if(dp[n][j]==true){ min=sum-2*j; if(min==diff) count++; } } return count; } public static int minimumDiff(int arr[],int n){ int sum=0; for(int i=0;i<n;i++){ sum+=arr[i]; } int max=sum/2; boolean dp[][]=new boolean[n+1][max+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=max;j++){ if(i==0) dp[i][j]=false; if(j==0) dp[i][j]=true; } } for(int i=1;i<=n;i++){ for(int j=1;j<=max;j++){ if(arr[i-1]<=j) dp[i][j]=dp[i-1][j]||dp[i-1][j-arr[i-1]]; else dp[i][j]=dp[i-1][j]; } } int min=Integer.MAX_VALUE; for(int j=0;j<=max;j++){ if(dp[n][j]==true){ min=Math.min(min,sum-2*j); } } return min; } public static int findTargetSumWays(int[] nums, int target) { int n=nums.length; int dp[][]=new int[n+1][target+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=target;j++){ if(i==0) dp[i][j]=0; if(j==0) dp[i][j]=1; } } for(int i=1;i<=n;i++){ for(int j=1;j<=target;j++){ if(nums[i-1]<=j) dp[i][j]=dp[i-1][j]+dp[i-1][j-nums[i-1]]; else dp[i][j]=dp[i-1][j]; } } // for(int i=0;i<=n;i++){ // for(int j=0;j<=target;j++){ // System.out.print(dp[i][j]+" "); // } // System.out.println(); // } return dp[n][target]; } static int equalPartition(int n, int arr[],int sum) { int max=sum; boolean dp[][]=new boolean[n+1][max+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=max;j++){ if(i==0) dp[i][j]=false; if(j==0) dp[i][j]=true; } } for(int i=1;i<=n;i++){ for(int j=1;j<=max;j++){ if(arr[i-1]<=j){ dp[i][j]=(dp[i-1][j]||dp[i-1][j-arr[i-1]]); } else{ dp[i][j]=dp[i-1][j]; } } } for(int i=0;i<=n;i++){ for(int j=0;j<=max;j++){ System.out.print(dp[i][j]+" "); } System.out.println(); } int count=0; for(int i=0;i<=n;i++){ if(dp[i][max]==true){ count++; } } return count; } public static long power(long base,long power){ long res=1; while(power!=0){ if(power%2==0){ power/=2; base=(base*base); } else{ power--; res=(res*base); } } return res; } } 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()); } } class pair implements Comparable<pair> { int x; int y; pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(pair o) { return (int)(y-o.y); } }
0
63a24497
6e5ab1d2
import java.util.*; import java.lang.*; import java.io.*; public class Main { void solve() { int n = in.nextInt(); char[] a = in.nextLine().toCharArray(); char[] b = in.nextLine().toCharArray(); int ans = MAX; ans = Math.min(ans, operations(a, b)); ans = Math.min(ans, change(a, b, '1')); ans = Math.min(ans, change(a, b, '0')); if (ans == MAX)ans = -1; out.append(ans + "\n"); } int operations(char[] a, char[] b) { int count01 = 0 , count10 = 0; int n = a.length; for (int i = 0 ; i < n; i++) { if (a[i] != b[i]) { if (a[i] == '0')count01++; else count10++; } } if (count01 != count10)return MAX; return count01 + count10; } int change(char[] a, char[] b , char ch) { int n = a.length; char[] c = new char[n]; for (int i = 0 ; i < n; i++)c[i] = a[i]; int index = -1; for (int i = 0; i < n; i++) { if (c[i] == '1' && b[i] == ch) { index = i; break; } } if (index == -1)return MAX; for (int i = 0 ; i < n; i++) { if (i == index)continue; c[i] = (char)( '0' + ('1' - c[i]) ); } int local = operations(c, b); if (local == MAX)return MAX; return 1 + local; } public static void main (String[] args) { // It happens - Syed Mizbahuddin Main sol = new Main(); int t = 1; t = in.nextInt(); while (t-- != 0) { sol.solve(); } System.out.print(out); } <T> void println(T[] s) { if (err == null)return; err.println(Arrays.toString(s)); } <T> void println(T s) { if (err == null)return; err.println(s); } void println(int s) { if (err == null)return; err.println(s); } void println(int[] a) { if (err == null)return; println(Arrays.toString(a)); } int[] array(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } return a; } int[] array1(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); } return a; } int max(int[] a) { int max = a[0]; for (int i = 0; i < a.length; i++)max = Math.max(max, a[i]); return max; } int min(int[] a) { int min = a[0]; for (int i = 0; i < a.length; i++)min = Math.min(min, a[i]); return min; } int count(int[] a, int x) { int count = 0; for (int i = 0; i < a.length; i++)if (x == a[i])count++; return count; } void printArray(int[] a) { for (int ele : a)out.append(ele + " "); out.append("\n"); } static { try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); err = new PrintStream(new FileOutputStream("error.txt")); } catch (Exception e) {} } static FastReader in; static StringBuilder out; static PrintStream err; final int MAX; final int MIN; int mod ; Main() { in = new FastReader(); out = new StringBuilder(); MAX = Integer.MAX_VALUE; MIN = Integer.MIN_VALUE; mod = (int)1e9 + 7; } 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; } } class Pair implements Comparable<Pair> { int first , second; Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair b) { return this.first - b.first; } public String toString() { String s = "{ " + Integer.toString(first) + " , " + Integer.toString(second) + " }"; return s; } } }
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CMenorah solver = new CMenorah(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class CMenorah { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); char[] a = in.next().toCharArray(); char[] b = in.next().toCharArray(); int ans = checkPairs(a, b, -1); ans = Math.min(ans, changePair(a, b, '1')); ans = Math.min(ans, changePair(a, b, '0')); if (ans == Integer.MAX_VALUE) ans = -1; out.println(ans); } int changePair(char[] a, char[] b, char t) { int index = -1; int n = a.length; for (int i = 0; i < n; ++i) { if (a[i] == '1' && b[i] == t) { index = i; break; } } return checkPairs(a, b, index); } int checkPairs(char[] a, char[] b, int changeStringIndex) { int n = a.length; int val = 0; char[] tmp = new char[n]; System.arraycopy(a, 0, tmp, 0, n); if (changeStringIndex != -1) { val = 1; for (int i = 0; i < n; ++i) { if (i == changeStringIndex) continue; tmp[i] = a[i] == '0' ? '1' : '0'; } } int _10 = 0, _01 = 0; for (int i = 0; i < n; ++i) { if (tmp[i] != b[i]) { if (tmp[i] == '0') _01++; else _10++; } } return _01 == _10 ? 2 * _01 + val : Integer.MAX_VALUE; } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
1
0c0af0ff
d6a8d884
import java.util.*; import java.lang.*; import java.io.*; public class Main { PrintWriter out = new PrintWriter(System.out); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(""); String next() throws IOException { if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } long nl() throws IOException { return Long.parseLong(next()); } long mod=1000000007; void solve() throws IOException { for (int tc=ni();tc>0;tc--) { int n=ni(); int[]A=new int[n]; long[]T=new long[n]; A[0]=ni(); T[0]=A[0]; long total=0; for (int i=1;i<n;i++) { A[i]=ni(); T[i]=T[i-1]+A[i]; } long[]B=new long[n]; long lefteven=n-1; long leftodd=n; int mineven=A[0]; int minodd=A[1]; long ans=Long.MAX_VALUE; for (int i=1;i<n;i++) { if (i%2==1) { leftodd--; minodd=Math.min(minodd,A[i]); B[i]=T[i]+lefteven*mineven+leftodd*minodd; } else { lefteven--; mineven=Math.min(mineven,A[i]); B[i]=T[i]+lefteven*mineven+leftodd*minodd; } ans=Math.min(ans,B[i]); } out.println(ans); } out.flush(); } int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); } long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); } long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; } public static void main(String[] args) throws IOException { new Main().solve(); } }
//Praise our lord and saviour qlf9 //DecimalFormat f = new DecimalFormat("##.00"); import java.util.*; import java.io.*; import java.math.*; import java.text.*; public class C{ public static void main(String[] omkar) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); StringBuilder sb = new StringBuilder(); int cases = Integer.parseInt(st.nextToken()); for(int i = 0; i < cases; i++) { solve(in, st, sb); } System.out.println(sb); } public static void solve(BufferedReader in, StringTokenizer st, StringBuilder sb) throws Exception { st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int[] arr = readArr(n, in, st); int[] mins = new int[n]; mins[0] = arr[0]; mins[1] = arr[1]; for(int i = 2; i < n; i++) { mins[i] = Math.min(arr[i], mins[i-2]); } long[] sums = new long[n]; sums[0] = (long)(arr[0]); for(int i = 1; i < n; i++) { sums[i] = sums[i-1]+(long)(arr[i]); } long minc = Long.MAX_VALUE; long temp; for(int i = 1; i < n; i++) { temp = sums[i]; temp += (long)(mins[i])*(long)(n-(i+2)/2); temp += (long)(mins[i-1])*(long)(n-(i+1)/2); minc = Math.min(minc, temp); } sb.append(minc+"\n"); } public static int[] readArr(int N, BufferedReader in, StringTokenizer st) throws Exception { int[] arr = new int[N]; st = new StringTokenizer(in.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); return arr; } }
0
a7063d01
ac4d0fc5
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.lang.reflect.Array; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } static String reverse(String s) { return (new StringBuilder(s)).reverse().toString(); } static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar) { factors[1]=1; int p; for(p = 2; p*p <=n; p++) { if(factors[p] == 0) { ar.add(p); factors[p]=p; for(int i = p*p; i <= n; i += p) if(factors[i]==0) factors[i] = p; } } for(;p<=n;p++){ if(factors[p] == 0) { factors[p] = p; ar.add(p); } } } static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort2(char ar[]) { int n = ar.length; ArrayList<Character> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } static class SegTree { long tree[]; long lz[]; long r; long combine(long a, long b){ return Math.min(a,b); } void build(long a[], int v, int tl, int tr) { if (tl == tr) { tree[v] = a[tl]; } else { int tm = (tl + tr) / 2; build(a, v*2, tl, tm); build(a, v*2+1, tm+1, tr); tree[v] = combine(tree[2*v], tree[2*v+1]); } } void pointUpdate(int v, int tl, int tr, int pos, long val) { if(tl>pos||tr<pos) return; if(tl==pos&&tr==pos){ tree[v] = val; return; } int tm = ((tl + tr) >> 1); pointUpdate(v*2, tl, tm, pos, val); pointUpdate(v*2+1, tm+1, tr, pos, val); tree[v] = combine(tree[2*v],tree[2*v+1]); } // void push(int v, int tl, int tr){ // if(tl==tr){ // lz[v] = 0; // return; // } // tree[2*v] += lz[v]; // tree[2*v+1] += lz[v]; // lz[2*v] += lz[v]; // lz[2*v+1] += lz[v]; // lz[v] = 0; // } // void rangeUpdate(int v, int tl, int tr, int l, int r, long val) { // if(tl>r||tr<l) // return; // push(v, tl, tr); // if(tl>=l&&tr<=r){ // tree[v] += val; // lz[v] += val; // return; // } // int tm = ((tl + tr) >> 1); // rangeUpdate(v*2, tl, tm, l, r, val); // rangeUpdate(v*2+1, tm+1, tr, l, r, val); // tree[v] = combine(tree[2*v],tree[2*v+1]); // } long get(int v, int tl, int tr, int l, int r, long val) { if(l>tr||r<tl||tree[v]>val){ return 0; } if (tl == tr) { tree[v] = Integer.MAX_VALUE; return 1; } int tm = ((tl + tr) >> 1); long al = get(2*v, tl, tm, l, r, val); long ar = get(2*v+1, tm+1, tr, l, r, val); tree[v] = combine(tree[2*v],tree[2*v+1]); return al+ar; } } static class BIT{ int n; long tree[]; long operate(long el, long val){ return el+val; } void update(int x, long val){ for(;x<n;x+=(x&(-x))){ tree[x] = operate(tree[x], val); } } long get(int x){ long sum = 0; for(;x>0;x-=(x&(-x))){ sum = operate(sum, tree[x]); } return sum; } } static int parent[]; static int rank[]; static long m = 0; static int find_set(int v) { if (v == parent[v]) return v; return find_set(parent[v]); } static void make_set(int v) { parent[v] = v; rank[v] = 1; } static void union_sets(int a, int b) { a = find_set(a); b = find_set(b); if (a != b) { if (rank[a] < rank[b]){ int tmp = a; a = b; b = tmp; } parent[b] = a; // if (rank[a] == rank[b]) // rank[a]++; rank[a] += rank[b]; max1 = Math.max(max1,rank[a]); } } static int parent1[]; static int rank1[]; static int find_set1(int v) { if (v == parent1[v]) return v; return find_set1(parent1[v]); } static void make_set1(int v) { parent1[v] = v; rank1[v] = 1; } static void union_sets1(int a, int b) { a = find_set1(a); b = find_set1(b); if (a != b) { if (rank1[a] < rank1[b]){ int tmp = a; a = b; b = tmp; } parent1[b] = a; // if (rank1[a] == rank1[b]) // rank1[a]++; rank1[a] += rank1[b]; } } static long max1 = 0; static int count = 0; static int count1 = 0; static boolean possible; public static void solve(InputReader sc, PrintWriter pw){ int i, j = 0; // int t = 1; long mod = 1000000007; // int factors[] = new int[1000001]; // ArrayList<Integer> ar = new ArrayList<>(); // sieveOfEratosthenes(1000000, factors, ar); // HashSet<Integer> set = new HashSet<>(); // for(int x:ar){ // set.add(x); // } int t = sc.nextInt(); u: while (t-- > 0) { int n = sc.nextInt(); int e[][] = new int[n-1][2]; int x[] = new int[n]; int m = 0; for(i=0;i<n-1;i++){ e[i][0] = sc.nextInt()-1; e[i][1] = sc.nextInt()-1; x[e[i][0]]++; x[e[i][1]]++; m = Math.max(x[e[i][0]],m); m = Math.max(x[e[i][1]],m); } if(m>2) pw.println(-1); else{ if(n==2){ pw.println(2); } else if(n==3){ pw.println(2+" "+3); } else{ int d = 0; int ans[] = new int[n-1]; ArrayList<Integer> ar[] = new ArrayList[n]; ArrayList<Integer> ar1[] = new ArrayList[n]; for(i=0;i<n;i++){ ar[i] = new ArrayList<>(); ar1[i] = new ArrayList<>(); } for(i=0;i<n-1;i++){ int a = e[i][0]; int b = e[i][1]; ar[a].add(b); ar1[a].add(i); ar[b].add(a); ar1[b].add(i); if(x[a]==1) d = a; if(x[b]==1) d = b; } visit(d,ar,ar1,ans,-1,2); for(i=0;i<n-1;i++){ pw.print(ans[i]+" "); } pw.println(); } } } } static void visit(int d, ArrayList<Integer> ar[], ArrayList<Integer> ar1[], int ans[], int par, int v){ if(ar[d].get(0)!=par){ ans[ar1[d].get(0)] = v; visit(ar[d].get(0), ar, ar1, ans, d, 5-v); return; } if(ar[d].size()==1) return; ans[ar1[d].get(1)] = v; visit(ar[d].get(1), ar, ar1, ans, d, 5-v); } static void KMPSearch(char pat[], char txt[], int pres[]){ int M = pat.length; int N = txt.length; int lps[] = new int[M]; int j = 0; computeLPSArray(pat, M, lps); int i = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { pres[i-1] = 1; j = lps[j - 1]; } else if (i < N && pat[j] != txt[i]) { if (j != 0) j = lps[j - 1]; else i = i + 1; } } } static void computeLPSArray(char pat[], int M, int lps[]) { int len = 0; int i = 1; lps[0] = 0; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = len; i++; } } } } static long[][] matrixMult(long a[][], long b[][], long mod){ int n = a.length; int m = a[0].length; int p = b[0].length; long c[][] = new long[n][p]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ for(int k=0;k<p;k++){ c[i][k] += a[i][j]*b[j][k]; c[i][k] %= mod; } } } return c; } static long[][] exp(long mat[][], long b, long mod){ if(b==0){ int n = mat.length; long res[][] = new long[n][n]; for(int i=0;i<n;i++){ res[i][i] = 1; } return res; } long half[][] = exp(mat, b/2, mod); long res[][] = matrixMult(half, half, mod); if(b%2==1){ res = matrixMult(res, mat, mod); } return res; } static void countPrimeFactors(int num, int a[], HashMap<Integer,Integer> pos){ for(int i=2;i*i<num;i++){ if(num%i==0){ int y = pos.get(i); while(num%i==0){ a[y]++; num/=i; } } } if(num>1){ int y = pos.get(num); a[y]++; } } static void assignAnc(ArrayList<Integer> ar[], int depth[], int sz[], int par[][] ,int curr, int parent, int d){ depth[curr] = d; sz[curr] = 1; par[curr][0] = parent; for(int v:ar[curr]){ if(parent==v) continue; assignAnc(ar, depth, sz, par, v, curr, d+1); sz[curr] += sz[v]; } } static int findLCA(int a, int b, int par[][], int depth[]){ if(depth[a]>depth[b]){ a = a^b; b = a^b; a = a^b; } int diff = depth[b] - depth[a]; for(int i=19;i>=0;i--){ if((diff&(1<<i))>0){ b = par[b][i]; } } if(a==b) return a; for(int i=19;i>=0;i--){ if(par[b][i]!=par[a][i]){ b = par[b][i]; a = par[a][i]; } } return par[a][0]; } static void formArrayForBinaryLifting(int n, int par[][]){ for(int j=1;j<20;j++){ for(int i=0;i<n;i++){ if(par[i][j-1]==-1) continue; par[i][j] = par[par[i][j-1]][j-1]; } } } static long lcm(int a, int b){ return a*b/gcd(a,b); } static class CustomPair { long a[]; CustomPair(long a[]) { this.a = a; } } static class Pair1 implements Comparable<Pair1> { long a; long b; Pair1(long a, long b) { this.a = a; this.b = b; } public int compareTo(Pair1 p) { if(a!=p.a) return (a<p.a?-1:1); return (b<p.b?-1:1); } } static class Pair implements Comparable<Pair> { int a; int b; int c; Pair(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public int compareTo(Pair p) { if(b!=p.b) return (b-p.b); return (a-p.a); } } static class Pair2 implements Comparable<Pair2> { int a; int b; int c; Pair2(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public int compareTo(Pair2 p) { return a-p.a; } } 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; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 9992768); 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()); } } }
import java.io.*; import java.util.*; public class Main { static boolean[] ret; static boolean[] updated; static ArrayList<Integer>[] adjacencyList; static Edge[] edgeList; static class Edge { int start, end, number; public Edge (int _start, int _end, int _number) { start = _start; end = _end; number = _number; } } public static void dfs(int node) { updated[node] = true; for (int next : adjacencyList[edgeList[node].start]) { if (!updated[next]) { ret[next] = !ret[node]; dfs(next); } } for (int next : adjacencyList[edgeList[node].end]) { if (!updated[next]) { ret[next] = !ret[node]; dfs(next); } } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int numCases = Integer.parseInt(br.readLine()); for (int i = 0; i < numCases; i++) { int numVertices = Integer.parseInt(br.readLine()); int[] numEdges = new int[numVertices]; edgeList = new Edge[numVertices - 1]; adjacencyList = new ArrayList[numVertices]; for (int j = 0; j < numVertices; j++) { adjacencyList[j] = new ArrayList<>(); } for (int j = 0; j < numVertices - 1; j++) { StringTokenizer st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()) - 1; int b = Integer.parseInt(st.nextToken()) - 1; edgeList[j] = new Edge(a, b, j); numEdges[a]++; numEdges[b]++; adjacencyList[a].add(j); adjacencyList[b].add(j); } boolean good = true; for (int j = 0; j < numVertices; j++) { if (numEdges[j] > 2) { good = false; break; } } if (!good) { pw.println(-1); } else { ret = new boolean[numVertices - 1]; updated = new boolean[numVertices - 1]; dfs(0); for (boolean b : ret) { if (b) pw.print(5 + " "); else pw.print(2 + " "); } pw.println(); } } br.close(); pw.close(); } }
0
35bb6075
ed728769
/* COLLECTIONS FRAMEWORK TUTORIAL * HashMap .add(key, value) .get(key) .containsKey(key) : true/false .size() */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { static final long M = 1000000007; // use main for only io public static void main(String args[]) { FastReader io = new FastReader(); new Solver().solve(io); } } //class Pair{ // int key;String value; // // public Pair(int key, String value){ // this.key = key; // this.value = value; // } //} class SparseTable{ int dp[][] = new int[300005][20]; int log[] = new int[300005]; public SparseTable(long a[], int n){ for(int i =0;i<n;i++)dp[i][0] = i; for(int i = 1;i < 20;i++){ for(int j = 0;j + (1 << i) < n;j++){ if(a[dp[j][i-1]] < a[dp[j + (1 << (i-1))][i-1]]){ dp[j][i] = dp[j][i-1]; } else{ dp[j][i] = dp[j + (1 << (i - 1))][i-1]; } } } log[1] = 0; for(int i = 2;i <= n;i++){ log[i] = log[i/2] + 1; } } int getMin(int L, int R, long a[]){ if(L > R)return 0; int j = log[R - L + 1]; if(a[dp[L][j]] < a[dp[R - (1 << j) + 1][j]])return dp[L][j]; return dp[R-(1 << j) + 1][j]; } } class Solver { static final int M = 998244353; void solve(FastReader io) { int t = io.nextInt(); while(t-- > 0){ int n = io.nextInt(); String s[] = new String[n]; for(int i = 0;i < n;i++)s[i] = io.nextLine(); int ans = 0; for(int i = 0;i < 5;i++){ int count[] = new int[n]; for(int j = 0;j < n;j++){ int freq = 0; for(int k = 0;k < s[j].length();k++){ // System.out.println(s[j].charAt(k) - 'a'); if((s[j].charAt(k) - 'a') == i){ freq++; } } // System.out.println(i + " " + freq); count[j] = 2*freq - s[j].length(); } Arrays.sort(count); // for(int it : count)System.out.print(it + " "); // System.out.println(); int curr = 0; int j = n - 1; for(;j >= 0 && (curr + count[j] > 0);j--){ curr += count[j]; } ans = Math.max(ans, n - j - 1); } System.out.println(ans); } } // returns the first key greater than or equal to val int lower_bound(int a[], int val) { int low = 0, high = a.length - 1, ret = -1; while (low <= high) { int mid = (low + high) / 2; if (a[mid] < val) low = mid + 1; else { ret = mid; high = mid - 1; } } return ret; } // returns the first key strictly greater than val int upper_bound(int a[], int val) { int low = 0, high = a.length - 1, ret = -1; while (low <= high) { int mid = (low + high) / 2; if (a[mid] <= val) low = mid + 1; else { ret = mid; high = mid - 1; } } return ret; } long modexp(long n, int m) { if (m == 0) return 1; else if (m == 1) return n; else { long p = modexp(n, m / 2); if (m % 2 == 1) return (((p * p) % M) * n) % M; else return (p * p) % M; } } long exp(long n, long m) { if (m == 0) return 1; if (m == 1) return n; long p = exp(n, m / 2); if (m % 2 == 1) return p * p * n; else return p * p; } long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } long inv(long n) { return modexp(n, M - 2); } long lcm(long a, long b) { return a * b / gcd(a, b); } long factorial(long fact[], int n) { fact[0] = 1; fact[1] = 1; long prod = 1; for (int i = 2; i <= n; i++) { prod = (prod * i) % M; fact[i] = prod; } return prod; } boolean isPrime(long n) { for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } } 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; } }
import java.util.*; import java.io.*; public class Solution { 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') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static int parent(int a , int p[]) { if(a == p[a]) return a; return p[a] = parent(p[a],p); } static void union(int a , int b , int p[] , int size[]) { a = parent(a,p); b = parent(b,p); if(a == b) return; if(size[a] < size[b]) { int temp = a; a = b; b = temp; } p[b] = a; size[a] += size[b]; } static long dp[][]; static long f(int n , int m) { if(m == 0) return 1; if(dp[n][m] != -1) return dp[n][m]; if(n < 9) dp[n][m] = f(n+1,m-1); else dp[n][m] = f(0,m-1)+f(1,m-1); dp[n][m] %= 1000000007; return dp[n][m]; } static long getSum(int index , long BITree[]) { long sum = 0; // Iniialize result // index in BITree[] is 1 more than // the index in arr[] // index = index + 1; // Traverse ancestors of BITree[index] while(index>0) { // Add current element of BITree // to sum sum += BITree[index]; // Move index to parent node in // getSum View index -= index & (-index); } return sum; } // Updates a node in Binary Index Tree (BITree) // at given index in BITree. The given value // 'val' is added to BITree[i] and all of // its ancestors in tree. public static void updateBIT(int n, int index, long val , long BITree[]) { // index in BITree[] is 1 more than // the index in arr[] // index = index + 1; // Traverse all ancestors and add 'val' while(index <= n) { // Add 'val' to current node of BIT Tree BITree[index] += val; // Update index to that of parent // in update View index += index & (-index); } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public static void main(String []args) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); // sc.nextLine(); while(t-- > 0) { int n = sc.nextInt(); sc.nextLine(); //String s = sc.nextLine(); int arr[][] = new int[26][n]; for(int i = 0 ; i < n ; i++) { String s = sc.nextLine(); for(int j = 0 ; j < 26 ; j++) { int cnt = 0; for(int k = 0 ; k < s.length() ; k++) { if(s.charAt(k)-'a' == j) cnt++; } arr[j][i] = 2*cnt-s.length(); } } int ans = 0; for(int i = 0 ; i < 26 ; i++) { Arrays.sort(arr[i]); int tot = 0; for(int j = n-1 ; j >= 0 ;j--) { tot += arr[i][j]; if(tot <= 0) break; ans = Math.max(ans,n-j); } } System.out.println(ans); } } }
0
a7e7f371
f8e7b886
import java.io.*; import java.util.*; public class cp { static int mod=(int)1e9+7; // static Reader sc=new Reader(); static FastReader sc=new FastReader(System.in); static int[] sp; static int size=(int)1e6; static int[] arInt; static long[] arLong; public static void main(String[] args) throws IOException { long tc=sc.nextLong(); // Scanner sc=new Scanner(System.in); // int tc=1; // primeSet=new HashSet<>(); // sieveOfEratosthenes((int)1e6+5); while(tc-->0) { int n=sc.nextInt(); int k[]=new int[n]; int h[]=new int[n]; for(int i=0;i<n;i++) k[i]=sc.nextInt(); for(int i=0;i<n;i++) h[i]=sc.nextInt(); ArrayList<Pair> interval=new ArrayList<Pair>(); ArrayList<Pair> act=new ArrayList<Pair>(); for(int i=0;i<n;i++) interval.add(new Pair(k[i]-h[i]+1,k[i])); Collections.sort(interval); // out.println(interval); act.add(interval.get(0)); for(int i=1;i<n;i++) { Pair p=act.get(act.size()-1); if(p.y<interval.get(i).x) act.add(interval.get(i)); else p.y=Math.max(p.y, interval.get(i).y); } // out.println(act); long mana=0; for(Pair p: act) { long x=p.y-p.x+1; mana+=(x*(x+1))/2; } out.println(mana); // int n=sc.nextInt(); // long days[]=new long[n]; // long power[]=new long[n]; // for (int i = 0; i < power.length; i++) { // days[i]=sc.nextLong(); // } // for (int i = 0; i < power.length; i++) { // power[i]=sc.nextLong(); // // } // // long ans=0; // for(int i=0;i<n;i++) // { // if(i==0) // { // ans+=power[i]*(power[i]+1L)/2L; // continue; // } // // long temp=power[i]*(power[i]+1)/2L; // long temp2=(power[i-1]+days[i]-days[i-1])*(power[i-1]+days[i]-days[i-1]+1L)/2L; // temp2-=power[i-1]*(power[i-1]+1L)/2L; // ans+=Math.min(temp, temp2); //// if(days[i]-days[i-1]<=power[i]) //// { //// ans+=power[i]*(power[i]+1)/2; //// } //// else { //// ans+=power[i]*(power[i]+1)/2; //// ans-=power[i-1]*(power[i-1]+1)/2; //// } // // // } // // out.println(ans); } out.flush(); out.close(); System.gc(); } /* ...SOLUTION ENDS HERE...........SOLUTION ENDS HERE... */ static int util(char a,char b) { int A=a-'0'; int B=b-'0'; return A+B; } static boolean check(int x,int[] rich,int[] poor) { int cnt=0; for(int i=0;i<rich.length;i++) { if(x-1-rich[i]<=cnt && cnt<=poor[i]) cnt++; } return cnt>=x; } static void arrInt(int n) throws IOException { arInt=new int[n]; for (int i = 0; i < arInt.length; i++) { arInt[i]=sc.nextInt(); } } static void arrLong(int n) throws IOException { arLong=new long[n]; for (int i = 0; i < arLong.length; i++) { arLong[i]=sc.nextLong(); } } static ArrayList<Integer> add(int id,int c) { ArrayList<Integer> newArr=new ArrayList<>(); for(int i=0;i<id;i++) newArr.add(arInt[i]); newArr.add(c); for(int i=id;i<arInt.length;i++) { newArr.add(arInt[i]); } return newArr; } // function to find last index <= y static int upper(ArrayList<Integer> arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) <= y) l = mid + 1; else h = mid - 1; } return h; } static int lower(ArrayList<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) >= x) h = mid - 1; else l = mid + 1; } return l; } static int N = 501; // Array to store inverse of 1 to N static long[] factorialNumInverse = new long[N + 1]; // Array to precompute inverse of 1! to N! static long[] naturalNumInverse = new long[N + 1]; // Array to store factorial of first N numbers static long[] fact = new long[N + 1]; // Function to precompute inverse of numbers public static void InverseofNumber(int p) { naturalNumInverse[0] = naturalNumInverse[1] = 1; for(int i = 2; i <= N; i++) naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p; } // Function to precompute inverse of factorials public static void InverseofFactorial(int p) { factorialNumInverse[0] = factorialNumInverse[1] = 1; // Precompute inverse of natural numbers for(int i = 2; i <= N; i++) factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p; } // Function to calculate factorial of 1 to N public static void factorial(int p) { fact[0] = 1; // Precompute factorials for(int i = 1; i <= N; i++) { fact[i] = (fact[i - 1] * (long)i) % p; } } // Function to return nCr % p in O(1) time public static long Binomial(int N, int R, int p) { // n C r = n!*inverse(r!)*inverse((n-r)!) long ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p; return ans; } static String tr(String s) { int now = 0; while (now + 1 < s.length() && s.charAt(now)== '0') ++now; return s.substring(now); } static ArrayList<Integer> ans; static void dfs(int node,Graph gg,int cnt,int k,ArrayList<Integer> temp) { if(cnt==k) return; for(Integer each:gg.list[node]) { if(each==0) { temp.add(each); ans=new ArrayList<>(temp); temp.remove(temp.size()-1); continue; } temp.add(each); dfs(each,gg,cnt+1,k,temp); temp.remove(temp.size()-1); } return; } static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static ArrayList<Integer> commDiv(int a, int b) { // find gcd of a, b int n = gcd(a, b); // Count divisors of n. ArrayList<Integer> Div=new ArrayList<>(); for (int i = 1; i <= Math.sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) Div.add(i); else { Div.add(i); Div.add(n/i); } } } return Div; } static HashSet<Integer> factors(int x) { HashSet<Integer> a=new HashSet<Integer>(); for(int i=2;i*i<=x;i++) { if(x%i==0) { a.add(i); a.add(x/i); } } return a; } static class Node { int vertex; HashSet<Node> adj; boolean rem; Node(int ver) { vertex=ver; rem=false; adj=new HashSet<Node>(); } @Override public String toString() { return vertex+" "; } } static class Tuple{ int a; int b; int c; public Tuple(int a,int b,int c) { this.a=a; this.b=b; this.c=c; } } //function to find prime factors of n static HashMap<Long,Long> findFactors(long n2) { HashMap<Long,Long> ans=new HashMap<>(); if(n2%2==0) { ans.put(2L, 0L); // cnt++; while((n2&1)==0) { n2=n2>>1; ans.put(2L, ans.get(2L)+1); // } } for(long i=3;i*i<=n2;i+=2) { if(n2%i==0) { ans.put((long)i, 0L); // cnt++; while(n2%i==0) { n2=n2/i; ans.put((long)i, ans.get((long)i)+1); } } } if(n2!=1) { ans.put(n2, ans.getOrDefault(n2, (long) 0)+1); } return ans; } //fenwick tree implementaion static class fwt { int n; long BITree[]; fwt(int n) { this.n=n; BITree=new long[n+1]; } fwt(int arr[], int n) { this.n=n; BITree=new long[n+1]; for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); } long getSum(int index) { long sum = 0; index = index + 1; while(index>0) { sum += BITree[index]; index -= index & (-index); } return sum; } void updateBIT(int n, int index,int val) { index = index + 1; while(index <= n) { BITree[index] += val; index += index & (-index); } } void print() { for(int i=0;i<n;i++) out.print(getSum(i)+" "); out.println(); } } class sparseTable{ int n; long[][]dp; int log2[]; int P; void buildTable(long[] arr) { n=arr.length; P=(int)Math.floor(Math.log(n)/Math.log(2)); log2=new int[n+1]; log2[0]=log2[1]=0; for(int i=2;i<=n;i++) { log2[i]=log2[i/2]+1; } dp=new long[P+1][n]; for(int i=0;i<n;i++) { dp[0][i]=arr[i]; } for(int p=1;p<=P;p++) { for(int i=0;i+(1<<p)<=n;i++) { long left=dp[p-1][i]; long right=dp[p-1][i+(1<<(p-1))]; dp[p][i]=Math.max(left, right); } } } long maxQuery(int l,int r) { int len=r-l+1; int p=(int)Math.floor(log2[len]); long left=dp[p][l]; long right=dp[p][r-(1<<p)+1]; return Math.max(left, right); } } //Function to find number of set bits static int setBitNumber(long n) { if (n == 0) return 0; int msb = 0; n = n / 2; while (n != 0) { n = n / 2; msb++; } return msb; } static int getFirstSetBitPos(long n) { return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1; } static ArrayList<Integer> primes; static HashSet<Integer> primeSet; static boolean prime[]; static void sieveOfEratosthenes(int n) { // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. prime= new boolean[n + 1]; for (int i = 2; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) primeSet.add(i); } } static long mod(long a, long b) { long c = a % b; return (c < 0) ? c + b : c; } static void swap(long arr[],int i,int j) { long temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } static boolean util(int a,int b,int c) { if(b>a)util(b, a, c); while(c>=a) { c-=a; if(c%b==0) return true; } return (c%b==0); } static void flag(boolean flag) { out.println(flag ? "YES" : "NO"); out.flush(); } static void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print_int(ArrayList<Integer> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void print_long(ArrayList<Long> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void printYesNo(boolean condition) { if (condition) { out.println("YES"); } else { out.println("NO"); } } static int LowerBound(int a[], int x) { // x is the target value or key int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } static int lowerIndex(int arr[], int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y static int upperIndex(int arr[], int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } static int upperIndex(long arr[], int n, long y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } static int UpperBound(int a[], int x) {// x is the key or target value int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } static int UpperBound(long a[], long x) {// x is the key or target value int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } static class DisjointUnionSets { int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each void makeSet() { for (int i = 0; i < n; i++) parent[i] = i; } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } // Unites the set that includes x and the set // that includes x void union(int x, int y) { int xRoot = find(x), yRoot = find(y); if (xRoot == yRoot) return; if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else // if ranks are the same { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + 1; } // if(xRoot!=yRoot) // parent[y]=x; } int connectedComponents() { int cnt=0; for(int i=0;i<n;i++) { if(parent[i]==i) cnt++; } return cnt; } } static class Graph { int v; ArrayList<Integer> list[]; Graph(int v) { this.v=v; list=new ArrayList[v+1]; for(int i=1;i<=v;i++) list[i]=new ArrayList<Integer>(); } void addEdge(int a, int b) { this.list[a].add(b); } } // static class GraphMap{ // Map<String,ArrayList<String>> graph; // GraphMap() { // // TODO Auto-generated constructor stub // graph=new HashMap<String,ArrayList<String>>(); // // } // void addEdge(String a,String b) // { // if(graph.containsKey(a)) // this.graph.get(a).add(b); // else { // this.graph.put(a, new ArrayList<>()); // this.graph.get(a).add(b); // } // } // } // static void dfsMap(GraphMap g,HashSet<String> vis,String src,int ok) // { // vis.add(src); // // if(g.graph.get(src)!=null) // { // for(String each:g.graph.get(src)) // { // if(!vis.contains(each)) // { // dfsMap(g, vis, each, ok+1); // } // } // } // // cnt=Math.max(cnt, ok); // } static double sum[]; static long cnt; // static void DFS(Graph g, boolean[] visited, int u) // { // visited[u]=true; // // for(int i=0;i<g.list[u].size();i++) // { // int v=g.list[u].get(i); // // if(!visited[v]) // { // cnt1=cnt1*2; // DFS(g, visited, v); // // } // // } // // // } static class Pair implements Comparable<Pair> { int x; int y; Pair(int x,int y) { this.x=x; this.y=y; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return this.x-o.x; } } static long sum_array(int a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static long sum_array(long a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void reverse_array(int a[]) { int n=a.length; int i,t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static void reverse_array(long a[]) { int n=a.length; int i; long t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // static long modInverse(long a, long m) // { // long g = gcd(a, m); // // return power(a, m - 2, m); // // } static long power(long x, long y) { long res = 1; x = x % mod; if (x == 0) return 0; while (y > 0) { if ((y & 1) != 0) res = (res * x) % mod; y = y >> 1; // y = y/2 x = (x * x) % mod; } return res; } static int power(int x, int y) { int res = 1; x = x % mod; if (x == 0) return 0; while (y > 0) { if ((y & 1) != 0) res = (res * x) % mod; y = y >> 1; // y = y/2 x = (x * x) % mod; } return res; } static long gcd(long a, long b) { if (a == 0) return b; //cnt+=a/b; return gcd(b%a,a); } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } static class FastReader{ byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static PrintWriter out=new PrintWriter(System.out); static int int_max=Integer.MAX_VALUE; static int int_min=Integer.MIN_VALUE; static long long_max=Long.MAX_VALUE; static long long_min=Long.MIN_VALUE; }
import java.util.*; import java.io.*; import java.time.*; import static java.lang.Math.*; @SuppressWarnings("unused") public class C { static boolean DEBUG = false; static Reader fs; static PrintWriter pw; static void solve() { int n = fs.nextInt(), k[] = fs.readArray(n), h[] = fs.readArray(n); int prev_h = h[0], prev_k = k[0]; // int ans = 0; ArrayList<pair> intervals = new ArrayList<>(); for (int i = 0; i < n; i++) { int start = k[i] - h[i] + 1; int end = k[i]; intervals.add(new pair(start, end)); } // pw.println(intervals); Collections.sort(intervals); ArrayList<pair> merged = new ArrayList<>(); merge(intervals, merged); long ans = 0; for(int i = 0 ; i < merged.size() ; i++) { ans += sum(merged.get(i).len()); } pw.println(ans); } static void merge(ArrayList<pair>a1, ArrayList<pair>a2) { int n = a1.size(); int index = 0; for(int i =1 ; i < n ; i++) { if(a1.get(index).s >= a1.get(i).f) { a1.get(index).s = max(a1.get(index).s, a1.get(i).s); } else { index++; a1.set(index, a1.get(i)); } } for(int i = 0 ; i <= index ; i++) { a2.add(a1.get(i)); } // pw.println(a1); } // int index = 0; // Stores index of last element // // in output array (modified arr[]) // // // Traverse all input Intervals // for (int i=1; i<arr.length; i++) // { // // If this is not first Interval and overlaps // // with the previous one // if (arr[index].end >= arr[i].start) // { // // Merge previous and current Intervals // arr[index].end = Math.max(arr[index].end, arr[i].end); // } // else { // index++; // arr[index] = arr[i]; // } // } static boolean overlapping(pair p1, pair p2) { if((p2.f >= p1.f && p1.s >= p2.f) || (p2.s >= p1.f && p1.s >= p2.s)) { return true; } return false; } static pair merge(pair p1, pair p2) { return new pair(min(p1.f, p2.f), max(p1.s, p2.s)); } static long sum(long n) { return (n * (n + 1) / 2); } static class pair implements Comparable<pair>{ int f, s; pair(int f, int s) { this.f = f; this.s = s; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{" + f + "," + s + "}"); return sb.toString(); } @Override public int compareTo(pair o) { return f - o.f; } public int len() { return s - f + 1; } } public static void main(String[] args) throws IOException { Instant start = Instant.now(); if (args.length == 2) { System.setIn(new FileInputStream(new File("D:\\program\\javaCPEclipse\\CodeForces\\src\\input.txt"))); // System.setOut(new PrintStream(new File("output.txt"))); System.setErr(new PrintStream(new File("D:\\program\\javaCPEclipse\\CodeForces\\src\\error.txt"))); DEBUG = true; } fs = new Reader(); pw = new PrintWriter(System.out); int t = fs.nextInt(); while (t-- > 0) { solve(); } Instant end = Instant.now(); if (DEBUG) { pw.println(Duration.between(start, end)); } pw.close(); } static void sort(int a[]) { ArrayList<Integer> l = new ArrayList<Integer>(); for (int x : a) l.add(x); Collections.sort(l); for (int i = 0; i < a.length; i++) { a[i] = l.get(i); } } public static void print(long a, long b, long c, PrintWriter pw) { pw.println(a + " " + b + " " + c); return; } static class Reader { BufferedReader br; StringTokenizer st; public Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[][] read2Array(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; } } }
0
624b8db5
90f01508
//created by Whiplash99 import java.io.*; import java.util.*; public class C { private static ArrayDeque<Integer>[] edge; private static HashMap<String,Integer> map; private static String getHash(int u, int v) { if(u>v) { int tmp=u; u=v; v=tmp; } return u+" "+v; } private static void DFS(int u, int p, int[] ans, int val) { for(int v:edge[u]) { if(v==p) continue; ans[map.get(getHash(u,v))]=val; DFS(v,u,ans,5-val); val=5-val; } } public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,N; int T=Integer.parseInt(br.readLine().trim()); StringBuilder sb=new StringBuilder(); while (T-->0) { N=Integer.parseInt(br.readLine().trim()); edge=new ArrayDeque[N]; for(i=0;i<N;i++) edge[i]=new ArrayDeque<>(); map=new HashMap<>(); int[] ans=new int[N-1]; int[] deg=new int[N]; for(i=0;i<N-1;i++) { String[] 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); deg[u]++; deg[v]++; map.put(getHash(u,v),i); } for(i=0;i<N;i++) if(deg[i]>2) break; if(i<N) { sb.append(-1).append("\n"); continue; } DFS(0,0,ans,2); for(int x:ans) sb.append(x).append(" "); sb.append("\n"); } System.out.println(sb); } }
// import java.io.DataInputStream; // import java.io.FileInputStream; // import java.io.IOException; import java.io.*; import java.util.*; public class one { static Scanner sc=new Scanner(System.in); boolean prime[]; static int prev=-1; static int dp[][]; public static int[] input(int size){ int arr[]=new int[size]; for(int i=0;i<size;i++) arr[i]=sc.nextInt(); return arr; } public static void main(String[] args) { //int testcase=1; int testcase=sc.nextInt(); //System.out.println("HI"); while(testcase-->0){ // int x=sc.nextInt(); // int y=sc.nextInt(); //String str[]=new String[size]; solve(); System.out.println(); } } public static void solve(){ HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(); int size=sc.nextInt(); int arr[][]=new int[size-1][2]; for(int i=0;i<size-1;i++){ arr[i][0]=sc.nextInt(); arr[i][1]=sc.nextInt(); } for(int x[]:arr){ map.put(x[0],map.getOrDefault(x[0], 0)+1); map.put(x[1],map.getOrDefault(x[1], 0)+1); if(map.get(x[0])>2||map.get(x[1])>2){ System.out.println(-1); return; } } List<List<Integer>> adj=new ArrayList<>(); for(int i=0;i<=size;i++) adj.add(new ArrayList<Integer>()); for(int x[]:arr){ adj.get(x[0]).add(x[1]); adj.get(x[1]).add(x[0]); } //System.out.println(adj); int vist[]=new int[size+1]; HashMap<String,Integer> ans=new HashMap<String,Integer>(); for(int i=1;i<=size;i++){ if(vist[i]==0){ dfs(i,vist,adj,ans,2); } } //System.out.println(ans); for(int x[]:arr){ //System.out.print(map.get(x[0])); int a=Math.min(x[0],x[1]); int b=Math.max(x[0],x[1]); String s=a+" "+b; System.out.print(ans.get(s)+" "); } // map=new HashMap<Integer,Integer>(); // for(int x[]:arr){ // if(map.containsKey(x[0])){ // int val=13-map.get(x[0]); // map.put(x[1],val); // System.out.print(val+" "); // }else if(map.containsKey(x[1])){ // int val=13-map.get(x[1]); // map.put(x[0],val); // System.out.print(val+" "); // }else{ // System.out.print(2+" "); // map.put(x[0],2); // map.put(x[1],2); // } // } } public static void dfs(int node,int vist[],List<List<Integer>> adj,HashMap<String,Integer> ans,int val){ vist[node]=1; for(int i:adj.get(node)){ if(vist[i]==1) continue; int x=Math.min(i, node); int y=Math.max(i, node); ans.put(x+" "+y,val); dfs(i,vist,adj,ans,5-val); val=5-val; } } }
0
40132ebc
d783d815
import java.util.ArrayList; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collections; import java.util.StringTokenizer; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import java.util.List; import java.util.HashMap; import java.util.LinkedList; import java.util.HashSet; import java.util.Stack; import java.util.Queue; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.sqrt; import static java.lang.Math.abs; import static java.lang.Math.random; import static java.lang.Integer.MAX_VALUE; import static java.lang.Integer.MIN_VALUE; import static java.util.Collections.reverseOrder; public final class Test1 { static int mod = 1000000007; static int mod1 = 998244353; public static void main(String[] args) { solve(); } static long gcd(int a, int b) {if (b == 0) return a; return gcd(b, a % b); } static long modAdd(long a, long b, long m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;} static long modMul(long a, long b, long m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;} static long modSub(long a, long b, long m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;} static long modDiv(long a, long b, long m) {a = a % m; b = b % m; return (modMul(a, mminvprime(b, m), m) + m) % m;} //only for prime m static long mminvprime(long a, long b) {return expo(a, b - 2, b);} static long expo(long a, long b, long mod) {long res = 1; while (b > 0) {if ((b & 1) != 0)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;} static long setBits(int n) {int cnt = 0; while (n != 0) { cnt++; n = n & (n - 1); } return cnt;} static int[] sieve(int n) {int[] arr = new int[n + 1]; for (int i = 2; i <= n; i++)if (arr[i] == 0) {for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return arr;} static void debug(int[] nums) { for (int i = 0; i < nums.length; i++) System.out.println(nums[i] + " "); } static void debug(long[] nums) { for (int i = 0; i < nums.length; i++) System.out.println(nums[i] + " "); } static void debug(String[] nums) { for (int i = 0; i < nums.length; i++) System.out.println(nums[i] + " "); } static void reverse(int[] nums) { int start = 0, end = nums.length - 1; while (start < end) {int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } } static void reverse(char[] nums) { int start = 0, end = nums.length - 1; while (start < end) {char temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } } 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()); } } 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); } // <------------------------- CODE START FROM HERE --------------------------------> public static void solve() { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-- != 0) { int n = sc.nextInt(); String[] arr = new String[n]; for (int i = 0; i < n; i++) arr[i] = sc.next(); int cnt[] = new int[5]; for (int i = 0; i < n; i++) { for (char ch : arr[i].toCharArray()) { cnt[ch - 'a']++; } } int res = 0; for (int i = 0; i < 5; i++) { res = Math.max(res, fun(arr, cnt, (char)( 'a' + i))); } System.out.println(res); } } static int fun(String[] arr, int[] cnt, char c) { int n = arr.length; int total = cnt[0] + cnt[1] + cnt[2] + cnt[3] + cnt[4] - cnt[c - 'a']; int letter_total = cnt[c - 'a']; PriorityQueue<Pair>pq = new PriorityQueue<>(); for (int i = 0; i < n; i++) { int letter = 0; int ext = 0; for (char ch : arr[i].toCharArray()) { if (ch == c) letter++; else ext++; } pq.offer(new Pair(letter, ext)); } while (pq.size() > 0) { if (total < letter_total) return pq.size(); Pair temp = pq.poll(); total -= temp.ext; letter_total -= temp.letter; } return 0; } static class Pair implements Comparable<Pair> { int letter, ext; Pair(int letter, int ext) { this.letter = letter; this.ext = ext; } public int compareTo(Pair p) { return (p.ext - p.letter) - (this.ext - this.letter); } } // <----------------------------------CODE END HERE------------------------> // System.out.println(); // int b[] = a.clone(); }
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Collections; import java.util.PriorityQueue; import java.util.Scanner; import java.util.StringJoiner; import java.util.StringTokenizer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.HashSet; import static java.lang.System.out; import static java.util.stream.Collectors.joining; public class C { static FastScanner sc = new FastScanner(System.in); public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { int T = sc.nextInt(); for (int tt = 1; tt <= T; tt++) { int n = sc.nextInt(); String[] strings = new String[n]; PriorityQueue<Pair>[] frequencies = new PriorityQueue[5]; for (int i = 0; i < 5; i++) frequencies[i] = new PriorityQueue<>(); for (int i = 0; i < n; i++) { strings[i] = sc.next(); int[] freq = new int[5]; for (char c : strings[i].toCharArray()) freq[c - 'a']++; for (int j = 0; j < 5; j++) { //if (freq[j] > 0) frequencies[j].add(new Pair(freq[j], strings[i].length())); } } /* for (int i = 0; i < 5; i++) { while (!frequencies[i].isEmpty()) System.out.print(frequencies[i].remove() + ", "); System.out.println(); }*/ int ans = 0; for (PriorityQueue<Pair> pq : frequencies) { long curlen = 0; long curfreq = 0; int cnt = 0; while (!pq.isEmpty()) { Pair pair = pq.remove(); curfreq += pair.freq; curlen += pair.len; if (curfreq >= curlen / 2 + 1) { cnt++; } else { break; } } ans = Math.max(ans, cnt); } System.out.println(ans); } } } static class Pair implements Comparable<Pair> { int freq, len; public Pair(int freq, int len) { this.freq = freq; this.len = len; } @Override public int compareTo(Pair o) { /*if(freq == 0 && o.freq == 0) return len - o.len; if(freq == 0) return len - (o.len - o.freq); if(o.freq == 0) return o.len - (len - freq); int diff1 = freq * o.len; int diff2 = o.freq * len; return diff2 - diff1;*/ return -(o.len - 2*o.freq - len + 2*freq); } @Override public String toString() { return freq + " " + len; } } /* 1 5 cbdca d a d eb */ static 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), 32768); } 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()); } } }
0
04df7bb8
1ea771ea
import java.math.BigInteger; import java.sql.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.Stack; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { static HashMap<Integer,Boolean>map; static long dp[][]; static boolean flag; static HashSet<Long>hs; static long mod=(long)(1e9+7); public static void main(String[] args) { StringBuilder ans=new StringBuilder(); FastReader sc=new FastReader(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); //int n=sb.length(); int k=sc.nextInt(); long L[]=new long[n]; long R[]=new long[n]; int a[]=new int[k]; int temp[]=new int[k]; for(int i=0;i<k;i++) a[i]=sc.nextInt(); for(int i=0;i<k;i++) temp[i]=sc.nextInt(); int c[]=new int [n]; Arrays.fill(c, Integer.MAX_VALUE); for(int i=0;i<k;i++) c[a[i]-1]=temp[i]; long p=Integer.MAX_VALUE; for(int i=0;i<n;i++) { p=Math.min(p+1, c[i]); L[i]=p; } p=Integer.MAX_VALUE; for(int i=n-1;i>=0;i--) { p=Math.min(p+1, c[i]); R[i]=p; } for(int i=0;i<n;i++) { ans.append(Math.min(L[i], R[i])+" "); } ans.append("\n"); } System.out.println(ans); } static class Sparse{ int log[]; long sparse[][]; Sparse(int n){ log=new int [n+1]; for(int i=1;i<n+1;i++) { log[i]=log[i/2]+1; } sparse=new long[n][18]; } } static long solve(String X,String Y,int n,int m,int M){ if(m==0&&n==0)return 0; // if(m==1&&X.charAt(n-1)!='u')return Integer.MIN_VALUE; if(n==0||m==0)return Integer.MIN_VALUE; if(dp[n][m]!=-1)return dp[n][m]; if(Y.charAt(m-1)==X.charAt(n-1)) { // else if(n==1)return Integer.MAX_VALUE; return dp[n][m]=1+ Math.max(solve (X,Y,n-1,m,M),solve (X,Y,n-1,m-1,M)); } else{ return dp[n][m]= solve(X,Y,n-1,m,M); } } static long solve(long [][]g,int n,int m,boolean visited [][]) { if(n==0||m==0)return 0; visited[n][m]=true; long ans=g[n-1][m-1]+Math.max(solve(g, n, m-1, visited),solve(g, n-1, m, visited)); visited[n][m]=false; return ans; } static boolean isP(long x,long n,long m) { return (x^n)<=m; } static class pair{ int n;int i; pair(int n,int i){ this.n=n; this.i=i; } } static long solve(char g[][],int n,int m) { if(n==0||m==0)return 0; if(n==1&&m==1)return 1; if(g[n-1][m-1]=='#')return 0; if(dp[n][m]!=-1)return dp[n][m]; return dp[n][m]= (solve(g, n-1, m)%mod+solve(g, n, m-1)%mod)%mod; } static int solve (int v,ArrayList<ArrayList<Integer>>adj,int d[],boolean visited[]) { visited[v]=true; for(int u:adj.get(v)) { if(!visited[u]) { solve(u, adj, d, visited); } d[v]=Math.max(1+d[u], d[v]); } return d[v]; } static class colors{ int c;int n; public colors(int c,int n) { // TODO Auto-generated constructor stub this.c=c; this.n=n; } } static int CeilIndex(long A[], int l, int r, long key) { while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] >= key) r = m; else l = m; } return r; } static int CeilIndexd(long A[], int l, int r, long key) { while (r - l > 1) { int m = l + (r - l) / 2; if (-1*A[m] >= key) r = m; else l = m; } return r; } static void solve(ArrayList<Long>A,long bd) { if(bd>(long)1e9)return; // if(hs.contains(bd))return; //A.add(bd); hs.add(bd); A.add(bd*10); A.add(bd*10+1); // hs.add(bd*10); //hs.add(bd*10+1); solve(A,bd*10); solve(A,bd*10+1); } static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long lcm(long a, long b) { return ((a / gcd(a, b))%mod * b%mod)%mod; } static long gcd(long a,long b) { if (a == 0) return b%mod; return (gcd(b % a, a))%mod; } //System.out.println(count); static void dfs(int v,boolean visited[],ArrayList<ArrayList<Integer>>adj,int div[],int t) { visited[v]=true; div[v]=t+1; for(int u:adj.get(v)) { if(!visited[u]) { dfs(u,visited,adj,div,(t+1)%2); } } } static class Helper{ int a;int b;int t; public Helper(int a,int b) { // TODO Auto-generated constructor stub this.a=a; this.b=b; } } // System.out.println(max); //System.out.println(ans.toString()); //main( static void solvedfs(ArrayList<ArrayList<Integer>>adj,int n,int v,int subt[],int subtAns[],boolean []visited) { int count=1; int ans=0; visited[v]=true; for(int u:adj.get(v)) { if(!visited[u]) { //System.out.println(v+" "+subt[v]+" "+n); subtAns[u]=Math.max(subtAns[u], subt[v]-subtAns[u]); solvedfs(adj, n, u, subt, subtAns, visited); } } } static int dfs(ArrayList<ArrayList<Integer>>adj,int v,int subt[],int subtAns[],boolean []visited) { int count=0; int ans=0; visited[v]=true; for(int u:adj.get(v)) { if(!visited[u]) { count+=ans; ans=Math.max(dfs(adj,u,subt,subtAns,visited),ans); } } subt[v]=count; subtAns[v]=ans; return ans+1; } static int solve(ArrayList<ArrayList<Integer>>adj,int node,ArrayList<Integer>A) { if(adj.get(node).size()==0)return 1; int count=0; for(int v:adj.get(node)) { count+=solve(adj,v,A); } A.set(node,count); return count+1; } static void dfs(String[]building,int i,int j,int n,int m, boolean visited[][]) { visited[i][j]=true; if(isValid(building,i+1,j,n,m,visited)) { visited[i+1][j]=true; dfs(building,i+1,j,n,m,visited); } if(isValid(building,i-1,j,n,m,visited)) { visited[i-1][j]=true; dfs(building,i-1,j,n,m,visited); } if(isValid(building,i,j+1,n,m,visited)) {visited[i][j+1]=true; dfs(building,i,j+1,n,m,visited); } if(isValid(building,i,j-1,n,m,visited)) {visited[i][j-1]=true; dfs(building,i,j-1,n,m,visited); } } static boolean isValid(String[]building,int i,int j,int n,int m, boolean visited[][]) { if(i==-1||j==-1||i==n||j==m||visited[i][j]||building[i].charAt(j)=='#') return false; return true; } static void compute(boolean sieve[],int n) { for(int i=2;i<=n;i++) { if(sieve[i])continue; for(int j=2*i;j<n;j+=i) { sieve[j]=true; } } } static void computeHs(boolean sieve[]) { int n=(int)(1e9-1e7+1); for(int i=1;i<n;i++) { if(sieve[i])continue; for(int j=2*i;j<n;j+=i) { sieve[j]=true; } } } static boolean isValid(StringBuilder s,int w) { if(w>s.length())return false; HashSet<Character>hs=new HashSet<Character>(); int a[]=new int[3]; for(int i=0;i<w;i++) { ++a[s.charAt(i)-49]; } if(a[0]>0&&a[1]>0&&a[2]>0)return true; int start=0; int end=w; while(end!=s.length()) { --a[s.charAt(start)-49]; ++a[s.charAt(end)-49]; start++; end++; if(a[0]>0&&a[1]>0&&a[2]>0)return true; } return false; } static int find(int parent[],int i) { if(parent[i]==-1)return i; return parent[i]=find(parent,parent[i]); } static void union(int parent[],int rank[],int s1,int s2) { if(rank[s1]>=rank[s2]) { parent[s2]=s1; rank[s1]+=rank[s2]; } else { parent[s1]=s2; rank[s2]+=rank[s1]; } } static int solve(String S,int K) { if(K<=0)return 0; if(S.charAt(K-1)!=S.charAt(K)) return 1+solve(S,K-1); else return solve(S,K-1); } static boolean isValid(int g[][],int r,int c,int n,int m,boolean visited[][],int s) { if(r==-1||r==n||c==-1||c==m||visited[r][c]||g[r][c]!=s)return false; return true; } 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; } } }
import java.io.*; import java.util.*; public class CODECHEF { 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(); } String nextLine() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c != 10 && c != 13; c = scan()) { sb.append((char) c); } return sb.toString(); } char nextChar() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; return (char) c; } 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 long MOD=1000000000; static class Pair{ long a; int b; Pair(long i,int j){ a=i; b=j; } } static long[] solve(int[] pos,long[] arr,int n,int k){ long[] ans=new long[n]; long[] left=new long[n]; long[] right=new long[n]; long min=Integer.MAX_VALUE; for(int i=0;i<n;i++){ min=Math.min(min+1,arr[i]); left[i]=min; } min=Integer.MAX_VALUE; for(int i=n-1;i>=0;i--){ min=Math.min(min+1,arr[i]); right[i]=min; } for(int i=0;i<n;i++){ ans[i]=Math.min(left[i],right[i]); } return ans; } public static void main(String[] args) throws java.lang.Exception { FastReader fs=new FastReader(System.in); // StringBuilder sb=new StringBuilder(); // PrintWriter out=new PrintWriter(System.out); int t=fs.nextInt(); while (t-->0){ int n=fs.nextInt(); int k=fs.nextInt(); int[] pos=new int[k]; for(int i=0;i<k;i++) pos[i]=fs.nextInt()-1; long[] temp=new long[n]; int ptr=0; Arrays.fill(temp,Integer.MAX_VALUE); for(int i=0;i<k;i++) temp[pos[ptr++]]=fs.nextLong(); long[] ans=solve(pos,temp,n,k); for(int i=0;i<n;i++) System.out.print(ans[i]+" "); System.out.println(); } //out.close; } }
1
065e0cbd
9b449b4f
import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static int ask(int i){ FastReader sc = new FastReader(); System.out.println("? " + (i+1)); System.out.flush(); int x = sc.nextInt(); return x - 1; } public static void main(String[] args) { FastReader sc = new FastReader(); int t = sc.nextInt(); int inf = 1000000007; while(t-->0){ int n = sc.nextInt(); int ans[] = new int[n]; for(int i=0;i<n;i++){ if(ans[i] == 0){ ArrayList<Integer> cycle = new ArrayList<Integer>(); int x = ask(i), y = ask(i); cycle.add(y); while(y != x){ y = ask(i); cycle.add(y); } for(int j=0;j<cycle.size();j++){ ans[cycle.get(j)] = cycle.get((j+1)%cycle.size()) + 1; } } } System.out.print("! "); for(int i=0;i<n;i++) System.out.print(ans[i] + " "); System.out.println(); } } }
/* "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.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 = 0; t < test; t++) { solve(); } out.close(); } private static void solve() { int n = sc.nextInt(); int[] permutation = new int[n]; Arrays.fill(permutation, -1); // there may be multiple cycles in the given permutation for (int i = 0; i < n; i++) { if (permutation[i] == -1) { // ith permutation value is not found yet // so we find all values of permutation having i in their cycle // for that we always ask(i) so that we can get all values in that cycle List<Integer> cycle = new ArrayList<>(); int startCycleValue = ask(i + 1); int currValueAt = ask(i + 1); cycle.add(currValueAt); while (currValueAt != startCycleValue) { currValueAt = ask(i + 1); cycle.add(currValueAt); } int m = cycle.size(); for (int j = 0; j < m; j++) { permutation[cycle.get(j)] = cycle.get((j + 1) % m); } } } out.println("! "); for (int i = 0; i < n; i++) { out.print((permutation[i] + 1) + " "); } out.println(); out.flush(); } private static int ask(int i) { out.println("? " + i + " "); out.flush(); int value = sc.nextInt(); return value - 1; } 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 end) { end.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 end) { end.printStackTrace(); } return str; } } }
0
23cb8587
48801d9e
import java.io.*; import java.util.*; public class C { static long mod = (long) (1e9 + 7); public static void main(String[] args) throws IOException { Scanner scn = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); StringBuilder sb = new StringBuilder(); int T = scn.ni(), tcs = 0; C: while (tcs++ < T) { int n = scn.ni(); tree = new ArrayList[n + 1]; range = new long[n + 1][2]; for (int i = 0; i <= n; i++) tree[i] = new ArrayList<>(); for (int i = 1; i <= n; i++) { range[i][0] = scn.nl(); range[i][1] = scn.nl(); } for (int i = 0; i < n - 1; i++) { int x = scn.ni(); int y = scn.ni(); tree[x].add(y); tree[y].add(x); } strg = new long[n + 1][2]; for (long a1[] : strg) Arrays.fill(a1, -1L); sb.append(Math.max(DFS(1, -1, 0), DFS(1, -1, 1))); sb.append("\n"); } out.print(sb); out.close(); } static ArrayList<Integer> tree[]; static long range[][], strg[][]; static long DFS(int u, int pa, int ok) { if (strg[u][ok] != -1) return strg[u][ok]; long tg = 0; for (int ch : tree[u]) { if (ch == pa) continue; long sg = 0; if (ok == 0) { sg = Math.max(DFS(ch, u, 0) + Math.abs(range[u][0] - range[ch][0]), DFS(ch, u, 1) + Math.abs(range[u][0] - range[ch][1])); } else { sg = Math.max(DFS(ch, u, 0) + Math.abs(range[u][1] - range[ch][0]), DFS(ch, u, 1) + Math.abs(range[u][1] - range[ch][1])); } tg += sg; } return strg[u][ok] = tg; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int ni() throws IOException { return Integer.parseInt(next()); } public long nl() throws IOException { return Long.parseLong(next()); } public int[] nia(int n) throws IOException { int a[] = new int[n]; String sa[] = br.readLine().split(" "); for (int i = 0; i < n; i++) a[i] = Integer.parseInt(sa[i]); return a; } public long[] nla(int n) throws IOException { long a[] = new long[n]; String sa[] = br.readLine().split(" "); for (int i = 0; i < n; i++) a[i] = Long.parseLong(sa[i]); return a; } public void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int v : a) l.add(v); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } public void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long v : a) l.add(v); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class C { private static FastReader fr = new FastReader(); private static PrintWriter out=new PrintWriter(System.out); private static Random random = new Random(); private static long[][] dp; private static long calculate(List<Integer>[] graph, int current, long[][] r, boolean[] stack, int use){ if(dp[current][use] != -1) return dp[current][use]; stack[current] = true; long max = 0; if(graph[current] != null){ for(int next : graph[current]){ if(!stack[next]){ stack[next] = true; long r1 = Math.abs(r[current][use] - r[next][0]) + calculate(graph, next, r, stack, 0); long r2 = Math.abs(r[current][use] - r[next][1]) + calculate(graph, next, r, stack, 1); max += Math.max(r1, r2); } } } stack[current] = false; dp[current][use] = max; return max; } public static void main(String[] args) throws IOException { StringBuilder sb = new StringBuilder(); // code goes here int t = fr.nextInt(); while (t-- > 0){ int n = fr.nextInt(); long[][] r = new long[n][2]; for(int i = 0; i < n; i++){ r[i] = fr.nextLongArray(2); } List<Integer>[] graph = new ArrayList[n]; for(int i = 0; i < n - 1; i++){ int u = fr.nextInt(); int v = fr.nextInt(); if(graph[u - 1] == null) graph[u - 1] = new ArrayList<>(); if(graph[v - 1] == null) graph[v - 1] = new ArrayList<>(); graph[u - 1].add(v - 1); graph[v - 1].add(u - 1); } boolean[] stack = new boolean[n]; dp = new long[n][2]; for(int i = 0; i < dp.length; i++){ Arrays.fill(dp[i], -1); } long r1 = calculate(graph, 0, r, stack, 0); long r2 = calculate(graph, 0, r, stack, 1); sb.append(Math.max(r1, r2)).append("\n"); } System.out.print(sb.toString()); } 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 FastReader{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] nextIntArray(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()); } public long[] nextLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } static class Pair<A, B>{ A first; B second; public Pair(A first, B second){ this.first = first; this.second = second; } } static long mod(String num, long a) { // Initialize result long res = 0; // One by one process all digits of 'num' for (int i = 0; i < num.length(); i++) res = (res*10 + num.charAt(i) - '0') %a; return res; } static long binomialCoeff(long n, long k, long MOD) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); res %= MOD; } return res; } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static long modInverse(long n, long p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static long nCrModPFermat(int n, int r, long p) { // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r long[] fac = new long[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } }
0
0b27be88
3f4a5b64
import java.util.*; import java.io.*; public class C { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(int arr[],int l1,int r1,int l2,int r2) { int tmp[]=new int[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(long arr[],int l1,int r1,int l2,int r2) { long tmp[]=new long[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void main(String args[]) throws IOException { Scan input=new Scan(); StringBuilder ans=new StringBuilder(""); int test=input.scanInt(); for(int tt=1;tt<=test;tt++) { int n=input.scanInt(); int m=input.scanInt(); int x=input.scanInt(); ans.append("YES\n"); TreeMap<Integer,Stack<Integer>> tm=new TreeMap<>(); for(int i=1;i<=m;i++) { ans.append(i+" "); int tmp=input.scanInt(); if(!tm.containsKey(tmp)) { Stack<Integer> stck=new Stack<>(); stck.add(i); tm.put(tmp, stck); } else { Stack<Integer> stck=tm.get(tmp); stck.add(i); } } for(int i=m;i<n;i++) { int tmp=input.scanInt(); int min=tm.firstKey(); Stack<Integer> stck=tm.get(min); int indx=stck.pop(); ans.append(indx+" "); if(stck.isEmpty()) { tm.remove(min); } tmp+=min; if(!tm.containsKey(tmp)) { stck=new Stack<>(); stck.add(indx); tm.put(tmp, stck); } else { stck=tm.get(tmp); stck.add(indx); } } ans.append("\n"); } System.out.println(ans); } }
import java.util.*; import java.io.*; public class C { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(int arr[],int l1,int r1,int l2,int r2) { int tmp[]=new int[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(long arr[],int l1,int r1,int l2,int r2) { long tmp[]=new long[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void main(String args[]) throws IOException { Scan input=new Scan(); StringBuilder ans=new StringBuilder(""); int test=input.scanInt(); for(int tt=1;tt<=test;tt++) { int n=input.scanInt(); int m=input.scanInt(); int x=input.scanInt(); ans.append("YES\n"); TreeMap<Integer,Stack<Integer>> tm=new TreeMap<>(); for(int i=1;i<=m;i++) { ans.append(i+" "); int tmp=input.scanInt(); if(!tm.containsKey(tmp)) { Stack<Integer> stck=new Stack<>(); stck.add(i); tm.put(tmp, stck); } else { Stack<Integer> stck=tm.get(tmp); stck.add(i); } } for(int i=m;i<n;i++) { int tmp=input.scanInt(); int min=tm.firstKey(); Stack<Integer> stck=tm.get(min); int indx=stck.pop(); ans.append(indx+" "); if(stck.isEmpty()) { tm.remove(min); } tmp+=min; if(!tm.containsKey(tmp)) { stck=new Stack<>(); stck.add(indx); tm.put(tmp, stck); } else { stck=tm.get(tmp); stck.add(indx); } } ans.append("\n"); } System.out.println(ans); } }
1
8f6421f3
ea2fc2bc
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Arrays; public class Main{ public static void main (String[] args){ FastReader s = new FastReader(); int t=1;t=s.ni(); for(int test=1;test<=t;test++){ int n=s.ni(),k=s.ni(); int position[]=s.readArray(k),temp[]=s.readArray(k); int ans[]=new int[n]; Arrays.fill(ans,Integer.MAX_VALUE/2); for(int i=0;i<k;i++){ ans[position[i]-1]=temp[i]; } for(int i=1;i<n;i++){ ans[i]=Math.min(ans[i-1]+1,ans[i]); } for(int i=n-2;i>=0;i--){ ans[i]=Math.min(ans[i],ans[i+1]+1); } for(int i=0;i<n;i++) System.out.print(ans[i]+" "); System.out.println(); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in));} int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } int[] readArray(int n){ int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] =Integer.parseInt(next()); return a; } String next(){ while (st == null || !st.hasMoreElements()) {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;} } }
//package Practise; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class AirConditioner { public static void main(String args[]) { FastScanner fs=new FastScanner(); int t=fs.nextInt(); for(int t1=0;t1<t;t1++) { int n=fs.nextInt(); int k=fs.nextInt(); int []arr1=new int[k]; int []arr2=new int[k]; arr1=fs.readArray(k); arr2=fs.readArray(k); int []dp=new int[n]; //for(int i=0;i<k;i++) //dp[arr1[i]-1]=arr2[i]; Arrays.fill(dp,Integer.MAX_VALUE/2); for(int i=0;i<k;i++) { dp[arr1[i]-1]=arr2[i]; } for(int i=1;i<n;i++) { dp[i]=Math.min(dp[i],dp[i-1]+1); } //Print(dp); for(int i=n-2;i>=0;i--) { dp[i]=Math.min(dp[i], dp[i+1]+1); } //Print(dp); /*for(int i=0;i<n;i++) { int min=Integer.MAX_VALUE; for(int j=0;j<k;j++) { min=Math.min(min, arr2[j]+Math.abs(i-arr1[j]+1)); } dp[i]=min; }*/ for(int val:dp) { System.out.print(val+" "); } System.out.println(); } } 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 void Print(int []arr) { for(int val:arr) System.out.print(val+" "); System.out.println(); } 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()); } } }
1
9028caf7
d221162a
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=1; while(T-->0) { int n=input.nextInt(); int a[]=new int[n]; ArrayList<Integer> list=new ArrayList<>(); ArrayList<Integer> space=new ArrayList<>(); for(int i=0;i<n;i++) { a[i]=input.nextInt(); if(a[i]==1) { list.add(i); } else { space.add(i); } } int pre[]=new int[space.size()]; for(int i=0;i<list.size();i++) { if(i==0) { int min=Integer.MAX_VALUE; for(int j=0;j<space.size();j++) { pre[j]=Math.abs(list.get(i)-space.get(j)); min=Math.min(min,pre[j]); pre[j]=min; } } else { int arr[]=new int[space.size()]; for(int j=0;j<i;j++) { arr[j]=Integer.MAX_VALUE; } int min=Integer.MAX_VALUE; for(int j=i;j<space.size();j++) { int v=Math.abs(list.get(i)-space.get(j)); v+=pre[j-1]; arr[j]=v; min=Math.min(min,v); arr[j]=min; } for(int j=0;j<space.size();j++) { pre[j]=arr[j]; } } } out.println(pre[space.size()-1]); } out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
import java.util.*; import java.io.*; public class Main2 { 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 long mod = 998244353; // static Scanner sc = new Scanner(System.in); static FastReader sc = new FastReader(); static PrintWriter out = new PrintWriter(System.out); public static void main (String[] args) { int t = 1; // t = sc.nextInt(); z : while(t-->0) { int n = sc.nextInt(); int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = sc.nextInt(); List<Integer> a1 = new ArrayList<>(); ArrayList<Integer> a2 = new ArrayList<>(); for (int i = 0; i < n; i++) { if(a[i] == 0) a1.add(i); else a2.add(i); } long dp[][] = new long[n+1][n+1]; for (int i = 0; i <= n; i++) { Arrays.fill(dp[i],-1); } out.write(find(0,0,a1,a2,dp)+"\n"); } out.close(); } private static long find(int i, int j, List<Integer> a1, ArrayList<Integer> a2, long[][] dp) { if(j == a2.size()) return 0; int req = a2.size()-j; int ava = a1.size()-i; if(ava<req) return Integer.MAX_VALUE/2; if(dp[i][j] != -1) return dp[i][j]; long ans1 = find(i+1,j,a1,a2,dp); long ans2 = Math.abs(a1.get(i)-a2.get(j)) + find(i+1,j+1,a1,a2,dp); return dp[i][j] = Math.min(ans1, ans2); } }
0
4e5ee0f7
d6fb3b9e
import java.io.*; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.util.Collections; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.*; public class Main1 { public static void main(String[] args) throws IOException { // try { // Scanner in = new Scanner(System.in) ; FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt() ; while (t-- > 0){ int n = in.nextInt() ; int dp[][] = new int[n][5] ; String tt[] = new String[n] ; for (int i = 0; i <n ; i++) { String s= in.next() ; tt[i] = s ; for (int j = 0; j <s.length() ; j++) { dp[i][s.charAt(j)-'a']++ ; } } int max = 0 ; for (int i = 0; i <5 ; i++) { ArrayList<Integer>list = new ArrayList<>() ; for (int j = 0; j <n ; j++) { list.add(dp[j][i] - (tt[j].length()-dp[j][i]) ); } list.sort(Collections.reverseOrder()); int ans = 0 ; int sum = 0 ; for (int curr : list){ sum+= curr ; if (sum > 0){ ans++ ; max = max(max , ans) ; } else break; } } System.out.println(max); } out.flush(); out.close(); // } catch (Exception e) { // return; // } } static long gcd(long a, long b) { return (b == 0) ? a : gcd(b, a % b); } static int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } 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()); } } }
import java.util.*; public class Sol { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int a[][]=new int[n][5]; int tot[]=new int[n]; for(int i=0;i<n;i++) { String x = sc.next(); for(int j=0;j<x.length();j++) a[i][x.charAt(j)-'a'] += 1; tot[i]=x.length(); } int max=Integer.MIN_VALUE; for(int i=0;i<5;i++) max=Math.max(max,function(a,n,i,tot)); System.out.println(max); } } static int function(int a[][],int n,int i,int tot[]) { Integer ans[] = new Integer[n]; for(int j=0;j<n;j++) ans[j]=a[j][i]-(tot[j]-a[j][i]); int res=0,j=0; Arrays.sort(ans,Collections.reverseOrder()); while(j<n&&res+ans[j]>0) res+=ans[j++]; return j; } }
0
11373c16
d8e4eb5e
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef {static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main (String[] args) throws java.lang.Exception { FastReader scan = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int n = scan.nextInt(); ArrayList<Integer> a = new ArrayList<>(); ArrayList<Integer> b = new ArrayList<>(); for(int i=0;i<n;i++){ int x = scan.nextInt(); if(x==1) a.add(i); else b.add(i); } int x = a.size(); if(x==0){ pw.println(0); pw.flush(); return; } int y = b.size(); int dp[][] = new int[x][y]; int min = Integer.MAX_VALUE; for(int i=0;i<y;i++){ min = Math.min(Math.abs(a.get(0) - b.get(i)),min); dp[0][i] = min; } for(int i=1;i<x;i++){ min = Integer.MAX_VALUE; for(int j=i;j<y;j++){ min = Math.min(Math.abs(a.get(i)-b.get(j))+dp[i-1][j-1],min); dp[i][j] = min; } } pw.println(dp[x-1][y-1]); pw.flush(); } }
import java.io.*; import java.util.*; public class E { public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int cnt = n; boolean[] non = new boolean[n]; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i++) { if(Integer.parseInt(st.nextToken()) == 0) { non[i] = true; cnt--; } } int x = 0; int y = 0; int[] location = new int[cnt]; int[] rlocation = new int[n-cnt]; for(int i = 0; i < n; i++) { if(!non[i]) { location[x] = i; x++; }else{ rlocation[y] = i; y++; } } int[][] dp = new int[(n-cnt)+1][cnt+1]; Arrays.fill(dp[0], 100000000); dp[0][0] = 0; for(int i = 0; i < n-cnt; i++) { //System.out.println("HIT"); if(i < (n-cnt)) Arrays.fill(dp[i+1], 100000000); for(int j = 0; j < cnt; j++) { if(i < (n-cnt)) { dp[i+1][j] = Math.min(dp[i+1][j], dp[i][j]); dp[i+1][j+1] = Math.min(dp[i+1][j+1], dp[i][j] + Math.abs(rlocation[i] - location[j])); //System.out.println(dp[i+1][j+1] + " " + dp[i][j] + " " + j + " " + rlocation[i] + " " + location[j]); } } } int min = Integer.MAX_VALUE; for(int i = 0; i < (n-cnt)+1; i++) { min = Math.min(dp[i][cnt], min); } System.out.println(min); } }
0
201e3463
de599e42
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.TreeSet; public class D { public static void main(String[] args) { CP sc =new CP(); int tt = sc.nextInt(); while (tt-- > 0) { int n = sc.nextInt(); TreeSet<Long> set = new TreeSet<>(); long prev = -1; boolean flag = true; for (int i = 0; i < n; i++) { long x = sc.nextInt(); if (i == 0) { set.add(x); prev = x; continue; } if (x > prev) { Long high = set.higher(prev); if (high == null) set.add(x); else if (high >= x) set.add(x); else flag = false; } else if (x < prev) { Long low = set.lower(prev); if (low == null) set.add(x); else if (low <= x) set.add(x); else flag = false; } prev = x; } System.out.println(flag ? "YES" : "NO"); } } /*****************************************************************************/ static class CP { BufferedReader bufferedReader; StringTokenizer stringTokenizer; public CP() { bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } int nextInt() { return Integer.parseInt(NNNN()); } long nextLong() { return Long.parseLong(NNNN()); } double nextDouble() { return Double.parseDouble(NNNN()); } String NNNN() { while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) { try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return stringTokenizer.nextToken(); } String nextLine() { String spl = ""; try { spl = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } return spl; } } /*****************************************************************************/ }
import java.util.*; import java.io.*; public class _724 { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); TreeSet<Long> set = new TreeSet<>(); long prev = -1; boolean ok = true; for (int i = 0; i < n; i++) { long x = sc.nextInt(); if (i == 0) { set.add(x); prev = x; continue; } if (x > prev) { Long high = set.higher(prev); if (high == null) set.add(x); else if (high >= x) set.add(x); else { ok = false; } } else if (x < prev) { Long low = set.lower(prev); if (low == null) set.add(x); else if (low <= x) set.add(x); else { ok = false; } } prev = x; } out.println(ok ? "YES" : "NO"); } out.close(); } 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); } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
1
873828f7
ac8acb97
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int[] c=new int[n]; for(int i=0;i<n;i++) c[i]=sc.nextInt(); int[] mn= {Integer.MAX_VALUE,Integer.MAX_VALUE}; long[] rem= {(long)n,(long)n}; long sum=0; long ans=Long.MAX_VALUE; for(int i=0;i<n;i++) { mn[i%2]=Math.min(mn[i%2], c[i]); rem[i%2]--; sum+=c[i]; if(i>0) { long cur=sum+rem[0]*mn[0]+rem[1]*mn[1]; ans=Math.min(ans, cur); } } System.out.println(ans); } } }
import java.util.Scanner; public class C1499 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); // int[] arr = new int[n]; long[] mn = { Long.MAX_VALUE, Long.MAX_VALUE }; long[] rem = { n, n }; long sum = 0; long ans = Long.MAX_VALUE; for (int i = 0; i < n; i++) { int temp = in.nextInt(); mn[i % 2] = Math.min(mn[i % 2], temp); rem[i % 2]--; sum += temp; if (i > 0) { long cur = sum + rem[0] * mn[0] + rem[1] * mn[1]; ans = Math.min(ans, cur); } } System.out.println(ans); // int a = Integer.MAX_VALUE; // int aIndex = -1; // int b = Integer.MAX_VALUE; // int bIndex = -1; // // for (int i = 0; i < n; i++) { // arr[i] = in.nextInt(); // if (i % 2 == 0) { // if (arr[i] < a) { // a = arr[i]; // aIndex = i; // } // } else { // if (arr[i] < b) { // b = arr[i]; // bIndex = i; // } // } // } // int sum = 0; // for (int i = 0; i < Math.max(bIndex, aIndex) + 1; i++) { // if (i % 2 == 0) { // if (i == aIndex) { // if (aIndex < bIndex) { // sum += (n - (i / 2) - ((bIndex - aIndex) / 2)) * arr[i]; // } else { // sum += (n - (i / 2)) * arr[i]; // } // } else { // sum += arr[i]; // } // } else { // if (i == bIndex) { // if (bIndex < aIndex) { // sum += (n - (i / 2) - ((aIndex - bIndex) / 2)) * arr[i]; // } else { // sum += (n - (i / 2)) * arr[i]; // } // } else { // sum += arr[i]; // } // } // // } // System.out.println(sum); // for (int i = 0; i < n; i++) { // arr[i] = in.nextInt(); // if (arr[i] < a) { // a = arr[i]; // aIndex = i; // // } // // } // if (aIndex == 0) { // // for (int i = 1; i < n; i++) { // if (arr[i] < b) { // b = arr[i]; // bIndex = i; // } // } // System.out.println(aIndex + " " + bIndex); // System.out.println(a + " " + b); // int sum = 0; // for (int i = 1; i < bIndex; i++) { // sum += arr[i]; // } // sum += b * (n - bIndex + 1); // sum += a * n; // System.out.println(sum); // } else { // int b = Integer.MAX_VALUE; // int bIndex = -1; // for (int i = 0; i < aIndex; i++) { // if (arr[i] < b) { // b = arr[i]; // bIndex = i; // } // } // System.out.println(aIndex + " " + bIndex); // System.out.println(a + " " + b); // int sum = 0; // for (int i = 0; i < bIndex; i++) { // sum += arr[i]; // } // sum += b * (n - bIndex); // sum += a * n; // System.out.println(sum); // } } } }
1
1f6b81b1
51151974
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class InterestingStory { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader sc = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); int t = sc.nextInt(); // int t = 1; while (t-- != 0) { solver.solve(sc, out); } out.close(); } static class Solver { public void solve(InputReader sc, PrintWriter out) { int n = sc.nextInt(); char[][] words = new char[n][]; for(int i = 0; i < n; i++) words[i] = sc.next().toCharArray(); int[][] arr = new int[n][]; for(int i = 0; i < n; i++) { arr[i] = new int[words[i].length]; for(int j = 0; j < arr[i].length; j++) arr[i][j] = words[i][j]-'a'; } int max = 0; for(int now = 0; now < 5; now++) { PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); for(int i = 0; i < n; i++) { int nowcnt = 0; int othercnt = 0; for(int j = 0; j < arr[i].length; j++) { if(arr[i][j]==now) nowcnt++; else othercnt++; } pq.add(nowcnt-othercnt); } int canTake = 0; int sum = 0; while(!pq.isEmpty()) { int nowAdd = pq.poll(); if(sum+nowAdd>0) { sum += nowAdd; canTake++; } else { break; } } max = Math.max(max,canTake); } out.println(max); } } static void sort(int[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); } static void sort(long[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); } static void sortDec(int[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); int l = 0; int r = n - 1; while (l < r) { arr[l] ^= arr[r]; arr[r] ^= arr[l]; arr[l] ^= arr[r]; l++; r--; } } static void sortDec(long[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); int l = 0; int r = n - 1; while (l < r) { arr[l] ^= arr[r]; arr[r] ^= arr[l]; arr[l] ^= arr[r]; l++; r--; } } static class InputReader { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int peek() { if (numChars == -1) { return -1; } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } 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 long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long 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; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) { s = readLine0(); } return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) { return readLine(); } else { return readLine0(); } } public BigInteger readBigInteger() { try { return new BigInteger(nextString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) { read(); } return value == -1; } public String next() { return nextString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int[] nextSortedIntArray(int n) { int array[] = nextIntArray(n); Arrays.sort(array); return array; } public int[] nextSumIntArray(int n) { int[] array = new int[n]; array[0] = nextInt(); for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt(); return array; } public long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; ++i) array[i] = nextLong(); return array; } public long[] nextSumLongArray(int n) { long[] array = new long[n]; array[0] = nextInt(); for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt(); return array; } public long[] nextSortedLongArray(int n) { long array[] = nextLongArray(n); Arrays.sort(array); return array; } } }
import java.io.*; import java.util.*; public class Solution{ public static void main (String[] args) throws java.lang.Exception { FastReader sc = new FastReader(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int testCase = sc.nextInt(); while (testCase-->0){ int n = sc.nextInt(); String[] strArr = new String[n]; for(int i=0; i<n; i++) { strArr[i]=sc.nextLine(); } int[] total = new int[5]; ArrayList<int[]> al = new ArrayList<>(); for(int i=0; i<n; i++){ int[] arr= new int[5]; for(int j=0; j<strArr[i].length(); j++){ arr[strArr[i].charAt(j)-'a']++; } for(int j=0; j<5; j++){ total[j]+=arr[j]; } al.add(arr); } int ans=0; for(int i=0; i<5; i++){ ArrayList<Integer> all = new ArrayList<>(); for(int j=0; j<n; j++){ all.add(strArr[j].length()-2*al.get(j)[i]); } java.util.Collections.sort(all); int c=0, d=0; for(int j=0; j<n; j++){ c+=all.get(j); if(c<0) d=j+1; } ans = Math.max(ans,d); } System.out.println(ans); } } // Fast Reader Class 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; } } }
0
45f46b14
7b162d33
import java.util.*; public class Main { public static void main(String[] args){ Scanner scn = new Scanner(System.in); int t = scn.nextInt(); StringBuilder gs = new StringBuilder(""); for(int Z=0 ; Z<t ; Z++){ int n = scn.nextInt(); String[] str = new String[n]; Set<String> hs = new HashSet<>(); int minLen = Integer.MAX_VALUE; for(int i=0 ; i<n ; i++) { str[i] = scn.next(); hs.add(str[i]); minLen = Math.min(minLen, str[i].length()); } if(minLen == 1) gs.append("YES" + "\n"); else { boolean mark = false; for(int i=0 ; i<n ; i++) { if(str[i].length() == 2 && str[i].charAt(0) == str[i].charAt(1)) { mark = true; break; } String rev = ""; for(int j=str[i].length()-1 ; j>=0 ; j--) rev += str[i].charAt(j); if(hs.contains(rev)) { mark = true; break; } if(str[i].length() == 3) { String ans = rev.substring(1, rev.length()); if(hs.contains(ans)){ mark = true; break; } } if(str[i].length() < 3) { for(int k=0 ; k<26 ; k++) { String str1 = (char)(k + 'a') + rev; if(hs.contains(str1)) { mark= true; break; } } } hs.remove(str[i]); } if(!mark) gs.append("NO" + "\n"); else gs.append("YES" + "\n"); } } System.out.println(gs); } }
import java.util.*; public class Main { public static void main(String[] args){ Scanner scn = new Scanner(System.in); int t = scn.nextInt(); StringBuilder sb = new StringBuilder(""); for(int A=0 ; A<t ; A++){ int n = scn.nextInt(); String[] arr = new String[n]; Map<String, Integer> hm = new HashMap<>(); int min = 4; for(int i=0 ; i<n ; i++) { arr[i] = scn.next(); hm.put(arr[i], arr[i].length()); min = Math.min(min, arr[i].length()); } if(min == 1) sb.append("YES" + "\n"); else { boolean flag = false; for(int i=0 ; i<n ; i++) { if(arr[i].length() == 2 && arr[i].charAt(0) == arr[i].charAt(1)) { flag = true; break; } String s = ""; for(int j=arr[i].length()-1 ; j>=0 ; j--) s += arr[i].charAt(j); if(hm.containsKey(s)) { flag = true; break; } if(arr[i].length() < 3) { for(int k=0 ; k<26 ; k++) { String str = (char)(k + 'a') + s; if(hm.containsKey(str)) { flag= true; break; } } } if(arr[i].length() == 3) { String str = s.substring(1, s.length()); if(hm.containsKey(str)){ flag = true; break; } } hm.remove(arr[i]); } if(flag) sb.append("YES" + "\n"); else sb.append("NO" + "\n"); } } System.out.println(sb); } }
1
d55c238c
ebce9e39
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class First { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); //int a = 1; int t; t = in.nextInt(); //t = 1; while (t > 0) { //out.print("Case #"+(a++)+": "); solver.call(in,out); t--; } out.close(); } static class TaskA { public void call(InputReader in, PrintWriter out) { int n, m, x; n = in.nextInt(); m = in.nextInt(); x = in.nextInt(); int[] arr = new int[n]; answer[] array = new answer[n]; int[] ar = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); array[i] = new answer(arr[i],i); } long[] ans = new long[m]; Arrays.sort(array); int a = 0 , b = 0; while(true){ for (int i = 0; i < m; i++) { ar[b] = i+1; b++; if(b==n){ break; } } if(b==n){ break; } for (int i = m-1; i >= 0; i--) { ar[b] = i+1; b++; if(b==n){ break; } } if(b==n){ break; } } for (int i = 0; i < n; i++) { ans[ar[i]-1] += array[i].a; } for (int i = 0; i < m-1; i++) { if(Math.abs(ans[i]- ans[i+1])>x){ out.println("NO"); return; } } out.println("YES"); int[] answer = new int[n]; for (int i = 0; i < n; i++) { answer[array[i].b] = ar[i]; } for (int i = 0; i < n; i++) { out.print(answer[i]+" "); } out.println(); } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static class answer implements Comparable<answer>{ int a; int b; public answer(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(answer o) { return o.a - this.a; } @Override public boolean equals(Object o){ if(o instanceof answer){ answer c = (answer)o; return a == c.a && b == c.b; } return false; } } static class answer1 implements Comparable<answer1>{ int a, b, c; public answer1(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public int compareTo(answer1 o) { if(o.c==this.c){ return this.a - o.a; } return o.c - this.c; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (Long i:a) l.add(i); l.sort(Collections.reverseOrder()); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static final Random random=new Random(); static void shuffleSort(int[] a) { int n=a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } 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()); } } }
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class First { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); //int a = 1; int t; t = in.nextInt(); //t = 1; while (t > 0) { //out.print("Case #"+(a++)+": "); solver.call(in,out); t--; } out.close(); } static class TaskA { public void call(InputReader in, PrintWriter out) { int n, m, x; n = in.nextInt(); m = in.nextInt(); x = in.nextInt(); int[] arr = new int[n]; answer[] array = new answer[n]; int[] ar = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); array[i] = new answer(arr[i],i); } long[] ans = new long[m]; Arrays.sort(array); int a = 0 , b = 0; while(true){ for (int i = 0; i < m; i++) { ar[b] = i+1; b++; if(b==n){ break; } } if(b==n){ break; } for (int i = m-1; i >= 0; i--) { ar[b] = i+1; b++; if(b==n){ break; } } if(b==n){ break; } } for (int i = 0; i < n; i++) { ans[ar[i]-1] += array[i].a; } for (int i = 0; i < m-1; i++) { if(Math.abs(ans[i]- ans[i+1])>x){ out.println("NO"); return; } } out.println("YES"); int[] answer = new int[n]; for (int i = 0; i < n; i++) { answer[array[i].b] = ar[i]; } for (int i = 0; i < n; i++) { out.print(answer[i]+" "); } out.println(); } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static class answer implements Comparable<answer>{ int a; int b; public answer(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(answer o) { return o.a - this.a; } @Override public boolean equals(Object o){ if(o instanceof answer){ answer c = (answer)o; return a == c.a && b == c.b; } return false; } } static class answer1 implements Comparable<answer1>{ int a, b, c; public answer1(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public int compareTo(answer1 o) { if(o.c==this.c){ return this.a - o.a; } return o.c - this.c; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (Long i:a) l.add(i); l.sort(Collections.reverseOrder()); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static final Random random=new Random(); static void shuffleSort(int[] a) { int n=a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } 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()); } } }
1
c48673a6
ebed1250
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class C { public static void main(String[] args) { new C().solve(System.in, System.out); } public void solve(InputStream in, OutputStream out) { InputReader inputReader = new InputReader(in); PrintWriter writer = new PrintWriter(new BufferedOutputStream(out)); int t = inputReader.nextInt(); for (int t1 = 0; t1 < t; t1++) { int n = inputReader.nextInt(); List<Long> c = new ArrayList<>(n); for (int i = 0; i < n; i++) { c.add(inputReader.nextLong()); } writer.println(solve(n, c)); } writer.close(); } public long solve(int n, List<Long> c) { long[] minEven = new long[n]; long[] minOdd = new long[n]; long[] sumOdd = new long[n]; long[] sumEven = new long[n]; minEven[0] = Long.MAX_VALUE; minOdd[0] = Long.MAX_VALUE; for (int i = 0; i < n; i++) { if (i > 0) { minEven[i] = minEven[i - 1]; minOdd[i] = minOdd[i - 1]; sumOdd[i] = sumOdd[i - 1]; sumEven[i] = sumEven[i - 1]; } if (i % 2 == 0) { minEven[i] = Math.min(minEven[i], c.get(i)); sumEven[i] += c.get(i); } else { minOdd[i] = Math.min(minOdd[i], c.get(i)); sumOdd[i] += c.get(i); } } long best = Long.MAX_VALUE; for (int k = 1; k < n; k++) { int countOdd = (k + 1) / 2; int countEven = (k + 1) / 2; if (k % 2 == 0) { countEven++; } long oddResult = minOdd[k] * (n - countOdd) + sumOdd[k]; long evenResult = minEven[k] * (n - countEven) + sumEven[k]; long current = oddResult + evenResult; best = Math.min(best, current); } return best; } private 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()); } } }
import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class Main { private static void run() throws IOException { int n = in.nextInt(); long[] c = new long[n]; for (int i = 0; i < n; i++) { c[i] = in.nextInt(); } long ans = (c[0] + c[1]) * n; long sum = c[0] + c[1]; long[] min = {c[0], c[1]}; for (int i = 2; i < n; i++) { sum += c[i]; int index = i % 2; min[index] = Math.min(min[index], c[i]); int[] times = new int[2]; times[index] = n - (i / 2 + 1); times[index ^ 1] = n - ((i - 1) / 2 + 1); ans = Math.min(ans, sum + min[0] * times[0] + min[1] * times[1]); } out.println(ans); } public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(new OutputStreamWriter(System.out)); int t = in.nextInt(); for (int i = 0; i < t; i++) { run(); } out.flush(); in.close(); out.close(); } private static int gcd(int a, int b) { if (a == 0 || b == 0) return 0; while (b != 0) { int tmp; tmp = a % b; a = b; b = tmp; } return a; } static final long mod = 1000000007; static long pow_mod(long a, long b) { long result = 1; while (b != 0) { if ((b & 1) != 0) result = (result * a) % mod; a = (a * a) % mod; b >>= 1; } return result; } private static long multiplied_mod(long... longs) { long ans = 1; for (long now : longs) { ans = (ans * now) % mod; } return ans; } @SuppressWarnings("FieldCanBeLocal") private static Reader in; private static PrintWriter out; private static void print_array(int[] array) { for (int now : array) { out.print(now); out.print(' '); } out.println(); } private static void print_array(long[] array) { for (long now : array) { out.print(now); out.print(' '); } out.println(); } static class Reader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { final byte[] buf = new byte[1024]; // 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 nextSign() throws IOException { byte c = read(); while ('+' != c && '-' != c) { c = read(); } return '+' == c ? 0 : 1; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() throws IOException { int b; // noinspection ALL while ((b = read()) != -1 && isSpaceChar(b)) { ; } return b; } public char nc() throws IOException { return (char) skip(); } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') { c = read(); } final boolean neg = c == '-'; if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; } } private byte read() throws IOException { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } public void close() throws IOException { din.close(); } } }
0
0ca738ce
931faca2
import java.io.*; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class G { public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int t = 1; for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out); out.close(); } static class Task { static int max = (int) (4e5), MOD = 998244353; static long[] fact = new long[max+1], invFact = new long[max+1], naturalInverse = new long[max+1]; public void solve(int testNumber, FastReader scan, PrintWriter out) { int n = scan.nextInt(), k = scan.nextInt(); Item[] lanterns = new Item[2 * n]; for(int i = 0; i < n; i++) { int l = scan.nextInt(), r = scan.nextInt(); lanterns[i * 2] = new Item(l, 0); lanterns[i * 2 + 1] = new Item(r, 1); } Arrays.sort(lanterns); precomp(); int have = 0; long ans = 0; for(Item x : lanterns) { if(x.start == 1) have--; else { ans = (ans + binomial(have, k - 1)) % MOD; have++; } } out.println(ans); } static class Item implements Comparable<Item> { int val; int start; public Item(int a, int b) { val = a; start = b; } @Override public int compareTo(Item item) { int ret = Integer.compare(val, item.val); if(ret == 0) ret = Integer.compare(start, item.start); return ret; } } static void precomp() { fact[0] = invFact[0] = invFact[1] = naturalInverse[0] = naturalInverse[1] = 1; for(int i = 1; i <= max; i++) { fact[i] = (fact[i-1]*i)%MOD; if(i == 1) continue; naturalInverse[i] = naturalInverse[MOD % i] * (MOD - MOD/i) % MOD; invFact[i] = (invFact[i-1]*naturalInverse[i])%MOD; } } static long binomial(int a, int b) { if(a < b) return 0; return ((fact[a]*invFact[b])%MOD*invFact[a-b])%MOD; } } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } 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; } } }
import java.util.*; import java.io.*; import java.math.*; public class Main { static FastReader sc=new FastReader(); static int dp[][][][]; static int mod=1000000007; static int mod1=998244353; static int max; static long bit[]; static long seg[]; static long fact[]; static long A[]; static long[] fac = new long[300001]; static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) { //CHECK FOR N=1 //CHECK FOR N=1 //StringBuffer sb=new StringBuffer(""); int ttt=1; // ttt =i(); fac[0] = 1; for (int i = 1; i <= 300000; i++) fac[i] = fac[i - 1] * i % mod1; outer :while (ttt-- > 0) { int n=i(); int k=i(); Pair P[]=new Pair[2*n]; int c=0; for(int i=0;i<n;i++) { P[c]=new Pair(i(),0); c++; P[c]=new Pair(i(),1); c++; } Arrays.sort(P); int cnt=0; long ans=0; for(int i=0;i<2*n;i++) { if(P[i].y==0) cnt++; else { ans+=nCrModPFermat(cnt-1, k-1, mod1); ans%=mod1; cnt--; } } System.out.println(ans); } //System.out.println(sb.toString()); out.close(); //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 } static long modInverse(long n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static long nCrModPFermat(int n, int r, int p) { if (n<r) return 0; // Base case if (r == 0) return 1; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } static class Pair implements Comparable<Pair> { int x; int y; Pair(int x,int y){ this.x=x; this.y=y; } @Override public int compareTo(Pair o) { if(this.x>o.x) return +1; else if(this.x<o.x) return -1; else { if(this.y>o.y) return +1; else if(this.y<o.y) return -1; else return 0; } } // public int hashCode() // { // final int temp = 14; // int ans = 1; // ans =x*31+y*13; // return ans; // } // @Override // public boolean equals(Object o) // { // if (this == o) { // return true; // } // if (o == null) { // return false; // } // if (this.getClass() != o.getClass()) { // return false; // } // Pair other = (Pair)o; // if (this.x != other.x || this.y!=other.y) { // return false; // } // return true; // } // /* FOR TREE MAP PAIR USE */ // public int compareTo(Pair o) { // if (x > o.x) { // return 1; // } // if (x < o.x) { // return -1; // } // if (y > o.y) { // return 1; // } // if (y < o.y) { // return -1; // } // return 0; // } } //FENWICK TREE static void update(int i, int x){ for(; i < bit.length; i += (i&-i)) bit[i] += x; } static int sum(int i){ int ans = 0; for(; i > 0; i -= (i&-i)) ans += bit[i]; return ans; } //END //static void add(int v) { // if(!map.containsKey(v)) { // map.put(v, 1); // } // else { // map.put(v, map.get(v)+1); // } //} //static void remove(int v) { // if(map.containsKey(v)) { // map.put(v, map.get(v)-1); // if(map.get(v)==0) // map.remove(v); // } //} public static int upper(int A[],int k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { ans=mid; l=mid+1; } else { u=mid-1; } } return ans; } public static int lower(int A[],int k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { l=mid+1; } else { ans=mid; u=mid-1; } } return ans; } static int[] copy(int A[]) { int B[]=new int[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static long[] copy(long A[]) { long B[]=new long[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static long sum(int A[]) { long sum=0; for(int i : A) { sum+=i; } return sum; } static long sum(long A[]) { long sum=0; for(long i : A) { sum+=i; } return sum; } static void reverse(long A[]) { int n=A.length; long B[]=new long[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void reverse(int A[]) { int n=A.length; int B[]=new int[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void input(int A[],int B[]) { for(int i=0;i<A.length;i++) { A[i]=sc.nextInt(); B[i]=sc.nextInt(); } } static int[][] input(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]=i(); } } return A; } static char[][] charinput(int n,int m){ char A[][]=new char[n][m]; for(int i=0;i<n;i++) { String s=s(); for(int j=0;j<m;j++) { A[i][j]=s.charAt(j); } } return A; } static int find(int A[],int a) { if(A[a]==a) return a; return A[a]=find(A, A[a]); } static int max(int A[]) { int max=Integer.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static int min(int A[]) { int min=Integer.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long max(long A[]) { long max=Long.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static long min(long A[]) { long min=Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long [] prefix(long A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] prefix(int A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] suffix(long A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static long [] suffix(int A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static void fill(int dp[]) { Arrays.fill(dp, -1); } static void fill(int dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(int dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(int dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static void fill(long dp[]) { Arrays.fill(dp, -1); } static void fill(long dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(long dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(long dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static int min(int a,int b) { return Math.min(a, b); } static int min(int a,int b,int c) { return Math.min(a, Math.min(b, c)); } static int min(int a,int b,int c,int d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static int max(int a,int b) { return Math.max(a, b); } static int max(int a,int b,int c) { return Math.max(a, Math.max(b, c)); } static int max(int a,int b,int c,int d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long min(long a,long b) { return Math.min(a, b); } static long min(long a,long b,long c) { return Math.min(a, Math.min(b, c)); } static long min(long a,long b,long c,long d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static long max(long a,long b) { return Math.max(a, b); } static long max(long a,long b,long c) { return Math.max(a, Math.max(b, c)); } static long max(long a,long b,long c,long d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long power(long x, long y, long p) { if(y==0) return 1; if(x==0) return 0; long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static void print(int A[]) { for(int i : A) { System.out.print(i+" "); } System.out.println(); } static void print(long A[]) { for(long i : A) { System.out.print(i+" "); } System.out.println(); } static long mod(long x) { return ((x%mod + mod)%mod); } static String reverse(String s) { StringBuffer p=new StringBuffer(s); p.reverse(); return p.toString(); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static void sort(long[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static String sort(String s) { Character ch[]=new Character[s.length()]; for(int i=0;i<s.length();i++) { ch[i]=s.charAt(i); } Arrays.sort(ch); StringBuffer st=new StringBuffer(""); for(int i=0;i<s.length();i++) { st.append(ch[i]); } return st.toString(); } static HashMap<Integer,Integer> hash(int A[]){ HashMap<Integer,Integer> map=new HashMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Integer,Integer> tree(int A[]){ TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean prime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static 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; } } }
0
2b8f032c
a195911e
import java.io.*; import java.util.*; public class Main { static int INF = (int)1e9 + 1; public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out = new PrintWriter(System.out); /****** CODE STARTS HERE *****/ //-------------------------------------------------------------------------------------------------------- int t = fs.nextInt(); w:while(t-->0) { int n = fs.nextInt(); int[] k = fs.readArray(n); int[] h = fs.readArray(n); long ans = 0; int mtn = INF, prev = k[n-1]; for(int j=n-1; j>=0; j--) { if(mtn!=INF && mtn > k[j]) { int x = prev-mtn+1; ans += ((long)x*(x+1))/2; mtn = INF; prev = k[j]; } if(mtn >= k[j]-h[j]+1) mtn = k[j]-h[j]+1; if(j==0) { int x = prev-mtn+1; ans += ((long)x*(x+1))/2; } } out.println(ans); } out.close(); } //****** CODE ENDS HERE ***** //---------------------------------------------------------------------------------------------------------------- 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); } //----------- FastScanner class for faster input--------------------------- 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()); } } }
import java.util.*; import java.io.*; import java.math.*; public class Main { static FastReader sc=new FastReader(); static int dp[]; static boolean v[]; // static int mod=998244353;; static int mod=1000000007; static int max; static int bit[]; //static long fact[]; // static long A[]; static HashMap<Integer,Integer> map; //static StringBuffer sb=new StringBuffer(""); //static HashMap<Integer,Integer> map; static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) { // StringBuffer sb=new StringBuffer(""); int ttt=1; ttt =i(); outer :while (ttt-- > 0) { int n=i(); long A[]=inputL(n); long B[]=inputL(n); long C[]=new long[n]; for(int i=0;i<n;i++) { C[i]=A[i]-B[i]+1; } long min=C[n-1]; long ans=0; long last=A[n-1]; for(int i=n-1;i>=0;i--) { if(C[i]>min) { continue; } if(A[i]<min) { long y=last-min+1; ans+=y*(y+1)/2; last=A[i]; min=C[i]; continue; } min=C[i]; } long y=last-min+1; ans+=y*(y+1)/2; System.out.println(ans); } //System.out.println(sb.toString()); out.close(); //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 } static class Pair implements Comparable<Pair> { int x; int y; int z; Pair(int x,int y){ this.x=x; this.y=y; // this.z=z; } @Override public int compareTo(Pair o) { if(this.x>o.x) return 1; else if(this.x<o.x) return -1; else { if(this.y>o.y) return 1; else if(this.y<o.y) return -1; else return 0; } } public int hashCode() { final int temp = 14; int ans = 1; ans =x*31+y*13; return ans; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } if (this.getClass() != o.getClass()) { return false; } Pair other = (Pair)o; if (this.x != other.x || this.y!=other.y) { return false; } return true; } // /* FOR TREE MAP PAIR USE */ // public int compareTo(Pair o) { // if (x > o.x) { // return 1; // } // if (x < o.x) { // return -1; // } // if (y > o.y) { // return 1; // } // if (y < o.y) { // return -1; // } // return 0; // } } static int find(int A[],int a) { if(A[a]==a) return a; return A[a]=find(A, A[a]); } //static int find(int A[],int a) { // if(A[a]==a) // return a; // return find(A, A[a]); //} //FENWICK TREE static void update(int i, int x){ for(; i < bit.length; i += (i&-i)) bit[i] += x; } static int sum(int i){ int ans = 0; for(; i > 0; i -= (i&-i)) ans += bit[i]; return ans; } //END static void add(int v) { if(!map.containsKey(v)) { map.put(v, 1); } else { map.put(v, map.get(v)+1); } } static void remove(int v) { if(map.containsKey(v)) { map.put(v, map.get(v)-1); if(map.get(v)==0) map.remove(v); } } public static int upper(int A[],int k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { ans=mid; l=mid+1; } else { u=mid-1; } } return ans; } public static int lower(int A[],int k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { l=mid+1; } else { ans=mid; u=mid-1; } } return ans; } static int[] copy(int A[]) { int B[]=new int[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static long[] copy(long A[]) { long B[]=new long[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static long sum(int A[]) { long sum=0; for(int i : A) { sum+=i; } return sum; } static long sum(long A[]) { long sum=0; for(long i : A) { sum+=i; } return sum; } static void reverse(long A[]) { int n=A.length; long B[]=new long[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void reverse(int A[]) { int n=A.length; int B[]=new int[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void input(int A[],int B[]) { for(int i=0;i<A.length;i++) { A[i]=sc.nextInt(); B[i]=sc.nextInt(); } } static int[][] input(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]=i(); } } return A; } static char[][] charinput(int n,int m){ char A[][]=new char[n][m]; for(int i=0;i<n;i++) { String s=s(); for(int j=0;j<m;j++) { A[i][j]=s.charAt(j); } } return A; } static int nextPowerOf2(int n) { n--; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n++; return n; } static int highestPowerof2(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } static long highestPowerof2(long x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } static int max(int A[]) { int max=Integer.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static int min(int A[]) { int min=Integer.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long max(long A[]) { long max=Long.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static long min(long A[]) { long min=Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long [] prefix(long A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] prefix(int A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] suffix(long A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static long [] suffix(int A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static void fill(int dp[]) { Arrays.fill(dp, -1); } static void fill(int dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(int dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(int dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static void fill(long dp[]) { Arrays.fill(dp, -1); } static void fill(long dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(long dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(long dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static int min(int a,int b) { return Math.min(a, b); } static int min(int a,int b,int c) { return Math.min(a, Math.min(b, c)); } static int min(int a,int b,int c,int d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static int max(int a,int b) { return Math.max(a, b); } static int max(int a,int b,int c) { return Math.max(a, Math.max(b, c)); } static int max(int a,int b,int c,int d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long min(long a,long b) { return Math.min(a, b); } static long min(long a,long b,long c) { return Math.min(a, Math.min(b, c)); } static long min(long a,long b,long c,long d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static long max(long a,long b) { return Math.max(a, b); } static long max(long a,long b,long c) { return Math.max(a, Math.max(b, c)); } static long max(long a,long b,long c,long d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long power(long x, long y, long p) { if(y==0) return 1; if(x==0) return 0; long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long power(long x, long y) { if(y==0) return 1; if(x==0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y = y >> 1; x = (x * x); } return res; } static void print(int A[]) { for(int i : A) { out.print(i+" "); } out.println(); } static void print(long A[]) { for(long i : A) { System.out.print(i+" "); } System.out.println(); } static long mod(long x) { return ((x%mod + mod)%mod); } static String reverse(String s) { StringBuffer p=new StringBuffer(s); p.reverse(); return p.toString(); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static void sort(long[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static String sort(String s) { Character ch[]=new Character[s.length()]; for(int i=0;i<s.length();i++) { ch[i]=s.charAt(i); } Arrays.sort(ch); StringBuffer st=new StringBuffer(""); for(int i=0;i<s.length();i++) { st.append(ch[i]); } return st.toString(); } static HashMap<Integer,Integer> hash(int A[]){ HashMap<Integer,Integer> map=new HashMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static HashMap<Long,Integer> hash(long A[]){ HashMap<Long,Integer> map=new HashMap<Long, Integer>(); for(long i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Integer,Integer> tree(int A[]){ TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Long,Integer> tree(long A[]){ TreeMap<Long,Integer> map=new TreeMap<Long, Integer>(); for(long i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean prime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static 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; } } }
0
169e34bf
d9199dfd
import java.util.*; public class D{ static Scanner sc; public static void solve(){ int n=sc.nextInt(); Integer a[]=new Integer[n]; int flag; for(int i=0;i<n;i++) a[i]=sc.nextInt(); String s=sc.next(); ArrayList<Integer> x=new ArrayList<>(); ArrayList<Integer> y=new ArrayList<>(); for(int i=0;i<n;i++){ if(s.charAt(i)=='B') x.add(a[i]); else y.add(a[i]); } Collections.sort(x); Collections.sort(y); int p=n; int q=1; for(int i=y.size()-1;i>=0;i--){ if(y.get(i)>p){System.out.println("NO"); return;} p-=1; } for(int i=0;i<x.size();i++){ if(x.get(i)<q){System.out.println("NO"); return;} q+=1; } System.out.println("YES"); } public static void main(String args[]){ sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) solve(); } }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; public class Simple{ public static void main(String args[]){ //System.out.println("Hello Java"); Scanner s = new Scanner(System.in); int t = s.nextInt(); while (t>0){ int n = s.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++){ arr[i] = s.nextInt(); } String str = s.next(); //Arrays.sort(arr); ArrayList<Integer> blue = new ArrayList<>(); ArrayList<Integer> red = new ArrayList<>(); for(int i=0;i<n;i++){ if(str.charAt(i)=='R'){ red.add(arr[i]); } else{ blue.add(arr[i]); } } Collections.sort(red); Collections.sort(blue); int start =1; boolean bool =true; for(int i=0;i<blue.size();i++){ if(blue.get(i)<start){ bool = false; break; } start++; } if(!bool){ System.out.println("NO"); } else{ for(int i=0;i<red.size();i++){ if(red.get(i)>start){ bool = false; break; } start++; } if(bool){ System.out.println("YES"); } else{ System.out.println("NO"); } } t--; } s.close(); } }
0
161b4a40
da5cf40b
import java.util.*; import java.io.*; public class Main{ static final Random random=new Random(); static long mod=1000000007L; static HashMap<String,Integer>map=new HashMap<>(); 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; } int[] readIntArray(int n){ int[] res=new int[n]; for(int i=0;i<n;i++)res[i]=nextInt(); return res; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.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 void main(String[] args) { try { FastReader in=new FastReader(); FastWriter out = new FastWriter(); int testCases=in.nextInt(); //int testCases=1; while(testCases-- > 0){ solve(in); } out.close(); } catch (Exception e) { return; } } public static void solve( FastReader in){ int n=in.nextInt(); String s=in.next(); String t=in.next(); //int k=in.nextInt(); //long y=in.nextInt(); //long n=in.nextLong(); //int k=in.nextInt(); //long k=in.nextLong(); StringBuilder res=new StringBuilder(); char[] s1=s.toCharArray(); char[] t1=t.toCharArray(); int ans=n+2; int[] cnt={0,0}; for(int i=0;i<n;i++){ if(s1[i]=='0' && t1[i]=='1'){ cnt[0]++; } if(s1[i]=='1' && t1[i]=='0'){ cnt[1]++; } } if(cnt[0]==cnt[1])ans=Math.min(ans,cnt[0]+cnt[1]); cnt[0]=cnt[1]=0; for(int i=0;i<n;i++){ if(s1[i]=='0' && t1[i]=='0'){ cnt[0]++; } if(s1[i]=='1' && t1[i]=='1'){ cnt[1]++; } } if(cnt[1]==cnt[0]+1){ ans=Math.min(ans,cnt[0]+cnt[1]); } if(ans>n){ res.append("-1"); } else{ res.append(""+ans); } //int ans=x.size()+y.size(); //res.append(""+"Yes"); //res.append(""+""); System.out.println(res.toString()); } static int gcd(int a,int b){ if(b==0){ return a; } return gcd(b,a%b); } static void sort(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } static void reversesort(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); Collections.reverse(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static void debug(String x){ System.out.println(x); } static < E > void print(E res) { System.out.println(res); } static String rString(String s){ StringBuilder sb=new StringBuilder(); sb.append(s); return sb.reverse().toString(); } }
/***** ---> :) Vijender Srivastava (: <--- *****/ import java.util.*; import java.lang.*; import java.io.*; public class Main { static FastReader sc =new FastReader(); static PrintWriter out=new PrintWriter(System.out); static long mod=(long)1e9+7; /* start */ public static void main(String [] args) { // int testcases = 1; int testcases = i(); while(testcases-->0) { solve(); } out.flush(); out.close(); } static void solve() { int n = i(); char c[] = inputC(); char d[] = inputC(); int x01=0,x10=0,x00=0,x11=0; for(int i=0;i<n;i++) { if(c[i]=='0'&&d[i]=='0')x00++; if(c[i]=='0'&&d[i]=='1')x01++; if(c[i]=='1'&&d[i]=='0')x10++; if(c[i]=='1'&&d[i]=='1')x11++; } int ans = Integer.MAX_VALUE; if(x01==0 && x10==0) { pl(0); return ; } if(x11==x00+1) { ans = min(x11+x00,ans); } if(x01==x10) { ans = min(x01+x10,ans); } if(ans == Integer.MAX_VALUE){ ans = -1; } pl(ans); } /* end */ 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 void p(Object o) { out.print(o); } static void pl(Object o) { out.println(o); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static char[] inputC() { String s = sc.nextLine(); return s.toCharArray(); } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static long[] putL(long a[]) { long A[]=new long[a.length]; for(int i=0;i<a.length;i++) { A[i]=a[i]; } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static String reverse(String s) { StringBuffer p=new StringBuffer(s); p.reverse(); return p.toString(); } static int min(int a,int b) { return Math.min(a, b); } static int min(int a,int b,int c) { return Math.min(a, Math.min(b, c)); } static int min(int a,int b,int c,int d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static int max(int a,int b) { return Math.max(a, b); } static int max(int a,int b,int c) { return Math.max(a, Math.max(b, c)); } static int max(int a,int b,int c,int d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long min(long a,long b) { return Math.min(a, b); } static long min(long a,long b,long c) { return Math.min(a, Math.min(b, c)); } static long min(long a,long b,long c,long d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static long max(long a,long b) { return Math.max(a, b); } static long max(long a,long b,long c) { return Math.max(a, Math.max(b, c)); } static long max(long a,long b,long c,long d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long sum(int A[]) { long sum=0; for(int i : A) { sum+=i; } return sum; } static long sum(long A[]) { long sum=0; for(long i : A) { sum+=i; } return sum; } static void print(int A[]) { for(int i : A) { System.out.print(i+" "); } System.out.println(); } static void print(long A[]) { for(long i : A) { System.out.print(i+" "); } System.out.println(); } static long mod(long x) { return ((x%mod + mod)%mod); } static long power(long x, long y) { if(y==0) return 1; if(x==0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x) ; y = y >> 1; x = (x * x); } return res; } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean prime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long[] sort(long a[]) { ArrayList<Long> arr = new ArrayList<>(); for(long i : a) { arr.add(i); } Collections.sort(arr); for(int i = 0; i < arr.size(); i++) { a[i] = arr.get(i); } return a; } static int[] sort(int a[]) { ArrayList<Integer> arr = new ArrayList<>(); for(Integer i : a) { arr.add(i); } Collections.sort(arr); for(int i = 0; i < arr.size(); i++) { a[i] = arr.get(i); } return a; } //pair class private static class Pair implements Comparable<Pair> { long first, second; public Pair(long f, long s) { first = f; second = s; } @Override public int compareTo(Pair p) { if (first > p.first) return 1; else if (first < p.first) return -1; else { if (second > p.second) return 1; else if (second < p.second) return -1; else return 0; } } } }
0
312d9460
e7024f3e
//https://codeforces.com/contest/1547/problem/E //E. Air Conditioners import java.util.*; import java.io.*; public class CF_1547_E{ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(); StringTokenizer st, st1; int q = Integer.parseInt(br.readLine()); while(q-->0){ br.readLine(); st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); PriorityQueue<Pair> right_side = new PriorityQueue<Pair>(); int at[] = new int[n+1]; st = new StringTokenizer(br.readLine()); st1 = new StringTokenizer(br.readLine()); for(int i=0;i<k;i++){ int a = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st1.nextToken()); at[a] = t; right_side.add(new Pair(a, t)); } long left= Integer.MAX_VALUE; for(int i=1;i<=n;i++){ while(right_side.isEmpty()==false && right_side.peek().a<=i){ Pair temp = right_side.poll(); if(temp.t - temp.a <= left) left = temp.t - temp.a; } if(at[i]!=0){ if(at[i]-i <=left) left = at[i] - i; } long ans = left+i; if(!right_side.isEmpty()){ Pair right = right_side.peek(); ans = Math.min(ans, right.t+right.a-i); } sb.append(ans+" "); } sb.append("\n"); } pw.print(sb); pw.flush(); pw.close(); } } class Pair implements Comparable<Pair>{ int a, t; Pair(int a, int t){ this.a = a; this.t = t; } public int compareTo(Pair A){ return (this.a+this.t-A.a-A.t); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static String solve(int n, int k, int[] a, int[] t) { Pair[] pairs = new Pair[k]; for (int i = 0; i < k; i++) { pairs[i] = new Pair(a[i], t[i]); } Arrays.sort(pairs); int[] ret = new int[n + 1]; Arrays.fill(ret, Integer.MAX_VALUE); int pIdx = 0; int ct = pairs[pIdx].t; ret[pairs[pIdx].a] = ct; for (int i = pairs[pIdx].a + 1; i <= n; i++) { ct++; if (pIdx + 1 < k && pairs[pIdx + 1].a == i) { if (ct > pairs[pIdx + 1].t) { ct = pairs[pIdx + 1].t; } pIdx++; } ret[i] = ct; // System.out.println(Arrays.toString(ret)); } // System.out.println(); pIdx = k - 1; ct = pairs[pIdx].t; for (int i = pairs[pIdx].a - 1; i > 0; i--) { ct++; if (pIdx - 1 >= 0 && pairs[pIdx - 1].a == i) { if (ct > pairs[pIdx - 1].t) { ct = pairs[pIdx - 1].t; } pIdx--; } if (ct < ret[i]) { ret[i] = ct; } // System.out.println(Arrays.toString(ret)); } StringBuilder out = new StringBuilder(); for (int i = 1; i <= n; i++) { out.append(ret[i]).append(" "); } // System.out.println(); // System.out.println(); return out.toString(); } static class Pair implements Comparable<Pair> { int a, t; public Pair(int a, int t) { this.a = a; this.t = t; } @Override public int compareTo(Pair o) { return this.a - o.a; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); StringBuilder out = new StringBuilder(); int T = Integer.parseInt(st.nextToken()); while (T-- > 0) { st = new StringTokenizer(br.readLine()); st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] a = new int[k]; for (int i = 0; i < k; i++) { a[i] = Integer.parseInt(st.nextToken()); } st = new StringTokenizer(br.readLine()); int[] t = new int[k]; for (int i = 0; i < k; i++) { t[i] = Integer.parseInt(st.nextToken()); } out.append(solve(n, k, a, t)).append("\n"); } System.out.println(out); } }
0
7974ffba
94b3b86d
import java.util.*; import java.io.*; import java.math.*; public class Euler { static int N = (int)1e5 + 5; static int n, a, b, da, db; static int[] depth = new int[N]; static ArrayList<Integer>[] adj = new ArrayList[N]; static int diam; public static int dfs(int x, int p) { int len = 0; for (int y : adj[x]) { if (y != p) { depth[y] = depth[x] + 1; int cur = 1 + dfs(y, x); diam = Math.max(diam, cur + len); len = Math.max(len, cur); } } return len; } public static void main(String[] args){ FastReader in = new FastReader(); PrintWriter o = new PrintWriter(System.out); int t = in.nextInt(); while(t-- > 0) { n = in.nextInt(); a = in.nextInt(); b = in.nextInt(); da = in.nextInt(); db = in.nextInt(); for (int i = 1; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int u = in.nextInt(); int v = in.nextInt(); adj[u].add(v); adj[v].add(u); } diam = 0; depth[a] = 0; dfs(a, -1); boolean works = true; if (depth[b] <= da) { o.println("Alice"); continue; } if (2 * da >= diam) { o.println("Alice"); continue; } if (db > 2 * da) { o.println("Bob"); continue; } if (db <= 2 * da) { o.println("Alice"); } } o.close(); o.flush(); return; } 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; } } }
import java.io.*; import java.util.*; public class D { public static ArrayList<Integer> adj[]; public static int node; public static int dist = 0; public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); int T = sc.nextInt(); PrintWriter out = new PrintWriter(System.out); for(int t = 0; t < T; t++){ int N = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int da = sc.nextInt(); int db = sc.nextInt(); adj = new ArrayList[N+1]; for(int i = 0; i <= N; i++){ adj[i] = new ArrayList<Integer>(); } for(int i = 0; i < N-1; i++){ int v = sc.nextInt(); int u = sc.nextInt(); adj[v].add(u); adj[u].add(v); } if(db > 2*da){ dfs1(a, 0, b, 0); if(dist <= da){ out.println("Alice"); } else{ node = 0; dist = 0; dfs(1, 0, 0); dfs(node, 0, 0); if(dist > 2*da){ out.println("Bob"); } else{ out.println("Alice"); } } } else{ out.println("Alice"); } } out.close(); } public static void dfs1(int a, int p, int b, int d){ if(a == b){ dist = d; } for(int next : adj[a]){ if(next != p){ dfs1(next, a, b, d+1); } } } public static void dfs(int i, int p, int d){ if(d > dist){ node = i; dist = d; } for(int next : adj[i]){ if(next != p){ dfs(next, i, d+1); } } } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static void ASSERT(boolean assertion, String message) { if (!assertion) throw new AssertionError(message); } }
0
8f30bfc3
af1b152e
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.List; import java.util.StringJoiner; public class Solution { private static List<Long> chairs; private static List<Long> folks; private static Long[] data; private static Long[][] cache; public static void main(String[] args) { Print print = new Print(); Scan scan = new Scan(); int n = scan.scanInt(); data = scan.scan1dLongArray(); chairs = new ArrayList<>(); folks = new ArrayList<>(); cache = new Long[n][n]; for (int i = 0; i < n; i++) { if (data[i] == 0) { chairs.add((long) i); } else { folks.add((long) i); } } print.printLine(Long.toString(solve(folks, chairs, 0, 0))); print.close(); } private static long solve(List<Long> folks, List<Long> chairs, int i, int j) { if (i == folks.size()) { return 0; } if (j == chairs.size()) { return Integer.MAX_VALUE; } if (cache[i][j] != null) { return cache[i][j]; } return cache[i][j] = Math .min(Math.abs(folks.get(i) - chairs.get(j)) + solve(folks, chairs, i + 1, j + 1), solve(folks, chairs, i, j + 1)); } static class Scan { private byte[] buf = new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in = System.in; } public int scan() { if (total < 0) { throw new InputMismatchException(); } if (index >= total) { index = 0; try { total = in.read(buf); } catch (IOException ignored) { } if (total <= 0) { return -1; } } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) { n = scan(); } int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } else { throw new InputMismatchException(); } } return neg * integer; } public double scanDouble() { double doub = 0; int n = scan(); while (isWhiteSpace(n)) { n = scan(); } int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n) && n != '.') { if (n >= '0' && n <= '9') { doub *= 10; doub += n - '0'; n = scan(); } else { throw new InputMismatchException(); } } if (n == '.') { n = scan(); double temp = 1; while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { temp /= 10; doub += (n - '0') * temp; n = scan(); } else { throw new InputMismatchException(); } } } return doub * neg; } public Integer[] scan1dIntArray() { String[] s = this.scanString().split(" "); Integer[] arr = new Integer[s.length]; for (int i = 0; i < s.length; i++) { arr[i] = Integer.parseInt(s[i]); } return arr; } public Integer[][] scan2dIntArray(int n, int m) { Integer[][] arr = new Integer[n][m]; for (int i = 0; i < n; i++) { String[] s = this.scanString().split(" "); for (int j = 0; j < m; j++) { arr[i][j] = Integer.parseInt(s[j]); } } return arr; } public String[] scan1dStringArray() { return this.scanString().split(" "); } public String[][] scan2dStringArray(int n, int m) { String[][] arr = new String[n][m]; for (int i = 0; i < n; i++) { String[] s = this.scanString().split(" "); for (int j = 0; j < m; j++) { arr[i][j] = s[j]; } } return arr; } public char[] scan1dCharArray() { return this.scanString().toCharArray(); } public char[][] scan2dCharArray(int n, int m) { char[][] arr = new char[n][m]; for (int i = 0; i < n; i++) { char[] s = this.scanString().toCharArray(); for (int j = 0; j < m; j++) { arr[i][j] = s[j]; } } return arr; } public Long[] scan1dLongArray() { String[] s = this.scanString().split(" "); Long[] arr = new Long[s.length]; for (int i = 0; i < s.length; i++) { arr[i] = Long.parseLong(s[i]); } return arr; } public Long[][] scan2dLongArray(int n, int m) { Long[][] arr = new Long[n][m]; for (int i = 0; i < n; i++) { String[] s = this.scanString().split(" "); for (int j = 0; j < m; j++) { arr[i][j] = Long.parseLong(s[j]); } } return arr; } public String scanString() { StringBuilder sb = new StringBuilder(); int n = scan(); while (isWhiteSpace(n)) { n = scan(); } while (!isWhiteSpace(n)) { sb.append((char) n); n = scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if (n == '\n' || n == '\r' || n == '\t' || n == -1) { return true; } return false; } } static class Print { private final BufferedWriter bw; public Print() { bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(String str) { try { bw.append(str); } catch (IOException ignored) { } } public void printLine(Integer[] arr) { StringJoiner sj = new StringJoiner(" "); for (Integer x : arr) { sj.add(Integer.toString(x)); } printLine(sj.toString()); } public void printLine(Integer[][] arr) { for (Integer[] x : arr) { StringJoiner sj = new StringJoiner(" "); for (Integer y : x) { sj.add(Integer.toString(y)); } printLine(sj.toString()); } } public void printLine(String[] arr) { StringJoiner sj = new StringJoiner(" "); for (String x : arr) { sj.add(x); } printLine(sj.toString()); } public void printLine(String[][] arr) { for (String[] x : arr) { StringJoiner sj = new StringJoiner(" "); for (String y : x) { sj.add(y); } printLine(sj.toString()); } } public void printLine(char[] arr) { StringJoiner sj = new StringJoiner(" "); for (char x : arr) { sj.add(Character.toString(x)); } printLine(sj.toString()); } public void printLine(char[][] arr) { for (char[] x : arr) { StringJoiner sj = new StringJoiner(" "); for (char y : x) { sj.add(Character.toString(y)); } printLine(sj.toString()); } } public void printLine(Long[] arr) { StringJoiner sj = new StringJoiner(" "); for (Long x : arr) { sj.add(Long.toString(x)); } printLine(sj.toString()); } public void printLine(Long[][] arr) { for (Long[] x : arr) { StringJoiner sj = new StringJoiner(" "); for (Long y : x) { sj.add(Long.toString(y)); } printLine(sj.toString()); } } public void printLine(String str) { print(str); try { bw.append("\n"); } catch (IOException ignored) { } } public void close() { try { bw.close(); } catch (IOException ignored) { } } } }
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.List; import java.util.StringJoiner; public class D { private static List<Long> chairs; private static List<Long> folks; private static Long[] data; private static Long[][] cache; public static void main(String[] args) { Print print = new Print(); Scan scan = new Scan(); int n = scan.scanInt(); data = scan.scan1dLongArray(); chairs = new ArrayList<>(); folks = new ArrayList<>(); cache = new Long[n][n]; for (int i = 0; i < n; i++) { if (data[i] == 0) { chairs.add((long) i); } else { folks.add((long) i); } } print.printLine(Long.toString(solve(folks, chairs, 0, 0))); print.close(); } private static long solve(List<Long> folks, List<Long> chairs, int i, int j) { if (i == folks.size()) { return 0; } if (j == chairs.size()) { return Integer.MAX_VALUE; } if (cache[i][j] != null) { return cache[i][j]; } return cache[i][j] = Math .min(Math.abs(folks.get(i) - chairs.get(j)) + solve(folks, chairs, i + 1, j + 1), solve(folks, chairs, i, j + 1)); } static class Scan { private byte[] buf = new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in = System.in; } public int scan() { if (total < 0) { throw new InputMismatchException(); } if (index >= total) { index = 0; try { total = in.read(buf); } catch (IOException ignored) { } if (total <= 0) { return -1; } } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) { n = scan(); } int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } else { throw new InputMismatchException(); } } return neg * integer; } public double scanDouble() { double doub = 0; int n = scan(); while (isWhiteSpace(n)) { n = scan(); } int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n) && n != '.') { if (n >= '0' && n <= '9') { doub *= 10; doub += n - '0'; n = scan(); } else { throw new InputMismatchException(); } } if (n == '.') { n = scan(); double temp = 1; while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { temp /= 10; doub += (n - '0') * temp; n = scan(); } else { throw new InputMismatchException(); } } } return doub * neg; } public Integer[] scan1dIntArray() { String[] s = this.scanString().split(" "); Integer[] arr = new Integer[s.length]; for (int i = 0; i < s.length; i++) { arr[i] = Integer.parseInt(s[i]); } return arr; } public Integer[][] scan2dIntArray(int n, int m) { Integer[][] arr = new Integer[n][m]; for (int i = 0; i < n; i++) { String[] s = this.scanString().split(" "); for (int j = 0; j < m; j++) { arr[i][j] = Integer.parseInt(s[j]); } } return arr; } public String[] scan1dStringArray() { return this.scanString().split(" "); } public String[][] scan2dStringArray(int n, int m) { String[][] arr = new String[n][m]; for (int i = 0; i < n; i++) { String[] s = this.scanString().split(" "); for (int j = 0; j < m; j++) { arr[i][j] = s[j]; } } return arr; } public char[] scan1dCharArray() { return this.scanString().toCharArray(); } public char[][] scan2dCharArray(int n, int m) { char[][] arr = new char[n][m]; for (int i = 0; i < n; i++) { char[] s = this.scanString().toCharArray(); for (int j = 0; j < m; j++) { arr[i][j] = s[j]; } } return arr; } public Long[] scan1dLongArray() { String[] s = this.scanString().split(" "); Long[] arr = new Long[s.length]; for (int i = 0; i < s.length; i++) { arr[i] = Long.parseLong(s[i]); } return arr; } public Long[][] scan2dLongArray(int n, int m) { Long[][] arr = new Long[n][m]; for (int i = 0; i < n; i++) { String[] s = this.scanString().split(" "); for (int j = 0; j < m; j++) { arr[i][j] = Long.parseLong(s[j]); } } return arr; } public String scanString() { StringBuilder sb = new StringBuilder(); int n = scan(); while (isWhiteSpace(n)) { n = scan(); } while (!isWhiteSpace(n)) { sb.append((char) n); n = scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if (n == '\n' || n == '\r' || n == '\t' || n == -1) { return true; } return false; } } static class Print { private final BufferedWriter bw; public Print() { bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(String str) { try { bw.append(str); } catch (IOException ignored) { } } public void printLine(Integer[] arr) { StringJoiner sj = new StringJoiner(" "); for (Integer x : arr) { sj.add(Integer.toString(x)); } printLine(sj.toString()); } public void printLine(Integer[][] arr) { for (Integer[] x : arr) { StringJoiner sj = new StringJoiner(" "); for (Integer y : x) { sj.add(Integer.toString(y)); } printLine(sj.toString()); } } public void printLine(String[] arr) { StringJoiner sj = new StringJoiner(" "); for (String x : arr) { sj.add(x); } printLine(sj.toString()); } public void printLine(String[][] arr) { for (String[] x : arr) { StringJoiner sj = new StringJoiner(" "); for (String y : x) { sj.add(y); } printLine(sj.toString()); } } public void printLine(char[] arr) { StringJoiner sj = new StringJoiner(" "); for (char x : arr) { sj.add(Character.toString(x)); } printLine(sj.toString()); } public void printLine(char[][] arr) { for (char[] x : arr) { StringJoiner sj = new StringJoiner(" "); for (char y : x) { sj.add(Character.toString(y)); } printLine(sj.toString()); } } public void printLine(Long[] arr) { StringJoiner sj = new StringJoiner(" "); for (Long x : arr) { sj.add(Long.toString(x)); } printLine(sj.toString()); } public void printLine(Long[][] arr) { for (Long[] x : arr) { StringJoiner sj = new StringJoiner(" "); for (Long y : x) { sj.add(Long.toString(y)); } printLine(sj.toString()); } } public void printLine(String str) { print(str); try { bw.append("\n"); } catch (IOException ignored) { } } public void close() { try { bw.close(); } catch (IOException ignored) { } } } }
1
18e2441c
24b20554
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Map; import java.util.HashMap; public class cf1515 { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } static class Task { public void solve(InputReader in, PrintWriter out) { int t = in.nextInt(); while (t-- != 0) { int n = in.nextInt(); int m = in.nextInt(); int x = in.nextInt(); TreeMap<Integer, ArrayList<Integer>> map = new TreeMap<>(); for (int i = 0; i < n; i++) { int j = in.nextInt(); if (!map.containsKey(j)) { map.put(j, new ArrayList<Integer>()); } map.get(j).add(i); } out.println("YES"); int[] ans = new int[n]; int sta = 0; for (int s : map.keySet()) { for (int i = 0; i < map.get(s).size(); i++) { ans[map.get(s).get(i)] = (sta++) % m + 1; } } for(int i=0;i<n;i++) { out.print(ans[i]+" "); } out.println(); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreElements()) { 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()); } } }
import java.util.*; import java.lang.*; public class Codeforces { static Scanner sr=new Scanner(System.in); public static void main(String[] args) throws java.lang.Exception { StringBuilder ans = new StringBuilder(""); int T = sr.nextInt(); while (T-- > 0) { int n=sr.nextInt(); int m=sr.nextInt(); int x=sr.nextInt(); TreeMap<Integer,ArrayList<Integer>>h=new TreeMap<>(); for(int i=0;i<n;i++) { int a=sr.nextInt(); if(!h.containsKey(a)) h.put(a,new ArrayList<>()); h.get(a).add(i); } ans.append("YES"); ans.append('\n'); int an[]=new int[n]; int q=0; for(int z:h.keySet()) { for(int i=0;i<h.get(z).size();i++) { an[h.get(z).get(i)]=(q++)%m+1; } } for(int i=0;i<n;i++) ans.append(an[i]+" "); ans.append('\n'); } System.out.println(ans); } }
1
28d8c381
417833c3
import java.io.*; import java.sql.SQLOutput; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int numCases = Integer.parseInt(br.readLine()); for (int i = 0; i < numCases; i++) { int length = Integer.parseInt(br.readLine()); int found = 0; int[] ret = new int[length + 1]; for (int j = 1; j <= length; j++) { if (found == length - 1) { break; } if (ret[j] == 0) { System.out.println("? " + j); System.out.flush(); int start = Integer.parseInt(br.readLine()); int lastNum = start; boolean cont = true; while (cont) { System.out.println("? " + j); System.out.flush(); int num = Integer.parseInt(br.readLine()); ret[lastNum] = num; found++; lastNum = num; if (num == start) cont = false; } } } for (int j = 0; j <= length; j++) if (ret[j] == 0) ret[j] = j; System.out.print("! "); for (int j = 1; j <= length; j++) System.out.print(ret[j] + " "); System.out.println(); } br.close(); } }
import java.io.*; import java.util.*; import java.math.*; import java.math.BigInteger; public final class B { static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); static ArrayList<Integer> g[]; static long mod=(long)998244353,INF=Long.MAX_VALUE; // static boolean set[]; static int par[],partial[]; static int Days[],P[][]; static int sum=0,size[]; static int seg[],col[]; // static ArrayList<Long> A; static char X[][]; static boolean set[][]; static int D[],min[],A[]; static long dp[][]; // static HashSet<Integer> visited,imposters; // static HashSet<Integer> set; // static node1 seg[]; //static pair moves[]= {new pair(-1,0),new pair(1,0), new pair(0,-1), new pair(0,1)}; public static void main(String args[])throws IOException { /* * star,rope,TPST * BS,LST,MS,MQ */ int T=i(); outer:while(T-->0) { int N=i(); int f[]=new int[N+5]; int ask=ask(1); HashSet<Integer> set=new HashSet<>(); int cnt=0; for(int i=1; i<=N; i++) { if(cnt+1==N) { set=new HashSet<>(); for( i=0; i<=N; i++)set.add(i); for( i=1; i<=N; i++)set.remove(f[i]); int a=-1; for(int v:set) { a=v; } for(i=1; i<=N; i++) { if(f[i]==0)f[i]=a; } break; } if(f[i]==0) { int last=0; set=new HashSet<>(); while(true) { int a=ask(i); f[last]=a; if(set.contains(a)) { break; } last=a; set.add(a); } cnt+=set.size(); } } for(int i=1; i<=N; i++) { ans.append(f[i]+" "); } System.out.println("! "+ans); ans=new StringBuilder(); } out.println(ans); out.close(); } static int ask(int a) { System.out.println("? "+a); // out.flush(); return i(); } static boolean f(String A,String B) { char X[]=A.toCharArray(),Y[]=B.toCharArray(); if(X[X.length-1]=='0' && A.length()==B.length()) { return A.equals(B); } else if(X[X.length-1]=='0') { for(int i=0; i<Y.length-X.length; i++) { boolean f=true; for(int j=0; j<X.length; j++) { if(X[j]!=Y[i+j]) { f=false; } } if(f) { for(int j=0; j<i; j++) { if(Y[j]=='0')f=false; } for(int j=i+X.length; j<Y.length; j++) { if(Y[j]=='0')f=false; } if(f) { // System.out.println(B.substring(i+X.length)); return true; } } } return false; } else { for(int i=0; i<=Y.length-X.length; i++) { boolean f=true; for(int j=0; j<X.length; j++) { if(X[j]!=Y[i+j]) { f=false; } } if(f) { for(int j=0; j<i; j++) { if(Y[j]=='0')f=false; } for(int j=i+X.length; j<Y.length; j++) { if(Y[j]=='0')f=false; } if(f) { // System.out.println(B.substring(i+X.length)); return true; } } } return false; } } static String reverse (String X) { StringBuilder sb=new StringBuilder(X); return sb.reverse().toString(); } static String binary(long x) { String str=""; long p=1L; while(p<=x) { if((p&x)!=0)str="1"+str; else str="0"+str; p<<=1; } return str; } static boolean can_loose(Trie root,boolean t) { if(root==null)return true; //never hits int cnt=0; for(Trie x:root.A) { if(x!=null) { cnt++; if(!can_loose(x,t^true)) { //System.out.println("TRUE FOR--> "+x.ch+" "+t); return true; } } } if(cnt==0)return true; return false; } static boolean f(Trie root) { if(root==null)return false; // int cnt=0; for(Trie x:root.A) { if(x!=null) { // cnt++; if(!f(x)) { return true; } } } return false; } static void insert(String X,Trie head) { Trie root=head; for(char x:X.toCharArray()) { int a=x-'a'; if(root.A[a]==null)root.A[a]=new Trie(); root=root.A[a]; root.ch=x; } root.ends=true; } static boolean search(String X,Trie head) { Trie root=head; for(char x:X.toCharArray()) { int a=x-'a'; if(root.A[a]==null)return false; root=root.A[a]; } return root.ends; } static boolean starts_with(String X,Trie head) { Trie root=head; for(char x:X.toCharArray()) { int a=x-'a'; if(root.A[a]==null)return false; root=root.A[a]; } return true; } static int lower(ArrayList<Integer>A,int i) { int l=-1,r=A.size(); while(r-l>1) { int m=(l+r)/2; if(A.get(m)>i)r=m; else l=m; } return r; } static int upper(ArrayList<Integer>A,int i) { int l=-1,r=A.size(); while(r-l>1) { int m=(l+r)/2; if(A.get(m)<i)l=m; else l=m; } return l; } static String f() { StringBuilder X=new StringBuilder(i()+"");int p=i(); while(p-->0)X.append("0"); return X.toString(); } static long f(int i,int g,int x,int left) { if(x<=1)return left; if(i<0 || g==1)return left; // System.out.println(i+" "+g); if(dp[i][g]==0) { int next=min[i]; int new_gcd=(int)GCD(g,x); //System.out.println(" factor--> "+x+" gcd--> "+g+" new--> "+new_gcd); long s=0; int c=0; for(int j=next+1; j<=i; j++) { if(A[i]%new_gcd==0) { s+=new_gcd; c--; } } long a=0,b=0; a=f(i,g,x-1,left); b=s+f(next,new_gcd,x-1,left-c); dp[i][g]=Math.max(a, b); } return dp[i][g]; } static boolean f(int A[],int B[],int x) { int c=0; int N=A.length; int l=0,r=x-1; for(int i=0; i<N; i++) { if(A[i]>=r && B[i]>=l) { r--; l++; c++; } if(c>=x)return true; } return false; } static boolean isPalindrome(int A[]) { int i=0,j=A.length-1; while(i<j) { if(A[i]!=A[j])return false; i++; j--; } return true; } static boolean isPalindrome(int A[],int x) { int i=0,j=A.length-1; while(i<j) { if(A[i]!=A[j]) { if(A[i]==x)i++; else if(A[j]==x)j--; else return false; } else { i++; j--; } } return true; } static long fact[]; static double nCr(int a,int b) { double x=fact[a], y=fact[b]*fact[a-b]; return x/y; } static int f(ArrayList<Integer> A,int x) { int l=-1,r=A.size(); while(r-l>1) { int m=(l+r)/2; if(A.get(m)<x)l=m; else r=m; } return r; } static boolean f(long a,long b,long x) { if(b==0) { return (x==a || x==b); } if(a<x)return false; else { if(a%b==x%b)return true; return f(b,a%b,x); } } static void dfs(int n,int p) { if(p!=-1)D[n]=D[p]+1; for(int c:g[n]) { if(c!=p) dfs(c,n); } } static long f(long a,long A[]) { int l=-1,r=A.length; while(r-l>1) { int m=(l+r)/2; if(A[m]<=a)l=m; else r=m; } return A[l]; } static void build(int v,int tl,int tr,int A[]) { if(tl==tr) { seg[v]=A[tl]; return; } int tm=(tl+tr)/2; build(v*2,tl,tm,A); build(v*2+1,tm+1,tr,A); seg[v]=Math.min(seg[v*2], seg[v*2+1]); } static void update(int v,int tl,int tr,int index,int x) { if(tl==tr && tl==index) { seg[v]=x; return; } int tm=(tl+tr)/2; if(index<=tm)update(v*2,tl,tm,index,x); else update(v*2+1,tm+1,tr,index,x); seg[v]=Math.min(seg[v*2], seg[v*2+1]); } static int ask(int v,int tl,int tr,int l,int r) { // System.out.println(v); // if(v>100)return 0; if(l>r)return Integer.MAX_VALUE; if(tl==l && tr==r)return seg[v]; int tm=(tl+tr)/2; int a=ask(v*2,tl,tm,l,Math.min(tm, r)); // System.out.println("for--> "+(v)+" tm--> "+(tm+1)+" tr--> "+tr+" l--> "+Math.max(l, tm+1)+" r--> "+r); int b=ask(v*2+1,tm+1,tr,Math.max(l, tm+1),r); return Math.min(a, b); } static int find(int a) { if(par[a]<0)return a; return par[a]=find(par[a]); } static void union(int a,int b) { a=find(a); b=find(b); if(a!=b) { par[a]+=par[b]; par[b]=a; } } static int ask(int a,int b) { System.out.println("? "+a+" "+b); return i(); } static long and(int i,int j) { System.out.println("and "+i+" "+j); return l(); } static long or(int i,int j) { System.out.println("or "+i+" "+j); return l(); } static boolean is_Sorted(int A[]) { int N=A.length; for(int i=1; i<=N; i++)if(A[i-1]!=i)return false; return true; } static boolean f(StringBuilder sb,String Y,String order) { StringBuilder res=new StringBuilder(sb.toString()); HashSet<Character> set=new HashSet<>(); for(char ch:order.toCharArray()) { set.add(ch); for(int i=0; i<sb.length(); i++) { char x=sb.charAt(i); if(set.contains(x))continue; res.append(x); } } String str=res.toString(); return str.equals(Y); } static boolean all_Zero(int f[]) { for(int a:f)if(a!=0)return false; return true; } static long form(int a,int l) { long x=0; while(l-->0) { x*=10; x+=a; } return x; } static int count(String X) { HashSet<Integer> set=new HashSet<>(); for(char x:X.toCharArray())set.add(x-'0'); return set.size(); } // static void build(int v,int tl,int tr,long A[]) // { // if(tl==tr) // { // seg[v]=A[tl]; // } // else // { // int tm=(tl+tr)/2; // build(v*2,tl,tm,A); // build(v*2+1,tm+1,tr,A); // seg[v]=Math.min(seg[v*2], seg[v*2+1]); // } // } static int [] sub(int A[],int B[]) { int N=A.length; int f[]=new int[N]; for(int i=N-1; i>=0; i--) { if(B[i]<A[i]) { B[i]+=26; B[i-1]-=1; } f[i]=B[i]-A[i]; } for(int i=0; i<N; i++) { if(f[i]%2!=0)f[i+1]+=26; f[i]/=2; } return f; } static int max(int a ,int b,int c,int d) { a=Math.max(a, b); c=Math.max(c,d); return Math.max(a, c); } static int min(int a ,int b,int c,int d) { a=Math.min(a, b); c=Math.min(c,d); return Math.min(a, c); } static HashMap<Integer,Integer> Hash(int A[]) { HashMap<Integer,Integer> mp=new HashMap<>(); for(int a:A) { int f=mp.getOrDefault(a,0)+1; mp.put(a, f); } return mp; } static long mul(long a, long b) { return ( a %mod * 1L * b%mod )%mod; } static void swap(int A[],int a,int b) { int t=A[a]; A[a]=A[b]; A[b]=t; } static boolean isSorted(int A[]) { for(int i=1; i<A.length; i++) { if(A[i]<A[i-1])return false; } return true; } static boolean isDivisible(StringBuilder X,int i,long num) { long r=0; for(; i<X.length(); i++) { r=r*10+(X.charAt(i)-'0'); r=r%num; } return r==0; } static int lower_Bound(int A[],int low,int high, int x) { if (low > high) if (x >= A[high]) return A[high]; int mid = (low + high) / 2; if (A[mid] == x) return A[mid]; if (mid > 0 && A[mid - 1] <= x && x < A[mid]) return A[mid - 1]; if (x < A[mid]) return lower_Bound( A, low, mid - 1, x); return lower_Bound(A, mid + 1, high, x); } static String f(String A) { String X=""; for(int i=A.length()-1; i>=0; i--) { int c=A.charAt(i)-'0'; X+=(c+1)%2; } return X; } static void sort(long[] a) //check for long { 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 String swap(String X,int i,int j) { char ch[]=X.toCharArray(); char a=ch[i]; ch[i]=ch[j]; ch[j]=a; return new String(ch); } static int sD(long n) { if (n % 2 == 0 ) return 2; for (int i = 3; i * i <= n; i += 2) { if (n % i == 0 ) return i; } return (int)n; } static void setGraph(int N) { // tot=new int[N+1]; partial=new int[N+1]; Days=new int[N+1]; P=new int[N+1][(int)(Math.log(N)+10)]; // set=new boolean[N+1]; g=new ArrayList[N+1]; D=new int[N+1]; for(int i=0; i<=N; i++) { g[i]=new ArrayList<>(); Days[i]=-1; D[i]=Integer.MAX_VALUE; //D2[i]=INF; } } static long pow(long a,long b) { long pow=1; long x=a; while(b!=0) { if((b&1)!=0)pow=(pow*x)%mod; x=(x*x)%mod; b/=2; } return pow; } static long toggleBits(long x)//one's complement || Toggle bits { int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1; return ((1<<n)-1)^x; } static int countBits(long a) { return (int)(Math.log(a)/Math.log(2)+1); } static long fact(long N) { long n=2; if(N<=1)return 1; else { for(int i=3; i<=N; i++)n=(n*i)%mod; } return n; } static int kadane(int A[]) { int lsum=A[0],gsum=A[0]; for(int i=1; i<A.length; i++) { lsum=Math.max(lsum+A[i],A[i]); gsum=Math.max(gsum,lsum); } return gsum; } 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 isPrime(long N) { if (N<=1) return false; if (N<=3) return true; if (N%2 == 0 || N%3 == 0) return false; for (int i=5; i*i<=N; i=i+6) if (N%i == 0 || N%(i+2) == 0) return false; return true; } static void print(char A[]) { for(char c:A)System.out.print(c+" "); System.out.println(); } static void print(boolean A[]) { for(boolean c:A)System.out.print(c+" "); System.out.println(); } static void print(int A[]) { for(int a:A)System.out.print(a+" "); System.out.println(); } static void print(long A[]) { for(long i:A)System.out.print(i+ " "); System.out.println(); } static void print(boolean A[][]) { for(boolean a[]:A)print(a); } static void print(long A[][]) { for(long a[]:A)print(a); } static void print(int A[][]) { for(int a[]:A)print(a); } static void print(ArrayList<Integer> A) { for(int a:A)System.out.print(a+" "); System.out.println(); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static int[] input(int N){ int A[]=new int[N]; for(int i=0; i<N; i++) { A[i]=in.nextInt(); } return A; } static long[] inputLong(int N) { long A[]=new long[N]; for(int i=0; i<A.length; i++)A[i]=in.nextLong(); return A; } static long GCD(long a,long b) { if(b==0) { return a; } else return GCD(b,a%b); } } class Trie { char ch; Trie A[]; boolean ends; Trie() { ch='*'; A=new Trie[26]; ends=false; } } //Code For FastReader //Code For FastReader //Code For FastReader //Code For FastReader 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; } }
0
3e28571b
77b5c134
import java.io.*; import java.util.*; import java.util.Map.Entry; import static java.lang.Math.*; public class Ans implements Runnable { public static void main(String args[]) { Ans s = new Ans(); s.run(); } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } InputReader sc = null; PrintWriter pw = null; static ArrayList<Integer>[] G = new ArrayList[(int)(3e5+10)]; static int[] dist = new int[(int)(3e5+10)]; static int[] a = new int[(int)(3e5+10)]; private static int[] nge(int n){ int[] edges = new int[n]; Arrays.fill(edges, -1); Stack<Integer> st = new Stack<>(); st.push(0); for(int i = 1; i < n; i++){ while(!st.isEmpty() && a[i] >= a[st.peek()]){ edges[st.pop()] = i; } st.push(i); } //debug("nge", edges); return edges; } private static int[] nle(int n){ int[] edges = new int[n]; Arrays.fill(edges, -1); Stack<Integer> st = new Stack<>(); st.push(0); for(int i = 1; i < n; i++){ while(!st.isEmpty() && a[i] <= a[st.peek()]){ edges[st.pop()] = i; } st.push(i); } //debug("nle", edges); return edges; } private static int[] pge(int n){ int[] edges = new int[n]; Arrays.fill(edges, -1); Stack<Integer> st = new Stack<>(); st.push(n-1); for(int i = n-2; i >= 0; i--){ while(!st.isEmpty() && a[i] >= a[st.peek()]){ edges[st.pop()] = i; } st.push(i); } //debug("pge", edges); return edges; } private static int[] ple(int n){ int[] edges = new int[n]; Arrays.fill(edges, -1); Stack<Integer> st = new Stack<>(); st.push(n-1); for(int i = n-2; i >= 0; i--){ while(!st.isEmpty() && a[i] <= a[st.peek()]){ edges[st.pop()] = i; } st.push(i); } //debug("ple", edges); return edges; } private static void buildGraph(int[] edges){ for(int i = 0; i < edges.length; i++){ if(edges[i] != -1){ // G[i].add(edges[i]); // G[edges[i]].add(i); G[min(i, edges[i])].add(max(i, edges[i])); } } } private static void bfs(int n){ dist[0] = 0; ArrayDeque<Integer> q = new ArrayDeque<>(); q.add(0); while(!q.isEmpty()){ int front = q.pollFirst(); if(front == n-1){ break; } for(int adj : G[front]){ if(dist[adj] == (int)(1e9)){ dist[adj] = 1 + dist[front]; q.add(adj); } } } } public void run() { // InputStream is; // is = new FileInputStream(new File("input.txt")); sc = new InputReader(System.in); pw = new PrintWriter(System.out); int n = sc.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); G[i] = new ArrayList<Integer>(); } buildGraph(nge(n)); buildGraph(nle(n)); buildGraph(ple(n)); buildGraph(pge(n)); Arrays.fill(dist, (int)(1e9)); bfs(n); pw.println(dist[n-1]); // is.close(); pw.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[5]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br = new BufferedReader(new InputStreamReader(stream)); String stock = ""; try { stock = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return stock; } 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 long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long 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 double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.Stack; // https://codeforces.com/contest/1407/problem/D public class Discrete_Centrifugal_Jumps { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] h = new int[n]; for (int i = 0; i < n; i++) h[i] = scan.nextInt(); System.out.println(getMinJump(h, n)); } static int getMinJump(int[] h, int n) { int[] rightG = new int[n], leftG = new int[n]; int[] rightS = new int[n], leftS = new int[n]; Arrays.fill(rightG, -1); Arrays.fill(rightS, -1); Arrays.fill(leftG, -1); Arrays.fill(leftS, -1); Stack<Integer> stack = new Stack<>(); // next greater in the right segment int i = 0; while (i < n) { if (!stack.empty() && h[i] >= h[stack.peek()]) rightG[stack.pop()] = i; else stack.push(i++); } stack = new Stack<>(); // next smaller in the right segment i = 0; while (i < n) { if (!stack.empty() && h[i] <= h[stack.peek()]) rightS[stack.pop()] = i; else stack.push(i++); } stack = new Stack<>(); // next greater in left segment i = n-1; while (i >= 0) { if (!stack.empty() && h[i] >= h[stack.peek()]) leftG[stack.pop()] = i; else stack.push(i--); } stack = new Stack<>(); // next smaller in left segment i = n-1; while (i >= 0) { if (!stack.empty() && h[i] <= h[stack.peek()]) leftS[stack.pop()] = i; else stack.push(i--); } ArrayList<Integer>[] jump = new ArrayList[n]; for (i = 0; i < n; i++) jump[i] = new ArrayList<>(); for (i = 0; i < n; i++) { // max(h[i+1] ... h[j-1]) < min(h[i], h[j]) if (rightG[i] != -1) jump[i].add(rightG[i]); if (leftG[i] != -1) jump[leftG[i]].add(i); // max(h[i], h[j]) < min(h[i+1] ... h[j]) if (rightS[i] != -1) jump[i].add(rightS[i]); if (leftS[i] != -1) jump[leftS[i]].add(i); } int[] dp = new int[n]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for (int u = 0; u < n; u++) { for (int v: jump[u]) { dp[v] = Math.min(dp[v], dp[u] + 1); } } return dp[n-1]; } }
0
69b8ffb2
c9159d9c
import java.util.*; //CODE FORCES public class anshulvmc { public static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static int gcd(int a, int b) { if (b==0) return a; return gcd(b, a%b); } public static void google(int t) { System.out.println("Case #"+t+": "); } // public static void gt(int[][] arr,int k) { // int n = arr.length+1; // k = Math.min(k,n+1); // // Node[] nodes = new Node[n]; // for(int i=0;i<n;i++) nodes[i] = new Node(); // for(int i=0;i<n-1;i++) { // int a = arr[i][0]; // int b = arr[i][1]; // System.out.println(a+" "+b); // nodes[a].adj.add(nodes[b]); // nodes[b].adj.add(nodes[a]); // } // // ArrayDeque<Node> bfs = new ArrayDeque<>(); // for(Node nn:nodes) { // if(nn.adj.size()<2) { // bfs.addLast(nn); // nn.dist=0; // } // } // // while(bfs.size()>0) { // Node nn = bfs.removeFirst(); // for(Node a : nn.adj) { // if(a.dist!=-1) continue; // a.usedDegree++; // if(a.adj.size() - a.usedDegree <= 1) { // a.dist = nn.dist+1; // bfs.addLast(a); // } // } // } // // int[] cs = new int[n+1]; // for(Node nn:nodes) { // cs[nn.dist]++; // } // for(int i=1;i<cs.length;i++) cs[i]+=cs[i-1]; // System.out.println(n-cs[k-1]); // } public static class Node{ ArrayList<Node> adj = new ArrayList<>(); int dist = -1; int usedDegree = 0; } public static void cat_mice(int dest,int[] arr) { sort(arr); int time = dest; int timeleft = dest-1; int counter=0; for(int i=arr.length-1;i>=0;i--) { int val = arr[i]; int takes = time - val; if(takes <= timeleft) { timeleft -= takes; counter++; } } System.out.println(counter); } public static void minex(int n,int[] arr) { sort(arr); int ans=arr[0]; for(int i=0;i<arr.length-1;i++) { ans = Math.max(ans,arr[i+1] - arr[i]); } System.out.println(ans); } public static void func(long start,long n) { long x = start; if(n==0){ System.out.println(x); return; } long k=n-1; long c=k/4; long rem=k%4; long ans=x; if(x%2 == 0) { ans -= 1; ans -= (c * 4); if(rem == 1) { ans += n; } else if(rem == 2) { ans += n + n-1; } else if(rem == 3){ ans += (n-2) + (n-1) - n; } } else { ans += 1; ans += (c * 4); if(rem == 1) { ans -= n; } else if(rem == 2) { ans -= n + n-1; } else if(rem == 3) { ans -= n-2 + n-1 - n; } } System.out.println(ans); } public static boolean redblue(int[] num, String chnum) { ArrayList<Integer> blue = new ArrayList<>(); ArrayList<Integer> red = new ArrayList<>(); for(int i=0;i<chnum.length();i++) { char ch = chnum.charAt(i); if(ch == 'B') { blue.add(num[i]); } else { red.add(num[i]); } } Collections.sort(blue); Collections.sort(red); // System.out.println(blue); // System.out.println(red); for(int i=0;i<blue.size();i++) { if(blue.get(i) >= i+1) { } else { return false; } } for(int i=0;i<red.size();i++) { if(red.get(i) > i+1 + blue.size()) { // System.out.println(red.get(i)+" "+(i+1 + blue.size())); return false; } } return true; } public static void main(String args[]) { Scanner scn = new Scanner(System.in); int test = scn.nextInt(); for(int i=0;i<test;i++) { int size = scn.nextInt(); int[] arr = new int[size]; for(int j=0;j<size;j++) { arr[j] = scn.nextInt(); } String str = scn.next(); boolean f = redblue(arr,str); if(f) { System.out.println("YES"); } else { System.out.println("NO"); } } // int n = 1; // int[] dp = new int[2]; // System.out.println(fact(n,dp)); } }
import java.util.*; public class SolutionB { public static long gcd(long a, long b){ if(b==0){ return a; } return gcd(b, a%b); } public static long gcdSum(long b){ long a = 0; long temp = b; while(temp!=0){ a = a + temp%10; temp = temp/10; } return gcd(a,b); } public static class Pair{ Long a; Long b; public Pair(Long a, Long b) { this.a = a; this.b = b; } } public static long factorial (long n){ if(n==0) return 1; else if(n==1) return n; return n * factorial(n-1); } public static long lcm (long n){ if(n<3) return n; return lcmForBig(n,n-1); } private static long lcmForBig(long n, long l) { if(l==1) return n; n = (n * l) / gcd(n, l); return lcmForBig(n, l-1); } public static void main(String[] args){ Scanner s = new Scanner(System.in); int t = s.nextInt(); for(int i =0;i<t;i++) { int n = s.nextInt(); int arr [] = new int[n]; ArrayList<Integer> blue = new ArrayList<>(); ArrayList<Integer> red = new ArrayList<>(); for(int j=0;j<n;j++){ int num = s.nextInt(); arr[j]=num; } String color = s.next(); for(int j=0;j<n;j++){ if(color.charAt(j)=='B'){ blue.add(arr[j]); } else{ red.add(arr[j]); } } Collections.sort(blue); String ans = "YES"; int counter = 0; for(int j=0;j<blue.size();j++){ int current = blue.get(j); if (current<1){ ans="NO"; break; } if(current>counter){ counter++; } else{ ans="NO"; break; } } if(ans=="NO"){ System.out.println(ans); } else{ int tempCounter = n+1; Collections.sort(red); for(int j=red.size()-1;j>=0;j--){ int current = red.get(j); if(current>=tempCounter){ ans="NO"; break; } else{ tempCounter--; } } if(tempCounter-counter!=1) System.out.println("NO"); else System.out.println(ans); } } return; } }
0
99ccaa44
e7a997b5
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); while(tc>0) { tc--; int ans = 0; int n = sc.nextInt(); int in[] = new int[n]; int wx[] = new int[n-1]; int wy[] = new int[n-1]; ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>(); HashMap<String,Integer> h = new HashMap<String,Integer>(); HashSet<Integer> h2 = new HashSet<Integer>(); for(int i=0;i<n;i++) { arr.add(new ArrayList<Integer>()); } for(int i=0;i<n-1;i++) { int x = sc.nextInt(); int y = sc.nextInt(); x--; y--; in[x]++; in[y]++; if(in[x]>2 || in[y]>2) { ans = -1; } else if(ans!=-1) { arr.get(x).add(y); arr.get(y).add(x); wx[i] = x; wy[i] = y; } } if(ans == -1) { System.out.println("-1"); } else { int vis[] = new int[n]; ArrayDeque<Integer> q = new ArrayDeque<Integer>(); q.add(0); vis[0] = 1; while(q.size()>0) { int x = q.removeFirst(); for(int i=0;i<arr.get(x).size();i++) { int y = arr.get(x).get(i); String temp =String.valueOf(x); if(vis[y] == 0) { vis[y] = 1; if(h2.contains(y) || h2.contains(x)) { String s1 = temp+"_"+String.valueOf(y); String s2 = String.valueOf(y)+"_"+temp; h.put(s1,11); h.put(s2,11); } else { String s1 = temp+"_"+String.valueOf(y); String s2 = String.valueOf(y)+"_"+temp; h.put(s1,2); h.put(s2,2); h2.add(x); h2.add(y); } q.add(y); } } } for(int i=0;i<wx.length;i++) { String s1 = String.valueOf(wx[i])+"_"+String.valueOf(wy[i]); System.out.print(h.get(s1)+" "); } System.out.println(); } } } }
import java.io.*; import java.util.*; public class c { public static void main(String[] args){ FastScanner sc = new FastScanner(); int t = sc.nextInt(); while(t-- > 0){ int n = sc.nextInt(); ArrayList<ArrayList<Edge>> graph = new ArrayList<>(); for(int i=0; i<n; i++){ graph.add(new ArrayList<Edge>()); } for(int i=0; i<n-1; i++){ int u = sc.nextInt(); int v = sc.nextInt(); Edge e = new Edge(u-1, v-1, i+1); Edge e2 = new Edge(v-1, u-1, i+1); graph.get(u-1). add(e); graph.get(v-1).add(e2); } int edges[] = new int[n]; int indegree1count = 0; int indegree2count = 0; for(ArrayList<Edge> list : graph){ if(list.size() == 1){ indegree1count++; } else if(list.size() == 2){ indegree2count++; } } if(indegree1count == 2 && indegree1count+indegree2count==n){ for(int i=0; i<graph.size(); i++){ ArrayList<Edge> list = graph.get(i); if(list.size() == 1){ dfs(graph, edges, false, -1, i) ; } } for(int i=1; i<edges.length; i++){ System.out.print(edges[i] + " "); } System.out.println(); } else{ System.out.println(-1); } } } public static void dfs(ArrayList<ArrayList<Edge>> graph, int[] edges, boolean isprev2, int parent, int current){ for(Edge e : graph.get(current)){ if(e.v == parent){ continue; } edges[e.id] = isprev2 ? 5 : 2; dfs(graph, edges, !isprev2, current, e.v); } } } class Edge { int u; int v; int id; public Edge(int u, int v, int id) { this.u = u; this.v = v; this.id = id; } } class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } }
0
0c9d4def
1a6f8b20
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class C{ private static int maxWords = 0; private static int[][] words; private static int n; private static int[] netwrtchar(int index){ ArrayList<Integer> list = new ArrayList<>(); for(int i=0; i<n; i++){ int sum = 0; for(int j=0; j<words[i].length; j++){ if(j==index) continue; sum += words[i][j]; } list.add(words[i][index] - sum); // f[i] = words[i][index] - sum; } Collections.sort(list, Collections.reverseOrder()); int[] f = new int[list.size()]; for(int i=0; i<list.size(); i++){ f[i] = list.get(i); } return f; } private static int maxWindow(int[] f){ int count = 0, sum = 0; int index = 0; while(index<f.length && sum+f[index]>0){ sum += f[index++]; count++; } return count; } public static void main(String[] args){ FS sc = new FS(); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while(t-->0){ n = sc.nextInt(); words = new int[n][5]; maxWords = 0; for(int i=0; i<n; i++){ String s = sc.next(); for(int j=0; j<s.length(); j++){ words[i][s.charAt(j)-'a']++; } } int maxWindow = 0; for(int i=0; i<5; i++){ int[] f = netwrtchar(i); int current = maxWindow(f); maxWindow = Math.max(maxWindow, current); } System.out.println(maxWindow); } pw.flush(); pw.close(); } static class FS{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(Exception ignored){ } } return st.nextToken(); } int[] nextArray(int n){ int[] a = new int[n]; for(int i = 0; i < n; i++){ a[i] = nextInt(); } return a; } long[] nextLongArray(int n){ long[] a = new long[n]; for(int i = 0; i < n; i++){ a[i] = nextLong(); } return a; } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } } }
import java.io.*; import java.util.*; public class Main { public static void main(String[] args)throws Exception { Main ob=new Main(); ob.fun(); } public void fun()throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(System.out); int t=Integer.parseInt(br.readLine()); while(t-->0) { int n=Integer.parseInt(br.readLine()); int ar[][]=new int [n][5]; int len[]=new int[n]; for(int i=0;i<n;i++) { String s=(br.readLine()); for(int j=0;j<s.length();j++) { ar[i][s.charAt(j)-'a']++; len[i]=s.length(); } } int max=0; for(int i=0;i<5;i++) { int num=fun2(ar,len,i); max=Math.max(num,max); } pw.println(max); } pw.flush(); } public int fun2(int ar[][],int len[],int col) { int ct=0; int n=ar.length; PriorityQueue<Integer> pq=new PriorityQueue<Integer>(Collections.reverseOrder()); for(int i=0;i<n;i++) { int dif=2*ar[i][col]-len[i]; pq.add(dif); } int sum=0; while(pq.size()>0) { int num=(int)(pq.poll()); if((sum+num)>0) { ct++; sum+=num; } } return ct; } }
0
49b94994
558df7d4
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main1582D { public static void main(String[] args) { final FastScanner in = new FastScanner(System.in); final PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt(); int[] a = new int[n]; for (int j = 0; j < n; j++) { a[j] = in.nextInt(); } int[] b = solution(a, n); for (int j = 0; j < n; j++) { out.print(b[j]); out.print(" "); } out.println(); } out.flush(); out.close(); in.close(); } private static int[] solution(int[] a, int n) { int[] b = new int[n]; int start = 0; if (n % 2 == 1) { if (a[0] + a[1] != 0) { b[0] = -a[2]; b[1] = -a[2]; b[2] = a[0] + a[1]; } else if (a[0] + a[2] != 0) { b[0] = -a[1]; b[1] = a[0] + a[2]; b[2] = -a[1]; } else { b[0] = a[1] + a[2]; b[1] = -a[0]; b[2] = -a[0]; } start = 3; } else { b[0] = -a[1]; b[1] = a[0]; int gcd = gcd(b[0], b[1]); b[0] /= gcd; b[1] /= gcd; start = 2; } for (int i = start; i < n; i += 2) { b[i] = -a[i + 1]; b[i + 1] = a[i]; } return b; } private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } catch (Exception e) { e.printStackTrace(); } } 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()); } double nextDouble() { return Double.parseDouble(next()); } int[] readIntArr(int n) { int[] result = new int[n]; for (int i = 0; i < n; i++) { result[i] = Integer.parseInt(next()); } return result; } long[] readLongArr(int n) { long[] result = new long[n]; for (int i = 0; i < n; i++) { result[i] = Long.parseLong(next()); } return result; } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } long nextLong() { return Long.parseLong(next()); } } }
import java.io.*; import java.util.*; public class Pupsen { public static void main(String[] args) throws Exception { FastIO in = new FastIO(); int t = in.nextInt(); for (int tc=0; tc<t; tc++) { int n = in.nextInt(); int[] a = new int[n]; for (int i=0; i<n; i++) { a[i] = in.nextInt(); } int[] b = new int[n]; if (n%2==0) { for (int i=0; i<n-1; i+=2) { b[i] = -a[i+1]; b[i+1] = a[i]; } for (int i=0; i<n; i++) System.out.print(b[i]+" "); } else { if (a[0]+a[1]!=0) { b[0] = -a[2]; b[1] = -a[2]; b[2] = a[0]+a[1]; } else if (a[0]+a[2]!=0) { b[0] = -a[1]; b[2] = -a[1]; b[1] = a[0]+a[2]; } else { b[1] = -a[0]; b[2] = -a[0]; b[0] = a[1]+a[2]; } for (int i=3; i<n-1; i+=2) { b[i] = -a[i+1]; b[i+1] = a[i]; } for (int i=0; i<n; i++) System.out.print(b[i]+" "); } System.out.println(); } } static class FastIO { BufferedReader br; StringTokenizer st; PrintWriter pr; public FastIO() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { String str = br.readLine(); return str; } } }
0
4552d8a0
d3a96420
import java.util.*; import java.io.*; ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** public class D_Blue_Red_Permutation{ public static void main(String[] args) { FastScanner s= new FastScanner(); // PrintWriter out=new PrintWriter(System.out); //end of program //out.println(answer); //out.close(); StringBuilder res = new StringBuilder(); int t=s.nextInt(); int p=0; while(p<t){ int n=s.nextInt(); long array[]= new long[n]; for(int i=0;i<n;i++){ array[i]=s.nextLong(); } String str=s.nextToken(); ArrayList<Long> red = new ArrayList<Long>(); ArrayList<Long> blue = new ArrayList<Long>(); for(int i=0;i<n;i++){ if(str.charAt(i)=='R'){ red.add(array[i]); } else{ blue.add(array[i]); } } Collections.sort(blue); int check1=0; for(int i=0;i<blue.size();i++){ int yo=i+1; if(blue.get(i)<yo){ check1=1; break; } } Collections.sort(red,Collections.reverseOrder()); int number=n; int check2=0; for(int i=0;i<red.size();i++){ if(red.get(i)>number){ check2=1; break; } number--; } if(check1==0 && check2==0){ res.append("YES\n"); } else{ res.append("NO\n"); } p++; } System.out.println(res); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { 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(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); String x=sc.next(); Vector<Integer> R=new Vector<>(); Vector<Integer> B=new Vector<>(); for(int i=0;i<n;i++){ if(x.charAt(i)=='B') R.add(a[i]); else B.add(a[i]); } Collections.sort(R); Collections.sort(B); boolean yes=true; for(int i=0;i<R.size();i++){ if(R.get(i)-i<1){System.out.println("NO");yes=false;break;} } if(yes) { int s=B.size(); for(int j=0;j<s;j++){ if(B.get(j)+s-j>n+1){System.out.println("NO");yes=false;break;} } } if(yes)System.out.println("YES"); } sc.close(); } }
0
49e94e7e
fcc7e8fa
import java.io.BufferedReader; import java.io.IOException; import java.lang.*; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.out; import java.util.*; import java.io.File; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigInteger; public class Main { /* 10^(7) = 1s. * ceilVal = (a+b-1) / b */ static final int mod = 1000000007; static final long temp = 998244353; static final long MOD = 1000000007; static final long M = (long)1e9+7; static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair ob) { return (int)(first - ob.first); } } static class Tuple implements Comparable<Tuple> { int first, second,third; public Tuple(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } public int compareTo(Tuple o) { return (int)(o.third - this.third); } } public static class DSU { int[] parent; int[] rank; //Size of the trees is used as the rank public DSU(int n) { parent = new int[n]; rank = new int[n]; Arrays.fill(parent, -1); Arrays.fill(rank, 1); } public int find(int i) //finding through path compression { return parent[i] < 0 ? i : (parent[i] = find(parent[i])); } public boolean union(int a, int b) //Union Find by Rank { a = find(a); b = find(b); if(a == b) return false; //if they are already connected we exit by returning false. // if a's parent is less than b's parent if(rank[a] < rank[b]) { //then move a under b parent[a] = b; } //else if rank of j's parent is less than i's parent else if(rank[a] > rank[b]) { //then move b under a parent[b] = a; } //if both have the same rank. else { //move a under b (it doesnt matter if its the other way around. parent[b] = a; rank[a] = 1 + rank[a]; } return true; } } static class Reader { 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) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] longReadArray(int n) throws IOException { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static long lcm(long a, long b) { return (a / LongGCD(a, b)) * b; } public static long LongGCD(long a, long b) { if(b == 0) return a; else return LongGCD(b,a%b); } public static long LongLCM(long a, long b) { return (a / LongGCD(a, b)) * b; } //Count the number of coprime's upto N public static long phi(long n) //euler totient/phi function { long ans = n; // for(long i = 2;i*i<=n;i++) // { // if(n%i == 0) // { // while(n%i == 0) n/=i; // ans -= (ans/i); // } // } // // if(n > 1) // { // ans -= (ans/n); // } for(long i = 2;i<=n;i++) { if(isPrime(i)) { ans -= (ans/i); } } return ans; } public static long fastPow(long x, long n) { if(n == 0) return 1; else if(n%2 == 0) return fastPow(x*x,n/2); else return x*fastPow(x*x,(n-1)/2); } public static long modPow(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return modPow(n, p - 2, p); } // Returns nCr % p using Fermat's little theorem. public static long nCrModP(long n, long r,long p) { if (n<r) return 0; if (r == 0) return 1; long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[(int)(n)] * modInverse(fac[(int)(r)], p) % p * modInverse(fac[(int)(n - r)], p) % p) % p; } public static long fact(long n) { long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (long i = 1; i <= n; i++) fac[(int)(i)] = fac[(int)(i - 1)] * i; return fac[(int)(n)]; } public static long nCr(long n, long k) { long ans = 1; for(long i = 0;i<k;i++) { ans *= (n-i); ans /= (i+1); } return ans; } //Modular Operations for Addition and Multiplication. public static long perfomMod(long x) { return ((x%M + M)%M); } public static long addMod(long a, long b) { return perfomMod(perfomMod(a)+perfomMod(b)); } public static long subMod(long a, long b) { return perfomMod(perfomMod(a)-perfomMod(b)); } public static long mulMod(long a, long b) { return perfomMod(perfomMod(a)*perfomMod(b)); } public static boolean isPrime(long n) { if(n == 1) { return false; } //check only for sqrt of the number as the divisors //keep repeating so only half of them are required. So,sqrt. for(int i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static List<Integer> SieveList(int n) { boolean prime[] = new boolean[(int)(n+1)]; Arrays.fill(prime, true); List<Integer> l = new ArrayList<>(); 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 p = 2; p<=n; p++) { if (prime[p] == true) { l.add(p); } } return l; } public static int countDivisors(int x) { int c = 0; for(int i = 1;i*i<=x;i++) { if(x%i == 0) { if(x/i != i) { c+=2; } else { c++; } } } return c; } public static long log2(long n) { long ans = (long)(log(n)/log(2)); return ans; } public static boolean isPow2(long n) { return (n != 0 && ((n & (n-1))) == 0); } public static boolean isSq(int x) { long s = (long)Math.round(Math.sqrt(x)); return s*s==x; } /* * * >= <= 0 1 2 3 4 5 6 7 5 5 5 6 6 6 7 7 lower_bound for 6 at index 3 (>=) upper_bound for 6 at index 6(To get six reduce by one) (<=) */ public 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; } public static int UpperBound(long a[], long x) { 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; } public static void Sort(long[] a) { List<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); // Collections.reverse(l); //Use to Sort decreasingly for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void ssort(char[] a) { List<Character> l = new ArrayList<>(); for (char 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) throws Exception { Reader sc = new Reader(); PrintWriter fout = new PrintWriter(System.out); int tt = sc.nextInt(); while(tt-- > 0) { int n = sc.nextInt(); char[] a = sc.next().toCharArray(), b = sc.next().toCharArray(); int c00 = 0, c01 = 0, c10 = 0, c11 = 0; for(int i = 0;i<n;i++) { if(a[i] == '0' && b[i] == '0') { c00++; } else if(a[i] == '0' && b[i] == '1') { c01++; } else if(a[i] == '1' && b[i] == '0') { c10++; } else if(a[i] == '1' && b[i] == '1') { c11++; } } int ans = mod; if(c01 == c10) ans = min(ans, c01 + c10); if(c11 == c00 + 1) ans = min(ans, c11 + c00); fout.println((ans == mod) ? -1 : ans); } fout.close(); } }
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); int t; t = in.nextInt(); //t = 1; while (t > 0) { solver.call(in,out); t--; } out.close(); } static class TaskA { public void call(InputReader in, PrintWriter out) { int n, _00 = 0, _01 = 0, _11 = 0, _10 = 0; n = in.nextInt(); char[] s = in.next().toCharArray(); char[] s1 = in.next().toCharArray(); for (int i = 0; i < n; i++) { if(s[i]==s1[i]){ if(s[i]=='0'){ _00++; } else{ _11++; } } else{ if(s[i]=='0'){ _01++; } else{ _10++; } } } int ans = Integer.MAX_VALUE; if(_10 ==_01){ ans = 2*_01; } if(_11 == _00 + 1){ ans = Math.min(ans, 2*_00 + 1); } if(ans == Integer.MAX_VALUE){ out.println(-1); } else{ out.println(ans); } } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static class answer implements Comparable<answer>{ int a, b; public answer(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(answer o) { return o.a - this.a; } } static class arrayListClass { ArrayList<Integer> arrayList2 ; public arrayListClass(ArrayList<Integer> arrayList) { this.arrayList2 = arrayList; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } 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 final Random random=new Random(); static void shuffleSort(int[] a) { int n = a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } 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()); } } }
0
90f01508
ec8566b8
// import java.io.DataInputStream; // import java.io.FileInputStream; // import java.io.IOException; import java.io.*; import java.util.*; public class one { static Scanner sc=new Scanner(System.in); boolean prime[]; static int prev=-1; static int dp[][]; public static int[] input(int size){ int arr[]=new int[size]; for(int i=0;i<size;i++) arr[i]=sc.nextInt(); return arr; } public static void main(String[] args) { //int testcase=1; int testcase=sc.nextInt(); //System.out.println("HI"); while(testcase-->0){ // int x=sc.nextInt(); // int y=sc.nextInt(); //String str[]=new String[size]; solve(); System.out.println(); } } public static void solve(){ HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(); int size=sc.nextInt(); int arr[][]=new int[size-1][2]; for(int i=0;i<size-1;i++){ arr[i][0]=sc.nextInt(); arr[i][1]=sc.nextInt(); } for(int x[]:arr){ map.put(x[0],map.getOrDefault(x[0], 0)+1); map.put(x[1],map.getOrDefault(x[1], 0)+1); if(map.get(x[0])>2||map.get(x[1])>2){ System.out.println(-1); return; } } List<List<Integer>> adj=new ArrayList<>(); for(int i=0;i<=size;i++) adj.add(new ArrayList<Integer>()); for(int x[]:arr){ adj.get(x[0]).add(x[1]); adj.get(x[1]).add(x[0]); } //System.out.println(adj); int vist[]=new int[size+1]; HashMap<String,Integer> ans=new HashMap<String,Integer>(); for(int i=1;i<=size;i++){ if(vist[i]==0){ dfs(i,vist,adj,ans,2); } } //System.out.println(ans); for(int x[]:arr){ //System.out.print(map.get(x[0])); int a=Math.min(x[0],x[1]); int b=Math.max(x[0],x[1]); String s=a+" "+b; System.out.print(ans.get(s)+" "); } // map=new HashMap<Integer,Integer>(); // for(int x[]:arr){ // if(map.containsKey(x[0])){ // int val=13-map.get(x[0]); // map.put(x[1],val); // System.out.print(val+" "); // }else if(map.containsKey(x[1])){ // int val=13-map.get(x[1]); // map.put(x[0],val); // System.out.print(val+" "); // }else{ // System.out.print(2+" "); // map.put(x[0],2); // map.put(x[1],2); // } // } } public static void dfs(int node,int vist[],List<List<Integer>> adj,HashMap<String,Integer> ans,int val){ vist[node]=1; for(int i:adj.get(node)){ if(vist[i]==1) continue; int x=Math.min(i, node); int y=Math.max(i, node); ans.put(x+" "+y,val); dfs(i,vist,adj,ans,5-val); val=5-val; } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class A { private static void sport(List<Integer>[] g, Map<W, Integer> map) { int n = g.length; for (int i = 0; i < n; i++) { if (g[i].size() > 2) { System.out.println(-1); return; } } int[] ans = new int[n - 1]; //dfs(new C(-1, 0), g, ans, 3, new HashSet<>()); Queue<int[]> queue = new LinkedList<>(); Set<Integer> seen = new HashSet<>(); int val = 3; for (Integer integer : g[0]) { Integer idx = map.get(new W(0, integer)); ans[idx] = val; queue.add(new int[]{val, integer}); seen.add(integer); val = val == 2 ? 3 : 2; } seen.add(0); while (!queue.isEmpty()) { int[] poll = queue.poll(); for (Integer u : g[poll[1]]) { if (!seen.contains(u)) { seen.add(u); int curr = poll[0] == 2 ? 3 : 2; Integer integer = map.get(new W(poll[1], u)); ans[integer] = curr; queue.add(new int[]{curr, u}); } } } for (int an : ans) { System.out.print(an + " "); } System.out.println(); } static class W { int u; int v; public W(int u, int v) { this.u = u; this.v = v; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; W w = (W) o; return u == w.u && v == w.v; } @Override public int hashCode() { return Objects.hash(u, v); } } static void dfs(C v, List<C>[] g, int[] ans, int prev, Set<Integer> seen) { if (v.i != -1) { ans[v.i] = prev == 2 ? 3 : 2; } seen.add(v.v); int next = prev == 2 ? 3 : 2; for (C c : g[v.v]) { if (!seen.contains(c.v)) { dfs(c, g, ans, next, seen); } next = next == 2 ? 3 : 2; } } static class C { int i; int v; public C(int i, int v) { this.i = i; this.v = v; } } public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); int t = sc.nextInt(); for (int i = 0; i < t; i++) { int n = sc.nextInt(); List<Integer>[] g = new ArrayList[n]; for (int j = 0; j < n; j++) { g[j] = new ArrayList<>(); } Map<W, Integer> map = new HashMap<>(); for (int j = 0; j < n - 1; j++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; g[u].add(v); g[v].add(u); map.put(new W(u, v), j); map.put(new W(v, u), j); } sport(g, map); } } static void shuffleArray(int[] ar) { // If running on Java 6 or older, use `new Random()` on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = 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()); } void nextLine() throws IOException { br.readLine(); } long[] readArrayLong(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } int[] readArrayInt(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()); } } }
0
99afdfb3
e152c1ff
import java.util.Scanner; public class C_Set_or_Decrease{ static Scanner in=new Scanner(System.in); static int testCases,n; static long a[]; static long wantedSum; static void solve(){ if(n==1){ if(a[0]<=wantedSum ){ System.out.println(0); }else{ System.out.println((-wantedSum+a[0]) ); } return; } long sum=0; for(long i: a){ sum+=i; } if(sum<=wantedSum){ System.out.println(0); return; } sort(a,0,n-1); long step=Math.max(sum-wantedSum,0); for(int i=1;i<n;i++){ sum-=a[n-i]-a[0]; long t=sum>wantedSum?(sum-wantedSum+i)/(i+1):0; step=Math.min(step,t+i); } System.out.println(step); //System.out.println("sum after iterate: "+sum); //System.out.println("ans: "+ans); } public static void main(String [] amit){ testCases=in.nextInt(); for(int t=0;t<testCases;t++){ n=in.nextInt(); wantedSum=in.nextLong(); a=new long[n]; for(int i=0;i<n;i++){ a[i]=in.nextLong(); } solve(); } } static void merge(long a[],int left,int right,int mid){ int n1=mid-left+1,n2=right-mid; long L[]=new long[n1]; long R[]=new long[n2]; for(int i=0;i<n1;i++){ L[i]=a[left+i]; } for(int i=0;i<n2;i++){ R[i]=a[mid+1+i]; } int i=0,j=0,k=left; while(i<n1 && j<n2){ if(L[i]<=R[j]){ a[k]=L[i]; i++; }else{ a[k]=R[j]; j++; } k++; } while(i<n1){ a[k]=L[i]; i++; k++; } while(j<n2){ a[k]=R[j]; j++; k++; } } static void sort(long a[],int left,int right){ if(left>=right){ return; } int mid=(left+right)/2; sort(a,left,mid); sort(a,mid+1,right); merge(a,left,right,mid); } }
import java.util.Scanner; public class C_Set_or_Decrease{ static Scanner in=new Scanner(System.in); static int testCases,n; static long a[]; static long wantedSum; static void solve(){ if(n==1){ if(a[0]<=wantedSum ){ System.out.println(0); }else{ System.out.println((-wantedSum+a[0]) ); } return; } long sum=0; for(long i: a){ sum+=i; } if(sum<=wantedSum){ System.out.println(0); return; } sort(a,0,n-1); long step=Math.max(sum-wantedSum,0); for(int i=1;i<n;i++){ sum-=a[n-i]-a[0]; long t=sum>wantedSum?(sum-wantedSum+i)/(i+1):0; step=Math.min(step,t+i); } System.out.println(step); //System.out.println("sum after iterate: "+sum); //System.out.println("ans: "+ans); } public static void main(String [] amit){ testCases=in.nextInt(); for(int t=0;t<testCases;t++){ n=in.nextInt(); wantedSum=in.nextLong(); a=new long[n]; for(int i=0;i<n;i++){ a[i]=in.nextLong(); } solve(); } } static void merge(long a[],int left,int right,int mid){ int n1=mid-left+1,n2=right-mid; long L[]=new long[n1]; long R[]=new long[n2]; for(int i=0;i<n1;i++){ L[i]=a[left+i]; } for(int i=0;i<n2;i++){ R[i]=a[mid+1+i]; } int i=0,j=0,k=left; while(i<n1 && j<n2){ if(L[i]<=R[j]){ a[k]=L[i]; i++; }else{ a[k]=R[j]; j++; } k++; } while(i<n1){ a[k]=L[i]; i++; k++; } while(j<n2){ a[k]=R[j]; j++; k++; } } static void sort(long a[],int left,int right){ if(left>=right){ return; } int mid=(left+right)/2; sort(a,left,mid); sort(a,mid+1,right); merge(a,left,right,mid); } }
1
5f3a196a
d76e3b9d
import java.io.*; import java.util.*; public class MonstersAndSpells { public static PrintWriter out; public static void main(String[] args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(br.readLine()); out=new PrintWriter(System.out); int t=Integer.parseInt(st.nextToken()); while(t-->0) { st=new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken());//monsters int time[]=new int[n];//time int health[]=new int[n];//health st=new StringTokenizer(br.readLine()); for(int i=0;i<n;i++) { time[i]=Integer.parseInt(st.nextToken()); } st=new StringTokenizer(br.readLine()); for(int i=0;i<n;i++) { health[i]=Integer.parseInt(st.nextToken()); } State a[]=new State[n]; for(int i=0;i<n;i++) { a[i]=new State(time[i]-health[i], time[i]); } Arrays.sort(a); long ans=0; for(int i=0;i<n;i++) { int j=i+1; int max=a[i].time; while(j<n&&a[j].x<max) { max=Math.max(max, time[j]); j++; } ans+=((long)(max-a[i].x)*(long)(max-a[i].x+1))/2; i=j-1; } out.println(ans); } out.close(); } static class State implements Comparable<State>{ int x, time; public State(int x, int time) { this.x=x;this.time=time; } public int compareTo(State o) { return x-o.x; } } }
import java.io.*; import java.util.*; public class c { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int numcases = Integer.parseInt(in.readLine()); for(int casenum = 0; casenum < numcases; casenum++){ int n = Integer.parseInt(in.readLine()); long[] t = new long[n]; long[] h = new long[n]; StringTokenizer tokenizer = new StringTokenizer(in.readLine()); for(int i = 0; i < n; i++){ t[i] = Integer.parseInt(tokenizer.nextToken()); } tokenizer = new StringTokenizer(in.readLine()); for(int i = 0; i < n; i++){ h[i] = Integer.parseInt(tokenizer.nextToken()); } long mana = 0; int index = 0; while(index < n){ long start = t[index] - h[index]; long end = t[index]; for(int i = index+1; i < n; i++){ if(t[i] - h[i] < start){ start = t[i] - h[i]; end = t[i]; index = i; } else if(t[i] - end < h[i]){ end = t[i]; index = i; } } mana += (end - start + 1) * (end - start) / 2; index++; } System.out.println(mana); } in.close(); out.close(); } }
0
28820c82
8637bb90
import java.util.*; import java.io.*; import java.math.*; import java.lang.*; public class MinimumGridPath { static int mod = 1000000007; public 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') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws Exception { Reader scn = new Reader(); PrintWriter pw = new PrintWriter(System.out); int t = scn.nextInt(); outer : while(t-->0){ int n = scn.nextInt(); long[] arr = new long[n]; for(int i=0; i<n; i++){ arr[i] = scn.nextInt(); } long ans = Long.MAX_VALUE; int k = 2; long oddSum = arr[0]; long evenSum = 0; long oddMin = arr[0]; long evenMin = Long.MAX_VALUE; long oddCount = 1; long evenCount = 0; while(k <= n){ if(k % 2 == 1){ oddSum += arr[k-1]; oddCount++; oddMin = Math.min(oddMin, arr[k-1]); }else{ evenSum += arr[k-1]; evenCount++; evenMin = Math.min(evenMin, arr[k-1]); } long sum = oddSum - oddMin + oddMin*(n - oddCount + 1) + evenSum - evenMin + evenMin*(n - evenCount + 1); ans = Math.min(ans, sum); k++; } pw.println(ans); } pw.close(); } public static class Pair{ long x; long y; Pair(long x, long y){ this.x = x; this.y = y; } } private static void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } private static void sort(long[] arr) { List<Long> list = new ArrayList<>(); for(int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } private static int lowerBound(int[] arr, int x){ int n = arr.length, si = 0, ei = n - 1; while(si <= ei){ int mid = si + (ei - si)/2; if(arr[mid] == x){ if(mid-1 >= 0 && arr[mid-1] == arr[mid]){ ei = mid-1; }else{ return mid; } }else if(arr[mid] > x){ ei = mid - 1; }else{ si = mid+1; } } return si; } private static int upperBound(int[] arr, int x){ int n = arr.length, si = 0, ei = n - 1; while(si <= ei){ int mid = si + (ei - si)/2; if(arr[mid] == x){ if(mid+1 < n && arr[mid+1] == arr[mid]){ si = mid+1; }else{ return mid + 1; } }else if(arr[mid] > x){ ei = mid - 1; }else{ si = mid+1; } } return si; } private static int upperBound(ArrayList<Integer> list, int x){ int n = list.size(), si = 0, ei = n - 1; while(si <= ei){ int mid = si + (ei - si)/2; if(list.get(mid) == x){ if(mid+1 < n && list.get(mid+1) == list.get(mid)){ si = mid+1; }else{ return mid + 1; } }else if(list.get(mid) > x){ ei = mid - 1; }else{ si = mid+1; } } return si; } // (x^y)%p in O(logy) private static long power(long x, long y){ long res = 1; x = x % mod; while(y > 0){ if ((y & 1) == 1){ res = (res * x) % mod; } y = y >> 1; x = (x * x) % mod; } return res; } public static boolean nextPermutation(int[] arr) { if(arr == null || arr.length <= 1){ return false; } int last = arr.length-2; while(last >= 0){ if(arr[last] < arr[last+1]){ break; } last--; } if (last < 0){ return false; } if(last >= 0){ int nextGreater = arr.length-1; for(int i=arr.length-1; i>last; i--){ if(arr[i] > arr[last]){ nextGreater = i; break; } } swap(arr, last, nextGreater); } reverse(arr, last+1, arr.length-1); return true; } private static void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } private static void reverse(int[] arr, int i, int j){ while(i < j){ swap(arr, i++, j--); } } // TC- O(logmax(a,b)) private static int gcd(int a, int b) { if(a == 0){ return b; } return gcd(b%a, a); } private static long gcd(long a, long b) { if(a == 0L){ return b; } return gcd(b%a, a); } private static long lcm(long a, long b) { return a / gcd(a, b) * b; } // TC- O(logmax(a,b)) private static int lcm(int a, int b) { return a / gcd(a, b) * b; } private static long inv(long x){ return power(x, mod - 2); } private static long summation(long n){ return (n * (n + 1L)) >> 1; } }
import java.util.*; import java.awt.Point; import java.io.*; import java.math.BigInteger; public class Solutions { static int MAX=Integer.MAX_VALUE; static int MIN=Integer.MIN_VALUE; //static ArrayList<ArrayList<Integer>>list=new ArrayList<ArrayList<Integer>>(); static FastScanner scr=new FastScanner(); static PrintStream out=new PrintStream(System.out); public static void main(String []args) { int T=scr.nextInt(); t:for(int tt=0;tt<T;tt++) { int n=scr.nextInt(); int []a=scr.readArray(n); long min[]=new long[2]; long sum[]=new long[2]; sum [0]=a[0]; sum [1]=0; min[0]=a[0]; min[1]=MAX; long ans=Long.MAX_VALUE; for(int i=1;i<n;i++) { min[i%2]=Math.min(min[i%2],a[i]); sum[i%2]+=a[i]; int odd=(i+2)/2; int even=(i+1)/2; ans=Math.min(ans,sum[0]+((n-odd)*min[0])+sum[1]+((n-even)*min[1])); } out.println(ans); } } static long modPow(long base,long exp,long mod) { if(exp==0) { return 1; } if(exp%2==0) { long res=(modPow(base,exp/2,mod)); return (res*res)%mod; } return (base*modPow(base,exp-1,mod))%mod; } static long gcd(long a,long b) { if(b==0) { return a; } return gcd(b,a%b); } 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[] sort(int a[]) { Arrays.sort(a); return a; } int []reverse(int a[]){ int b[]=new int[a.length]; int index=0; for(int i=a.length-1;i>=0;i--) { b[index]=a[i]; } return b; } 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[] 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()); } } } class triplet{ int x; int y; int z; triplet(int fisrt,int second,int third){ this.x=fisrt; this.y=second; this.z=third; } } class pair{ int x=0; int y=0; pair(int first,int second){ this.x=first; this.y=second; } }
0
b08b1c3c
d92b4600
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { static PrintWriter out = new PrintWriter(System.out); 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) {} return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); Node head = null; boolean notPossible = false; for (int i = 0; i < n; i++) { int x = sc.nextInt(); if (head == null) { head = new Node(x); } else { if ((head.next != null && x > head.next.value) || (head.prev != null && x < head.prev.value)) { notPossible = true; } else if ((head.next == null || x <= head.next.value) && x > head.value) { if (head.next != null && x == head.next.value) { head = head.next; continue; } Node temp = head.next; Node next = new Node(x); head.next = next; next.prev = head; next.next = temp; if (temp != null) { temp.prev = next; } head = next; } else if ((head.prev == null || x >= head.prev.value) && x < head.value) { if (head.prev != null && x == head.prev.value) { head = head.prev; continue; } Node temp = head.prev; Node prev = new Node(x); head.prev = prev; prev.next = head; prev.prev = temp; if (temp != null) { temp.next = prev; } head = prev; } } } if (notPossible) { out.println("NO"); } else { out.println("YES"); } } out.close(); } static class Node { int value; Node prev; Node next; Node(int value) { this.value = value; this.prev = null; this.next = null; } } }
import java.util.Scanner; public class D_724 { @SuppressWarnings("resource") public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); for(int test = 0; test < t; test++){ int n = input.nextInt(); ListNode on = new ListNode(input.nextInt(), null, null); boolean good = true; for(int i = 1; i < n; i++){ int num = input.nextInt(); if(good){ int at = on.data; if(num > at){ if(on.next == null || num < on.next.data){ on.next = new ListNode(num, on, on.next); on = on.next; if(on.next != null){ on.next.prev = on; } }else if(num == on.next.data){ on = on.next; }else{ good = false; } }else if(num < at){ if(on.prev == null || num > on.prev.data){ on.prev = new ListNode(num, on.prev, on); on = on.prev; if(on.prev != null){ on.prev.next = on; } }else if(num == on.prev.data){ on = on.prev; }else{ good = false; } } } } if(good){ System.out.println("YES"); }else{ System.out.println("NO"); } } } static class ListNode{ int data; ListNode prev; ListNode next; ListNode(int data, ListNode prev, ListNode next){ this.data = data; this.prev = prev; this.next = next; } } }
0
eea69e7f
f6ca6fc8
import java.util.*; public class Solution { public static int minMoves(int[] input) { List<Integer> people = new ArrayList<Integer>(); List<Integer> chairs = new ArrayList<Integer>(); for (int i = 0; i < input.length; i++) { if (input[i] == 1) { people.add(i); } else { chairs.add(i); } } int[] memo = new int[chairs.size() + 1]; for (int p = 1; ((!people.isEmpty()) && (p <= people.size())); p++) { int prev = memo[p]; memo[p] = memo[p - 1] + Math.abs(people.get(p - 1) - chairs.get(p - 1)); for (int c = p + 1; c <= chairs.size(); c++) { int tmp = memo[c]; memo[c] = Math.min(memo[c - 1], prev + Math.abs(people.get(p - 1) - chairs.get(c - 1))); prev = tmp; } } return memo[memo.length - 1]; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] input = new int[n]; for (int i = 0; i < n; i++) { input[i] = sc.nextInt(); } System.out.println(Solution.minMoves(input)); } }
import java.util.*; import java.io.*; public class D { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n = sc.nextInt(); ArrayList<Integer> o=new ArrayList<Integer>(); ArrayList<Integer> e=new ArrayList<Integer>(); for(int i=1;i<=n;i++){ int x=sc.nextInt(); if(x==1)o.add(i); else e.add(i); } int dp[][]=new int[o.size()+1][e.size()+1]; for(int i=1;i<=o.size();i++){ dp[i][i]=dp[i-1][i-1]+Math.abs(o.get(i-1)-e.get(i-1)); for(int j=i+1;j<=e.size();j++){ dp[i][j]=Math.min(dp[i][j-1],dp[i-1][j-1]+Math.abs(o.get(i-1)-e.get(j-1))); } } System.out.println(dp[o.size()][e.size()]); } }
0
584b0e9e
d9199dfd
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class D_Round_753_Div3 { public static int MOD = 1000000007; static int[][] dp; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int T = in.nextInt(); for (int z = 0; z < T; z++) { int n = in.nextInt(); int[] data = new int[n]; for (int i = 0; i < n; i++) { data[i] = in.nextInt(); } String line = in.next(); ArrayList<Integer> blue = new ArrayList<>(); ArrayList<Integer> red = new ArrayList<>(); for (int i = 0; i < n; i++) { if (line.charAt(i) == 'B') { blue.add(data[i]); } else { red.add(data[i]); } } Collections.sort(blue); Collections.sort(red); int st = 1; boolean ok = true; for (int i : blue) { if (i < st) { ok = false; break; } st++; } if (ok) { for (int i : red) { if (i > st) { ok = false; break; } st++; } } out.println(ok ? "Yes" : "No"); } out.close(); } static int find(int v, int[] u) { if (v == u[v]) { return v; } return u[v] = find(u[v], u); } static int abs(int a) { return a < 0 ? -a : a; } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point { int x; int y; public Point(int start, int end) { this.x = start; this.y = end; } public String toString() { return x + " " + y; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; data[index] %= MOD; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; result %= MOD; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return (val * val); } else { return (val * ((val * a))); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; public class Simple{ public static void main(String args[]){ //System.out.println("Hello Java"); Scanner s = new Scanner(System.in); int t = s.nextInt(); while (t>0){ int n = s.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++){ arr[i] = s.nextInt(); } String str = s.next(); //Arrays.sort(arr); ArrayList<Integer> blue = new ArrayList<>(); ArrayList<Integer> red = new ArrayList<>(); for(int i=0;i<n;i++){ if(str.charAt(i)=='R'){ red.add(arr[i]); } else{ blue.add(arr[i]); } } Collections.sort(red); Collections.sort(blue); int start =1; boolean bool =true; for(int i=0;i<blue.size();i++){ if(blue.get(i)<start){ bool = false; break; } start++; } if(!bool){ System.out.println("NO"); } else{ for(int i=0;i<red.size();i++){ if(red.get(i)>start){ bool = false; break; } start++; } if(bool){ System.out.println("YES"); } else{ System.out.println("NO"); } } t--; } s.close(); } }
1
29bbcd8b
d4779c71
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Stack; import java.util.StringTokenizer; public class D { private static final String INPUT_FILE_PATH = ""; void solve() { int n = in.nextInt(); int[] h = new int[n]; for (int i = 0; i < n; i++) h[i] = in.nextInt(); Stack<Integer> increasing = new Stack(); Stack<Integer> increasingIndices = new Stack(); Stack<Integer> decreasing = new Stack(); Stack<Integer> decreasingIndices = new Stack(); increasing.push(h[0]); increasingIndices.push(0); decreasing.push(h[0]); decreasingIndices.push(0); int[] dp = new int[n]; dp[0] = 0; for (int i = 1; i < n; i++) { dp[i] = dp[i - 1] + 1; while (!increasing.isEmpty() && increasing.peek() > h[i]) { dp[i] = Math.min(dp[i], 1 + dp[increasingIndices.peek()]); increasing.pop(); increasingIndices.pop(); } while (!decreasing.isEmpty() && decreasing.peek() < h[i]) { dp[i] = Math.min(dp[i], 1 + dp[decreasingIndices.peek()]); decreasing.pop(); decreasingIndices.pop(); } if (!increasing.isEmpty()) { dp[i] = Math.min(dp[i], 1 + dp[increasingIndices.peek()]); } if (!decreasing.isEmpty()) { dp[i] = Math.min(dp[i], 1 + dp[decreasingIndices.peek()]); } if (!increasing.isEmpty() && increasing.peek() == h[i]) { increasing.pop(); increasingIndices.pop(); } if (!decreasing.isEmpty() && decreasing.peek() == h[i]) { decreasing.pop(); decreasingIndices.pop(); } increasing.push(h[i]); increasingIndices.push(i); decreasing.push(h[i]); decreasingIndices.push(i); } out.println(dp[n - 1]); } private final InputReader in; private final PrintWriter out; private D(InputReader in, PrintWriter out) { this.in = in; this.out = out; } private static class InputReader { private BufferedReader br; private StringTokenizer st; public InputReader(InputStream inputStream) { this.br = new BufferedReader(new InputStreamReader(inputStream), 32768); this.st = null; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } 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 main(String[] args) throws Exception { InputStream inputStream = INPUT_FILE_PATH.isEmpty() ? System.in : new FileInputStream(new File(INPUT_FILE_PATH)); OutputStream outputStream = System.out; InputReader inputReader = new InputReader(inputStream); PrintWriter printWriter = new PrintWriter(outputStream); new D(inputReader, printWriter).solve(); printWriter.close(); } }
import java.util.ArrayList; import java.util.Scanner; import java.util.Stack; public class D { static Scanner sc = new Scanner(System.in); static int[] height; static int[] dp; public static void main(String[] args) { int n = sc.nextInt(); height = new int[n]; dp = new int[n]; dp[0] = 0; for (int i = 0; i < n; i++) { height[i] = sc.nextInt(); } Stack<Integer> rise = new Stack<Integer>(); Stack<Integer> fail = new Stack<Integer>(); rise.push(0); fail.push(0); for (int i = 1; i < n; i++) { dp[i] = dp[i-1]+1; if (rise.isEmpty()) { rise.push(i); } else if (height[rise.peek()] < height[i]) { rise.push(i); } else { while (!rise.isEmpty() && height[rise.peek()] > height[i]) { rise.pop(); if (!rise.isEmpty()) { dp[i] = Math.min(dp[i], dp[rise.peek()] + 1); } } while (!rise.isEmpty() && height[rise.peek()] == height[i]) { rise.pop(); } rise.push(i); } if (fail.isEmpty()) { fail.push(i); } else if (height[fail.peek()] > height[i]) { fail.push(i); } else { while (!fail.isEmpty() && height[fail.peek()] < height[i]) { fail.pop(); if (!fail.isEmpty()){ dp[i] = Math.min(dp[i], dp[fail.peek()] + 1); } } while (!fail.isEmpty() && height[fail.peek()] == height[i]) { fail.pop(); } fail.push(i); } } System.out.println(dp[n - 1]); } } // a[i] // // // 6 7 6 2 //3 5 6 4 5 6 3
0
3e93b259
a60fba84
import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair implements Comparable<Pair> { int f,s; Pair(int f,int s) { this.f=f; this.s=s; } public int compareTo(Pair p) { return this.f-p.f; } } public static void main(String args[]) { FastReader fs=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int tc=fs.nextInt(); while(tc-->0) { int n=fs.nextInt(); long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=fs.nextLong(); long minans=a[0]*n+a[1]*n; long sum=a[0]+a[1]; long min1=a[0],min2=a[1]; for(int i=2;i<n;i++) { sum+=a[i]; if(i%2==0) min1=Math.min(min1,a[i]); else min2=Math.min(min2,a[i]); long tsum=sum-min1-min2; if(i%2==0) tsum=tsum+(n-i/2+1)*min2+(n-i/2)*min1; else tsum=tsum+(min1+min2)*(n-((i+1)/2)+1); minans=Math.min(minans,tsum); //minans=Math.min(minans,(n-cnt1)*a[i]+(n-cnt2)*a[i-1]+sum); } pw.println(minans); } pw.flush(); pw.close(); } }
/*input 3 2 13 88 3 2 3 1 5 4 3 2 1 4 */ import java.util.*; import java.lang.*; import java.io.*; public class Main { static PrintWriter out; static int MOD = 1000000007; static FastReader scan; /*-------- I/O using short named function ---------*/ public static String ns(){return scan.next();} public static int ni(){return scan.nextInt();} public static long nl(){return scan.nextLong();} public static double nd(){return scan.nextDouble();} public static String nln(){return scan.nextLine();} public static void p(Object o){out.print(o);} public static void ps(Object o){out.print(o + " ");} public static void pn(Object o){out.println(o);} /*-------- for output of an array ---------------------*/ static void iPA(int arr []){ StringBuilder output = new StringBuilder(); for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output); } static void lPA(long arr []){ StringBuilder output = new StringBuilder(); for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output); } static void sPA(String arr []){ StringBuilder output = new StringBuilder(); for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output); } static void dPA(double arr []){ StringBuilder output = new StringBuilder(); for(int i=0; i<arr.length; i++)output.append(arr[i] + " ");out.println(output); } /*-------------- for input in an array ---------------------*/ static void iIA(int arr[]){ for(int i=0; i<arr.length; i++)arr[i] = ni(); } static void lIA(long arr[]){ for(int i=0; i<arr.length; i++)arr[i] = nl(); } static void sIA(String arr[]){ for(int i=0; i<arr.length; i++)arr[i] = ns(); } static void dIA(double arr[]){ for(int i=0; i<arr.length; i++)arr[i] = nd(); } /*------------ for taking input faster ----------------*/ 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; } } // Method to check if x is power of 2 static boolean isPowerOfTwo (int x) { return x!=0 && ((x&(x-1)) == 0);} //Method to return lcm of two numbers static int gcd(int a, int b){return a==0?b:gcd(b % a, a); } //Method to count digit of a number static int countDigit(long n){return (int)Math.floor(Math.log10(n) + 1);} //Method for sorting static void ruffle_sort(int[] a) { //shandom_ruffle Random r=new Random(); int n=a.length; for (int i=0; i<n; i++) { int oi=r.nextInt(n); int temp=a[i]; a[i]=a[oi]; a[oi]=temp; } //sort Arrays.sort(a); } //Method for checking if a number is prime or not 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 void main (String[] args) throws java.lang.Exception { OutputStream outputStream =System.out; out =new PrintWriter(outputStream); scan =new FastReader(); //for fast output sometimes StringBuilder sb = new StringBuilder(); int t = ni(); while(t-->0){ int n = ni(); long arr[] = new long[n]; lIA(arr); long ans = (long)(n*(arr[0] + arr[1])); long sum = arr[0] + arr[1]; long emin = arr[0], omin = arr[1]; for(int i=2; i<n; i++){ sum += arr[i]; if(i%2==0){ emin = Math.min(arr[i], emin); } else{ omin = Math.min(arr[i], omin); } long temp = sum - emin - omin; if(i%2==0) temp += (n-i/2)*emin + (n-i/2+1)*omin; else temp += (n-(i-1)/2)*(emin + omin); ans = Math.min(ans, temp); } pn(ans); } out.flush(); out.close(); } }
1
3412b353
528a6162
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { int n=Integer.parseInt(bu.readLine()); int k[]=new int[n+1],h[]=new int[n+1],i; String s[]=bu.readLine().split(" "); for(i=1;i<=n;i++) k[i]=Integer.parseInt(s[i-1]); s=bu.readLine().split(" "); for(i=1;i<=n;i++) h[i]=Integer.parseInt(s[i-1]); long max[]=new long[n+1]; for(i=1;i<=n;i++) { int j; long here=h[i]; for(j=i-1;j>=0;j--) { long diff=here-(k[i]-k[j]); if(diff<=0) {max[i]=max[j]+here*(here+1)/2; break;} if(diff<h[j]) here+=h[j]-diff; } } sb.append(max[n]+"\n"); } System.out.print(sb); } }
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); while(t-->0) { int n=Integer.parseInt(bu.readLine()); int k[]=new int[n+1],h[]=new int[n+1],i; String s[]=bu.readLine().split(" "); for(i=1;i<=n;i++) k[i]=Integer.parseInt(s[i-1]); s=bu.readLine().split(" "); for(i=1;i<=n;i++) h[i]=Integer.parseInt(s[i-1]); long max[]=new long[n+1]; for(i=1;i<=n;i++) { int j; long here=h[i]; for(j=i-1;j>=0;j--) { long diff=here-(k[i]-k[j]); if(diff<=0) {max[i]=max[j]+here*(here+1)/2; break;} if(diff<h[j]) here+=h[j]-diff; } } sb.append(max[n]+"\n"); } System.out.print(sb); } }
1
1c90c367
e52863b8
/* /$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ |__ $$ /$$__ $$ |$$ |$$ /$$__ $$ | $$| $$ \ $$| $$|$$| $$ \ $$ | $$| $$$$$$$$| $$ / $$/| $$$$$$$$ / $$ | $$| $$__ $$ \ $$ $$/ | $$__ $$ | $$ | $$| $$ | $$ \ $$$/ | $$ | $$ | $$$$$$/| $$ | $$ \ $/ | $$ | $$ \______/ |__/ |__/ \_/ |__/ |__/ /$$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$ /$$ /$$ /$$ /$$$$$$$$ /$$$$$$$ | $$__ $$| $$__ $$ /$$__ $$ /$$__ $$| $$__ $$ /$$__ $$| $$$ /$$$| $$$ /$$$| $$_____/| $$__ $$ | $$ \ $$| $$ \ $$| $$ \ $$| $$ \__/| $$ \ $$| $$ \ $$| $$$$ /$$$$| $$$$ /$$$$| $$ | $$ \ $$ | $$$$$$$/| $$$$$$$/| $$ | $$| $$ /$$$$| $$$$$$$/| $$$$$$$$| $$ $$/$$ $$| $$ $$/$$ $$| $$$$$ | $$$$$$$/ | $$____/ | $$__ $$| $$ | $$| $$|_ $$| $$__ $$| $$__ $$| $$ $$$| $$| $$ $$$| $$| $$__/ | $$__ $$ | $$ | $$ \ $$| $$ | $$| $$ \ $$| $$ \ $$| $$ | $$| $$\ $ | $$| $$\ $ | $$| $$ | $$ \ $$ | $$ | $$ | $$| $$$$$$/| $$$$$$/| $$ | $$| $$ | $$| $$ \/ | $$| $$ \/ | $$| $$$$$$$$| $$ | $$ |__/ |__/ |__/ \______/ \______/ |__/ |__/|__/ |__/|__/ |__/|__/ |__/|________/|__/ |__/ */ import java.io.BufferedReader; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import java.io.*; public class abc { static PrintWriter pw; static long x = 1, y = 1; /* * static long inv[]=new long[1000001]; static long dp[]=new long[1000001]; */ /// MAIN FUNCTION/// public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); pw = new PrintWriter(System.out); // use arraylist as it uses the concept of dynamic table(amortized analysis) // Arrays.stream(array).forEach(a -> Arrays.fill(a, 0)); /* List<Integer> l1 = new ArrayList<Integer>(); */ // Random rand = new Random(); int tst = sc.nextInt(); while(tst-->0) { int n=sc.nextInt(); int app[]=new int[n]; int h[]=new int[n]; for(int i=0;i<n;i++) { app[i]=sc.nextInt(); } for(int i=0;i<n;i++) { h[i]=sc.nextInt(); } long man = 0; long last = app[n - 1] - h[n - 1] + 1; int end = n-1; for (int i = n-2; i >=0; i--) { if(app[i]>=last) { last = Math.min(last,app[i] - h[i] + 1); } else { long s = app[end]-last+1; man += (s*(s+1))/2; end = i; last = app[i] - h[i] + 1;; } } long s = app[end]-last+1; man += (s*(s+1))/2; pw.println(man); } pw.flush(); } public static long eculidean_gcd(long a, long b) { if (a == 0) { x = 0; y = 1; return b; } long ans = eculidean_gcd(b % a, a); long x1 = x; x = y - (b / a) * x; y = x1; return ans; } public static int sum(int n) { int sum = 1; if (n == 0) return 0; while (n != 0) { sum = sum * n; n = n - 1; } return sum; } public static boolean isLsbOne(int n) { if ((n & 1) != 0) return true; return false; } public static pair helper(int arr[], int start, int end, int k, pair dp[][]) { if (start >= end) { if (start == end) return (new pair(arr[start], 0)); else return (new pair(0, 0)); } if (dp[start][end].x != -1 && dp[start][end].y != -1) { return dp[start][end]; } pair ans = new pair(0, Integer.MAX_VALUE); for (int i = start; i < end; i++) { pair x1 = helper(arr, start, i, k, dp); pair x2 = helper(arr, i + 1, end, k, dp); long tip = k * (x1.x + x2.x) + x1.y + x2.y; if (tip < ans.y) ans = new pair(x1.x + x2.x, tip); } return dp[start][end] = ans; } public static void debugger() { Random rand = new Random(); int tst = (int) (Math.abs(rand.nextInt()) % 2 + 1); pw.println(tst); while (tst-- > 0) { int n = (int) (Math.abs(rand.nextInt()) % 5 + 1); pw.println(n); for (int i = 0; i < n; i++) { pw.print((int) (Math.abs(rand.nextInt()) % 6 + 1) + " "); } pw.println(); } } static int UpperBound(long a[], long x) {// x is the key or target value int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] <= x) l = m; else r = m; } return l + 1; } static int LowerBound(long a[], long 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 void recursion(int n) { if (n == 1) { pw.print(n + " "); return; } // pw.print(n+" "); gives us n to 1 recursion(n - 1); // pw.print(n+" "); gives us 1 to n } // ch.charAt(i)+"" converts into a char sequence 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; } /* CREATED BY ME */ 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; } } public static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } public static boolean isPrime(long n) { if (n == 2) return true; long i = 2; while (i * i <= n) { if (n % i == 0) return false; i++; } return true; } static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static double max(double x, double y) { return Math.max(x, y); } static int min(int x, int y) { return Math.min(x, y); } static int abs(int x) { return Math.abs(x); } static long abs(long x) { return Math.abs(x); } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } static long max(long x, long y) { return Math.max(x, y); } static long min(long x, long y) { return Math.min(x, y); } public static class pair { long x; long y; public pair(long a, long b) { x = a; y = b; } } public static class Comp implements Comparator<pair> { public int compare(pair a, pair b) { long ans = a.x - b.x; if (ans > 0) return 1; if (ans < 0) return -1; return 0; } } // modular exponentiation public static long fastExpo(long a, int n, int mod) { if (n == 0) return 1; else { if ((n & 1) == 1) { long x = fastExpo(a, n / 2, mod); return (((a * x) % mod) * x) % mod; } else { long x = fastExpo(a, n / 2, mod); return (((x % mod) * (x % mod)) % mod) % mod; } } } public static long modInverse(long n, int p) { return fastExpo(n, p - 2, p); } /* * public static void extract(ArrayList<Integer> ar, int k, int d) { int c = 0; * for (int i = 1; i < k; i++) { int x = 0; boolean dm = false; while (x > 0) { * long dig = x % 10; x = x / 10; if (dig == d) { dm = true; break; } } if (dm) * ar.add(i); } } */ public static int[] prefixfuntion(String s) { int n = s.length(); int z[] = new int[n]; for (int i = 1; i < n; i++) { int j = z[i - 1]; while (j > 0 && s.charAt(i) != s.charAt(j)) j = z[j - 1]; if (s.charAt(i) == s.charAt(j)) j++; z[i] = j; } return z; } // counts the set(1) bit of a number public static long countSetBitsUtil(long x) { if (x <= 0) return 0; return (x % 2 == 0 ? 0 : 1) + countSetBitsUtil(x / 2); } //tells whether a particular index has which bit of a number public static int getIthBitsUtil(int x, int y) { return (x & (1 << y)) != 0 ? 1 : 0; } public static void swaper(long x, long y) { x = x ^ y; y = y ^ x; x = x ^ y; } public static double decimalPlaces(double sum) { DecimalFormat df = new DecimalFormat("#.00"); String angleFormated = df.format(sum); double fin = Double.parseDouble(angleFormated); return fin; } //use collections.swap for swapping static boolean isSubSequence(String str1, String str2, int m, int n) { int j = 0; for (int i = 0; i < n && j < m; i++) if (str1.charAt(j) == str2.charAt(i)) j++; return (j == m); } static long sum(long n) { long s2 = 0, max = -1, min = 10; while (n > 0) { s2 = (n % 10); min = min(s2, min); max = max(s2, max); n = n / 10; } return max * min; } static long pow(long base, long power) { if (power == 0) { return 1; } long result = pow(base, power / 2); if (power % 2 == 1) { return result * result * base; } return result * result; } // return the hash value of a string static long compute_hash(String s) { long val = 0; long p = 31; long mod = (long) (1000000007); long pow = 1; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); val = (val + (int) (ch - 'a' + 1) * pow) % mod; pow = (pow * p) % mod; } return val; } }
import java.util.*; import java.io.*; public class q3{ static FastScanner fs = new FastScanner(); static PrintWriter pw = new PrintWriter(System.out); static int[] sec; static int[] health; static int[] pp; public static void main(String[] args){ int T = fs.nextInt(); for (int tt=0;tt<T;tt++){ int n = fs.nextInt(); sec = new int[n]; health = new int[n]; for (int i=0;i<n;i++) sec[i] = fs.nextInt(); for (int i=0;i<n;i++) health[i] = fs.nextInt(); pp = new int[]{sec[n-1]-health[n-1]+1, sec[n-1], health[n-1]}; long sum = 0; for (int i=n-2;i>=0;i--){ int left = sec[i] - health[i] + 1, right = sec[i], top = health[i]; if (right < pp[0]){ sum += ((long)pp[2] + 1) * (long)pp[2] / 2; pp = new int[]{left, right, top}; } else if (left < pp[0]){ pp[0] = left; pp[2] = top + (pp[1] - right); } } sum += ((long)pp[2] + 1) * (long)pp[2] / 2; pw.println(sum); } pw.close(); } // ----------input function---------- static void sort(int[] a){ ArrayList<Integer> L = new ArrayList<>(); for (int i : a) L.add(i); Collections.sort(L); for (int i = 0; i < a.length; i++) a[i] = L.get(i); } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next(){ while (!st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } int[] readArray(int n){ int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong(){ return Long.parseLong(next()); } } }
0
11c2ab99
bdfe8110
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { FastScanner fs=new FastScanner(); int T=fs.nextInt(); PrintWriter out=new PrintWriter(System.out); for (int tt=0; tt<T; tt++) { int n=fs.nextInt(), k=fs.nextInt(); int[] positions=fs.readArray(k), temps=fs.readArray(k); int[] forced=new int[n]; Arrays.fill(forced, Integer.MAX_VALUE/2); for (int i=0; i<k; i++) forced[positions[i]-1]=temps[i]; for (int i=1; i<n; i++) forced[i]=Math.min(forced[i], forced[i-1]+1); for (int i=n-2; i>=0; i--) forced[i]=Math.min(forced[i], forced[i+1]+1); for (int i=0; i<n; i++) out.print(forced[i]+" "); out.println(); } out.close(); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class E { public static void main(String[] args) { FastScanner fs=new FastScanner(); int T=fs.nextInt(); PrintWriter out=new PrintWriter(System.out); for (int tt=0; tt<T; tt++) { int n=fs.nextInt(), k=fs.nextInt(); int[] positions=fs.readArray(k), temps=fs.readArray(k); int[] forced=new int[n]; Arrays.fill(forced, Integer.MAX_VALUE/2); for (int i=0; i<k; i++) forced[positions[i]-1]=temps[i]; for (int i=1; i<n; i++) forced[i]=Math.min(forced[i], forced[i-1]+1); for (int i=n-2; i>=0; i--) forced[i]=Math.min(forced[i], forced[i+1]+1); for (int i=0; i<n; i++) out.print(forced[i]+" "); out.println(); } out.close(); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
1
0b5cff5a
4fb09c5f
import java.io.*; import java.text.DecimalFormat; import java.util.*; public class E { static long mod=(long)1e9+7; static long mod1=998244353; public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); int t= in.nextInt(); while(t-->0) { int n = in.nextInt(); int k = in.nextInt(); int[] a= in.readArray(k); int[] temp = in.readArray(k); int[] pre = new int[n]; Arrays.fill(pre,Integer.MAX_VALUE); int[] suf = new int[n]; Arrays.fill(suf,Integer.MAX_VALUE); for(int i = 0;i<k;i++){ pre[a[i]-1]=temp[i]; suf[a[i]-1]=temp[i]; } int min = Integer.MAX_VALUE; E.ruffleSort(a); for(int i=a[0]-1;i<n;i++){ min = Math.min(min,pre[i]); pre[i] = min; min++; } min = Integer.MAX_VALUE; for(int i = a[k-1]-1;i>=0;i--){ min = Math.min(min,suf[i]); suf[i] = min; min++; } for(int i=0;i<n;i++) out.print(Math.min(pre[i],suf[i])+" "); out.println(); } out.close(); } 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 long gcd(long x, long y){ if(x==0) return y; if(y==0) return x; long r=0, a, b; a = Math.max(x, y); b = Math.min(x, y); r = b; while(a % b != 0){ r = a % b; a = b; b = r; } return r; } static long modulo(long a,long b,long c){ long x=1,y=a%c; while(b > 0){ if(b%2 == 1) x=(x*y)%c; y = (y*y)%c; b = b>>1; } return x%c; } public static void debug(Object... o){ System.err.println(Arrays.deepToString(o)); } static int upper_bound(int[] arr,int n,int x){ int mid; int low=0; int high=n; while(low<high){ mid=low+(high-low)/2; if(x>=arr[mid]) low=mid+1; else high=mid; } return low; } static int lower_bound(int[] arr,int n,int x){ int mid; int low=0; int high=n; while(low<high){ mid=low+(high-low)/2; if(x<=arr[mid]) high=mid; else low=mid+1; } return low; } static String printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.00000000000"); return String.valueOf(ft.format(d)); } static int countBit(long mask){ int ans=0; while(mask!=0){ mask&=(mask-1); ans++; } return ans; } 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 int[] readArray(int n) { int[] arr=new int[n]; for(int i=0;i<n;i++) arr[i]=nextInt(); return arr; } } }
import java.io.*; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Logger; import java.util.stream.Collectors; public class Trial { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int q = sc.nextInt(); while (q-- > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[k]; int[] t = new int[k]; HashMap<Integer, Integer> hm = new HashMap<>(); for (int i = 0; i < k; i++) { arr[i] = sc.nextInt() - 1; } for (int i = 0; i < k; i++) { t[i] = sc.nextInt(); hm.put(arr[i], t[i]); } int[] left = new int[n]; int[] right = new int[n]; left[0] = hm.getOrDefault(0, -1); right[n - 1] = hm.getOrDefault(n - 1, -1); for (int i = 1; i < n; i++) { if (hm.containsKey(i)) { if (left[i - 1] < 0) { left[i] = hm.get(i); } else { left[i] = Math.min(hm.get(i), left[i - 1] + 1); } } else { left[i] = left[i - 1] < 0 ? -1 : left[i - 1] + 1; } } for (int i = n - 2; i >= 0; i--) { if (hm.containsKey(i)) { if (right[i + 1] < 0) { right[i] = hm.get(i); } else { right[i] = Math.min(hm.get(i), right[i + 1] + 1); } } else { right[i] = right[i + 1] < 0 ? -1 : right[i + 1] + 1; } } for (int i = 0; i < n; i++) { if (left[i] < 0) { pw.print(right[i] + " "); } else if (right[i] < 0) { pw.print(left[i] + " "); } else { pw.print(Math.min(left[i], right[i]) + " "); } } pw.println(); } pw.flush(); pw.close(); } // inclusive private static void rotate(int[] arr, int l, int r) { int temp = arr[r]; for (int i = r - 1; i >= l; i--) { arr[i + 1] = arr[i]; } arr[l] = temp; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System) throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(System)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() { for (long i = 0; i < 3e9; i++) ; } } static class Pair { int a; int b; boolean asc; Pair(int a, int b, boolean asc) { this.a = a; this.b = b; this.asc = asc; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return a == pair.a && b == pair.b && asc == pair.asc; } @Override public int hashCode() { return Objects.hash(a, b, asc); } } }
0
54488276
f4757480
import java.io.*; import java.util.*; public class C { static int n; public static void main (String[] args) throws IOException { Kattio io = new Kattio(); int t = io.nextInt(); for (int ii=0; ii<t; ii++) { n = io.nextInt(); String[] arr = new String[n]; for (int i=0; i<n; i++) { String str = io.next(); arr[i] = str; } char[] chars = new char[]{'a','b','c','d','e'}; int ans = -1; for (int i=0; i<5; i++) { ans = Math.max(ans, solve(arr, chars[i])); } System.out.println(ans); } } static int solve(String[] arr, char c) { //System.out.println("Comparing based on " + c); Arrays.sort(arr, new Comp(c)); int good = 0; int total = 0; int ret = 0; for (int i=0; i<n; i++) { //System.out.println(good + " " + total); for (int j=0; j<arr[i].length(); j++) { if (arr[i].charAt(j) == c) good++; } total += arr[i].length(); if (2 * good > total) { ret++; } else { return ret; } } return ret; } static class Comp implements Comparator<String> { char c; public Comp (char c) { this.c = c; } public int compare(String a, String b) { double cnt1 = 0; double cnt2 = 0; for (int i=0; i<a.length(); i++) { if (a.charAt(i) == c) { cnt1++; } } for (int i=0; i<b.length(); i++) { if (b.charAt(i) == c) { cnt2++; } } //higher ratio is better return -Double.compare(cnt1 - (a.length() - cnt1), cnt2 - (b.length() - cnt2)); } } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(new FileWriter(problemName + ".out")); r = new BufferedReader(new FileReader(problemName + ".in")); } // returns null if no more input public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(r.readLine()); return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
import java.util.*; import java.io.*; public class CF_1551c{ public static final void main(String[] args){ Kattio io= new Kattio(); int t= io.getInt(); while(t-->0){ int n= io.getInt(); int[][] ps= new int[5][n]; for(int i=0; i<n; i++){ String w= io.getWord(); int len= w.length(); // count letters for(int j=0; j<len; j++) ps[w.charAt(j)-'a'][i]++; // calculate diffs letter-!letter // e.g. a-!a = a-(a+b+c+d+e-a) = a-(len-a) = a + (a-len) = 2a-len for(int k=0; k<5; k++) ps[k][i]+= ps[k][i]-len; } //sort diffs for(int k=0; k<5; k++) //mergeSort(ps[k]); Arrays.sort(ps[k]); //calculate prefix sums of diffs (until they're non-positive) //start from the end as sort is ascending //pick largest index out of 5 letter at which sum of diffs is positive int max= 0; for(int k=0; k<5; k++){ if(ps[k][n-1]<=0) continue; if(max==0) max= 1; for(int i=2; i<=n; i++){ ps[k][n-i]+= ps[k][n-i+1]; if(ps[k][n-i]<=0) break; if(i>max) max= i; } } io.println(max); } io.close(); } // using mergeSort to avoid Java quicksort TLE hacks static void mergeSort(int arr[]){ int n= arr.length; for (int sz= 1; sz<=n-1; sz=2*sz){ for (int l= 0; l<n-1; l+=2*sz){ int m= Math.min(l + sz-1, n-1); int r= Math.min(l + 2*sz-1, n-1); int n1= m-l+1, n2= r-m; int L[] = new int[n1]; for (int i= 0; i<n1; i++) L[i]= arr[l+i]; int R[] = new int[n2]; for (int j= 0; j<n2; j++) R[j]= arr[m+1+j]; int i= 0, j= 0, k= l; for(;i<n1 && j<n2; k++){ if(L[i]<=R[j]){arr[k]= L[i]; i++;} else{arr[k] = R[j]; j++;} } for(;i<n1; i++, k++) arr[k]= L[i]; for(;j<n2; j++, k++) arr[k]= R[j]; } } } static class Kattio extends PrintWriter { private BufferedReader r; private String line, token; private StringTokenizer st; public Kattio(){this(System.in);} public Kattio(InputStream i){ super(new BufferedOutputStream(System.out)); r= new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o){ super(new BufferedOutputStream(o)); r= new BufferedReader(new InputStreamReader(i)); } public boolean isLineEnd(){ return !st.hasMoreTokens(); } public boolean hasMoreTokens(){ return peekToken()!=null; } public int getInt(){ return Integer.parseInt(nextToken()); } public double getDouble(){ return Double.parseDouble(nextToken()); } public long getLong(){ return Long.parseLong(nextToken()); } public String getWord(){ return nextToken(); } public String getLine(){ try{if(!st.hasMoreTokens()) return r.readLine(); }catch(IOException e){} return null; } private String peekToken(){ if(token==null) try { while(st==null || !st.hasMoreTokens()) { line= r.readLine(); if(line==null) return null; st= new StringTokenizer(line); } token= st.nextToken(); }catch(IOException e){} return token; } private String nextToken() { String ans= peekToken(); token= null; return ans; } } }
0
505f8562
ed37ba7d
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.lang.System.out; import static java.lang.Long.MAX_VALUE; public final class Main{ FastReader in; StringBuffer sb; public static void main(String[] args) { new Main().run(); } void run(){ in= new FastReader(); start(); } void start(){ sb= new StringBuffer(); for(int t=in.nextInt();t>0;t--) solve(); out.print(sb); } long MOD= 1000000007; void solve(){ int n= in.nextInt(); int k= in.nextInt(); long[] a=longArr(k); long[] t=longArr(k); long[] ans= new long[n]; for(int i=0;i<n;i++){ ans[i]= Integer.MAX_VALUE; } for(int i=0;i<k;i++){ ans[(int) (a[i]-1)]= t[i]; } long[] left= new long[n]; left[0]= ans[0]; for(int i=1;i<n;i++) { left[i]= min(left[i-1]+1,ans[i]); } long[] right= new long[n]; right[n-1]= ans[n-1]; for(int i=n-2;i>=0;i--) { right[i]= min(right[i+1]+1,ans[i]); } for(int i=0;i<n;i++) sb.append(min(left[i], right[i])).append(" "); sb.append("\n"); } int upper_bound(long[] arr, int key) { int i=0, j=arr.length-1; if (arr[j]<=key) return j+1; if(arr[i]>key) return i; while (i<j){ int mid= (i+j)/2; if(arr[mid]<=key){ i= mid+1; }else{ j=mid; } } return i; } void sort(long[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } long[] longArr(int n){ long[] res= new long[n]; for(int i=0;i<n;i++){ res[i]= in.nextLong(); } return res; } // sieve of eratosthenes code for precomputing whether numbers are prime or not up to MAX_VALUE long MAX= MAX_VALUE; int[] precomp= new int[(int) (MAX+1)]; void sieve(){ long n= MAX; 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[p] is not changed, then it is a prime if(prime[(int) p]) { // Update all multiples of p for(long i = p*p; i <= n; i += p) prime[(int) i] = false; } } // Print all prime numbers for(long i = 2; i <= n; i++) { if(prime[(int) i]) precomp[(int) i]= 1; } } boolean isDigitSumPalindrome(long N) { // code here long sum= sumOfDigits(String.valueOf(N)); long rev=0; long org= sum; while (sum!=0){ long d= sum%10; rev = rev*10 +d; sum /= 10; } return org == rev; } long sumOfDigits(String n){ long sum= 0; for (char c: n.toCharArray()){ sum += Integer.parseInt(String.valueOf(c)); } return sum; } long[] revArray(long[] arr) { int n= arr.length; int i=0, j=n-1; while (i<j){ long temp= arr[i]; arr[i]= arr[j]; arr[j]= temp; i++; j--; } return arr; } long gcd(long a, long b){ if (b==0) return a; return gcd(b, a%b); } long lcm(long a,long b){ return (a*b)/gcd(a,b); } static class Pair{ long first; long second; Pair(long x,long y){ this.first=x; this.second=y; } } static class Compare { static void compare(ArrayList<Pair> arr, long n) { arr.sort(new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return (int) (p1.first - p2.first); } }); } } 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 (Exception 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 (Exception e){ e.printStackTrace(); } return str; } } }
import java.io.*; import java.util.*; import java.lang.*; public class codeforces { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; if (System.getProperty("ONLINE_JUDGE") == null) { long startTime = System.currentTimeMillis(); try { sc = new InputReader(new FileInputStream("input.txt")); out = new PrintWriter(new FileOutputStream("output.txt")); pr = new PrintWriter(new FileOutputStream("error.txt")); } catch (Exception ignored) { } int t = 1; int tt = t; t = sc.nextInt(); while (t-- > 0) { solve(); } long endTime = System.currentTimeMillis(); System.out.println("Time: " + (endTime - startTime) / tt + " ms"); out.flush(); pr.flush(); } else { sc = new InputReader(inputStream); out = new PrintWriter(outputStream); pr = new PrintWriter(outputStream); int t = 1; t = sc.nextInt(); while (t-- > 0) { solve(); } out.flush(); } } public static void solve() { n = sc.nextInt(); for (int i = 0; i < n; i++) { dp[i] = inf; ans[i] = inf; } m = sc.nextInt(); for (int i = 0; i < m; i++) arr[i] = sc.nextInt() - 1; for (int i = 0; i < m; i++) { arr2[i] = sc.nextInt(); dp[(int)arr[i]] = arr2[i]; } temp = inf; for (int i = 0; i < n; i++) { temp = Math.min(temp, dp[i]); ans[i] = Math.min(ans[i], temp); temp++; } temp = inf; for (int i = (int)n - 1; i > -1; i--) { temp = Math.min(temp, dp[i]); ans[i] = Math.min(ans[i], temp); temp++; } for (int i = 0; i < n; i++) out.print(ans[i] + " "); out.println(""); } /* * Set Iterator Iterator value = set.iterator(); Displaying the values after * iterating through the iterator * System.out.println("The iterator values are: "); while (value.hasNext()) { * System.out.println(value.next()); } */ /* * Map Iterator: for (Map.Entry<Integer, Integer> entry : map.entrySet()){ * System.out.println("Key => " + entry.getKey() + ", Value => " + * entry.getValue());} */ // Globals public static long n, m, temp; public static int template_array_size = (int) 1e6 + 16813; public static long[] arr = new long[template_array_size]; public static long[] arr2 = new long[template_array_size]; public static long[] dp = new long[template_array_size]; public static long[] ans = new long[template_array_size]; public static int inf = Integer.MAX_VALUE; public static int minf = Integer.MIN_VALUE; public static int mod = 1000000007; public static int ml = (int) 1e9; public static String s = ""; public static InputReader sc; public static PrintWriter out; public static PrintWriter pr; // Pair static class Pair { int first, second; Pair(int x, int y) { this.first = x; this.second = y; } } // FastReader Class 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()); } } // Req Functions public static void fill(int[][] dp, int x) { for (int i = 0; i < dp.length; ++i) { for (int j = 0; j < dp[0].length; ++j) { dp[i][j] = x; } } } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } public static long nCr(int n, int k) { long ans = 1L; k = k > n - k ? n - k : k; int j = 1; for (; j <= k; j++, n--) { if (n % j == 0) { ans *= n / j; } else if (ans % j == 0) { ans = ans / j * n; } else { ans = (ans * n) / j; } } return ans; } public static String reverseString(String input) { StringBuilder str = new StringBuilder(""); for (int i = input.length() - 1; i >= 0; i--) { str.append(input.charAt(i)); } return str.toString(); } public static int maxOf3(int x, int y, int z) { return Math.max(x, Math.max(y, z)); } public static int minof3(int x, int y, int z) { return Math.min(x, Math.min(y, z)); } public static long maxOf3(long x, long y, long z) { return Math.max(x, Math.max(y, z)); } public static long minof3(long x, long y, long z) { return Math.min(x, Math.min(y, z)); } public static void arrInput(int[] arr, int n) { for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); } public static void arrInput(long[] arr, int n) { for (int i = 0; i < n; i++) arr[i] = sc.nextLong(); } public static void arrInput(Pair[] pair, int n) { for (int i = 0; i < n; i++) pair[i] = new Pair(sc.nextInt(), sc.nextInt()); } public static int maxarrInput(int[] arr, int n) { int max = minf; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); max = Math.max(max, arr[i]); } return max; } public static long maxarrInput(long[] arr, int n) { long max = minf; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); max = Math.max(max, arr[i]); } return max; } public static int minarrInput(int[] arr, int n) { int min = inf; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); min = Math.max(min, arr[i]); } return min; } public static long minarrInput(long[] arr, int n) { long min = inf; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); min = Math.max(min, arr[i]); } return min; } public static int lowerBound(int[] arr, int x) { int l = -1, r = arr.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (arr[m] >= x) r = m; else l = m; } return r; } public static int upperBound(int[] arr, int x) { int l = -1, r = arr.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (arr[m] <= x) l = m; else r = m; } return l + 1; } public static void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int[n1]; int R[] = new int[n2]; for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] >= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void reversesort(int arr[], int l, int r) { if (l < r) { int m = l + (r - l) / 2; reversesort(arr, l, m); reversesort(arr, m + 1, r); merge(arr, l, m, r); } } public static void merge(long arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; long L[] = new long[n1]; long R[] = new long[n2]; for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] >= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void reversesort(long arr[], int l, int r) { if (l < r) { int m = l + (r - l) / 2; reversesort(arr, l, m); reversesort(arr, m + 1, r); merge(arr, l, m, r); } } // debug public static boolean sysFlag = System.getProperty("ONLINE_JUDGE") == null; public static void debug(int[][] dp) { if (sysFlag) { for (int i = 0; i < dp.length; ++i) { pr.print(i + "--> "); for (int j = 0; j < dp[0].length; ++j) { pr.print(dp[i][j] + " "); } pr.println(""); } } } public static void debug(long[][] dp) { if (sysFlag) { for (int i = 0; i < dp.length; ++i) { pr.print(i + "--> "); for (int j = 0; j < dp[0].length; ++j) { pr.print(dp[i][j] + " "); } pr.println(""); } } } public static void debug(int x) { if (sysFlag) pr.println("Int-Ele: " + x); } public static void debug(String x) { if (sysFlag) pr.println("String: " + x); } public static void debug(char x) { if (sysFlag) pr.println("Char: " + x); } public static void debug(long x) { if (sysFlag) pr.println("Long-Ele: " + x); } public static void debug(int[] arr, int n) { if (sysFlag) { for (int i = 0; i < n; ++i) { pr.println(i + " -> " + arr[i]); } } } public static void debug(char[] arr) { if (sysFlag) { for (int i = 0; i < arr.length; ++i) { pr.println(i + " -> " + arr[i]); } } } public static void debug(long[] arr, int n) { if (sysFlag) { for (int i = 0; i < n; ++i) { pr.println(i + " -> " + arr[i]); } } } public static void debug(ArrayList<Integer> list) { if (sysFlag) { for (int i = 0; i < list.size(); ++i) { pr.println(i + " -> " + list.get(i)); } } } public static void Ldebug(ArrayList<Long> list) { if (sysFlag) { for (int i = 0; i < list.size(); ++i) { pr.println(i + " -> " + list.get(i)); } } } public static void debugmapII(HashMap<Integer, Integer> map) { if (sysFlag) { for (Map.Entry<Integer, Integer> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapLI(HashMap<Long, Integer> map) { if (sysFlag) { for (Map.Entry<Long, Integer> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapLL(HashMap<Long, Long> map) { if (sysFlag) { for (Map.Entry<Long, Long> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapIL(HashMap<Integer, Long> map) { if (sysFlag) { for (Map.Entry<Integer, Long> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapSL(HashMap<String, Long> map) { if (sysFlag) { for (Map.Entry<String, Long> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapCL(HashMap<Character, Long> map) { if (sysFlag) { for (Map.Entry<Character, Long> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapSI(HashMap<String, Integer> map) { if (sysFlag) { for (Map.Entry<String, Integer> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debugmapCI(HashMap<Character, Integer> map) { if (sysFlag) { for (Map.Entry<Character, Integer> entry : map.entrySet()) pr.println("Key => " + entry.getKey() + ", Value => " + entry.getValue()); } } public static void debug(Set<Integer> set) { if (sysFlag) { Iterator value = set.iterator(); int i = 1; while (value.hasNext()) { pr.println((i++) + "-> " + value.next()); } } } }
0
089b7f00
fb20d298
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main (String[] args) throws java.lang.Exception { Scanner scan=new Scanner(System.in); int t=scan.nextInt(); while(t>0){ int n=scan.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++){ a[i]=scan.nextInt(); } TreeSet<Integer>set=new TreeSet<>(); set.add(a[0]); boolean flag=false; for(int i=1;i<n;i++){ set.add(a[i]); //Collections.sort(list); if(a[i-1]==a[i]) { continue; } Integer find = set.lower(a[i]); if(find!=null && find==a[i-1]) { continue; } find = set.higher(a[i]); if(find!=null && find==a[i-1]) { continue; } //System.out.println(set+" "+x+" "+y); // if(x==y){ // continue; // } // if(x+1==y || x==y+1){ // continue; // } flag=true; break; } if(flag){ System.out.println("No"); }else{ System.out.println("Yes"); } t--; } } }
/* * Author:- Tanmay */ import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); // int t=1; int t=sc.nextInt(); // outer: while(t-- >0) { int n = sc.nextInt(); int b[] = sc.readArray(n); TreeSet<Integer> set = new TreeSet<>(); boolean f = true; set.add(b[0]); for(int i=1 ; i<n ; i++) { set.add(b[i]); if(b[i-1]==b[i]) { continue; } Integer find = set.lower(b[i]); if(find!=null && find==b[i-1]) { continue; } find = set.higher(b[i]); if(find!=null && find==b[i-1]) { continue; } f = false; break; } if(f == false) { out.println("NO"); } else out.println("YES"); } out.flush(); out.close(); } 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()); } long [] longArray(int n) { long[] a=new long[n]; for(int i=0 ; i<n ; i++) a[i]=nextLong(); return a; } double nextDouble() { return Double.parseDouble(next()); } } }
1