src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.util.*; import java.io.*; import java.math.*; public class loser { static class InputReader { public BufferedReader br; public StringTokenizer token; public InputReader(InputStream stream) { br=new BufferedReader(new InputStreamReader(stream),32768); token=null; } public String next() { while(token==null || !token.hasMoreTokens()) { try { token=new StringTokenizer(br.readLine()); } catch(IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } static class card{ int l; int r; public card(int ch,int i) { this.l=ch; this.r=i; } } static class sort implements Comparator<card> { public int compare(card o1,card o2) { if(o1.l!=o2.l) return (int)(o1.l-o2.l); else return (int)(o1.r-o2.r); } } static void shuffle(long a[]) { List<Long> l=new ArrayList<>(); for(int i=0;i<a.length;i++) l.add(a[i]); Collections.shuffle(l); for(int i=0;i<a.length;i++) a[i]=l.get(i); } /*static long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } static int ans1=Integer.MAX_VALUE,ans2=Integer.MAX_VALUE,ans3=Integer.MAX_VALUE,ans4=Integer.MAX_VALUE; static boolean v[]=new boolean[101]; static void dfs(Integer so,Set<Integer> s[]){ if(!v[so.intValue()]) { v[so]=true; for(Integer h:s[so.intValue()]) { if(!v[h.intValue()]) dfs(h,s); } } } static class Print{ public PrintWriter out; Print(OutputStream o) { out=new PrintWriter(o); } } static int CeilIndex(int A[], int l, int r, int key) { while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] >= key) r = m; else l = m; } return r; } static int LongestIncreasingSubsequenceLength(int A[], int size) { // Add boundary case, when array size is one int[] tailTable = new int[size]; int len; // always points empty slot tailTable[0] = A[0]; len = 1; for (int i = 1; i < size; i++) { if (A[i] < tailTable[0]) // new smallest value tailTable[0] = A[i]; else if (A[i] > tailTable[len - 1]) // A[i] wants to extend largest subsequence tailTable[len++] = A[i]; else // A[i] wants to be current end candidate of an existing // subsequence. It will replace ceil value in tailTable tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i]; } return len; }*/ /*static int binary(int n) { int s=1; while(n>0) { s=s<<1; n--; } return s-1; } static StringBuilder bin(int i,int n) { StringBuilder s=new StringBuilder(); while(i>0) { s.append(i%2); i=i/2; } while(s.length()!=n) { s.append(0); } return s.reverse(); }*/ static boolean valid(int i,int j,int n,int m) { if(i<n && i>=0 && j<m && j>=0) return true; else return false; } public static void main(String[] args) { InputReader sc=new InputReader(System.in); int n=sc.nextInt(); int s=sc.nextInt(); card c[]=new card[n]; for(int i=0;i<n;i++) { int x=sc.nextInt(); int y=sc.nextInt(); c[i]=new card(x,y); } Arrays.sort(c,new sort()); int time=0; for(int i=n-1;i>=0;i--) { time+=s-c[i].l; if((c[i].r-time)>0) time+=c[i].r-time; s=c[i].l; } if(c[0].l!=0) time+=c[0].l; System.out.println(time); } }
nlogn
608_A. Saitama Destroys Hotel
CODEFORCES
import java.util.*; import java.io.*; public class ASimpleTask { /************************ SOLUTION STARTS HERE ***********************/ static long memo[][]; static int graph[]; static long hamiltonianPath(int mask , int u) { if(memo[mask][u] != -1) return memo[mask][u]; else if(u == Integer.numberOfTrailingZeros(mask)) return 0; else { long sum = 0; for(int fromSet = mask ^ (1 << u);fromSet > 0; fromSet ^= Integer.lowestOneBit(fromSet)) { int v = Integer.numberOfTrailingZeros(fromSet); // System.out.printf("mask = %s , u = %d , v = %d\n" , Integer.toBinaryString(mask) , u , v); if((graph[u] & (1 << v)) != 0) sum += hamiltonianPath(mask ^ (1 << u), v); } return memo[mask][u] = sum; } } private static void solveBottomUp(FastScanner s1, PrintWriter out){ int V = s1.nextInt(); int E = s1.nextInt(); graph = new int[V]; long DP[][] = new long[1 << V][V]; while(E-->0) { int u = s1.nextInt() - 1; int v = s1.nextInt() - 1; graph[u] |= (1 << v); graph[v] |= (1 << u); } for(int i=0;i<V;i++) DP[1 << i][i] = 1; for(int mask = 1 , end = 1 << V;mask < end;mask++) { for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); for(int fromSet = mask ^ (1 << u);fromSet > 0; fromSet ^= Integer.lowestOneBit(fromSet)) { int v = Integer.numberOfTrailingZeros(fromSet); // System.out.printf("mask = %s , u = %d , v = %d\n" , Integer.toBinaryString(mask) , u , v); if((graph[u] & (1 << v)) != 0) DP[mask][u] += DP[mask ^ (1 << u)][v]; } } } long totalCycles = 0; for(int mask = 1 , end = 1 << V;mask < end;mask++) { if(Integer.bitCount(mask) >= 3) { int start = Integer.numberOfTrailingZeros(mask); for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); if((graph[u] & (1 << start)) != 0) totalCycles += DP[mask][u]; } } } totalCycles /= 2; /* for(long l[] : DP) out.println(Arrays.toString(l));*/ out.println(totalCycles); } private static void solveTopDown(FastScanner s1, PrintWriter out){ int V = s1.nextInt(); int E = s1.nextInt(); graph = new int[V]; memo = new long[1 << V][V]; for(long l[] : memo) Arrays.fill(l, -1); while(E-->0) { int u = s1.nextInt() - 1; int v = s1.nextInt() - 1; graph[u] |= (1 << v); graph[v] |= (1 << u); } for(int i=0;i<V;i++) memo[1 << i][i] = 1; long totalCycles = 0; for(int mask = 1 , end = 1 << V;mask < end;mask++) { if(Integer.bitCount(mask) >= 3) { int start = Integer.numberOfTrailingZeros(mask); for(int set = mask;Integer.bitCount(set) > 1;set ^= Integer.highestOneBit(set)) { int u = Integer.numberOfTrailingZeros(Integer.highestOneBit(set)); if((graph[u] & (1 << start)) != 0) totalCycles += hamiltonianPath(mask, u); } } } totalCycles /= 2; out.println(totalCycles); } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE *********************/ public static void main(String []args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); solveTopDown(in, out); in.close(); out.close(); } static class FastScanner{ BufferedReader reader; StringTokenizer st; FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;} String next() {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;} st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();} String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble(){return Double.parseDouble(next());} char nextChar() {return next().charAt(0);} int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;} long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;} int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;} long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;} void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}} } /************************ TEMPLATE ENDS HERE ************************/ }
np
11_D. A Simple Task
CODEFORCES
/*==========================================================================*/ /* * AUTHOR: RonWonWon * CREATED: 02.05.2021 19:58:57 * EMAIL: rachitpts.2454@gmail.com */ /*==========================================================================*/ import java.io.*; import java.util.*; public class B { public static void main(String[] args) { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(), tt = 0; while(t-->0) { int n = in.nextInt(); if(n%2!=0) out.println("NO"); else{ n/=2; if(Math.sqrt(n)==Math.ceil(Math.sqrt(n))) out.println("YES"); else{ if(n%2!=0) out.println("NO"); else{ n/=2; if(Math.sqrt(n)==Math.ceil(Math.sqrt(n))) out.println("YES"); else out.println("NO"); } } } //tt++; out.println("Case #"+tt+": "+ans); } out.flush(); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while(!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch(IOException e) {} return st.nextToken(); } String nextLine(){ try{ return br.readLine(); } catch(IOException e) { } return ""; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } } static final Random random = new Random(); static void ruffleSort(int[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n), temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.TreeSet; import java.util.StringTokenizer; import java.util.AbstractCollection; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Zyflair Griffane */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; PandaScanner in = new PandaScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); A solver = new A(); solver.solve(1, in, out); out.close(); } } class A { public void solve(int testNumber, PandaScanner in, PrintWriter out) { String s = in.next(); String[] ss = Substring.allSubstrings(s); int res = 0; for (String sss: ss) { if (sss.length() <= res) continue; if (Substring.occurences(s, sss).length > 1) { res = sss.length(); } } out.println(res); } } class PandaScanner { public BufferedReader br; public StringTokenizer st; public InputStream in; public PandaScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(this.in = in)); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { return null; } } public String next() { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine().trim()); return next(); } return st.nextToken(); } } class Substring { public static String[] allSubstrings(String s) { TreeSet<String> substrings = new TreeSet<String>(); int n = s.length(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { substrings.add(s.substring(i, j)); } } return substrings.toArray(new String[0]); } public static int[] occurences(String s, String target) { int n = s.length(); ArrayList<Integer> res = new ArrayList<Integer>(); int idx = s.indexOf(target); while (idx != -1) { res.add(idx); if (idx == n - 1) break; idx = s.indexOf(target, idx + 1); } n = res.size(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = res.get(i); } return arr; } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; public class C817{ void solve() { long n = nl(), s = nl(); long l = 0, r = n; while(l < r) { long mid = (l + r)/2; if(mid - digSum(mid) < s) l = mid + 1; else r = mid; } out.println(l - digSum(l) >= s ? (n - l + 1) : 0); } int digSum(long k) { int sum = 0; while(k != 0) { sum += k % 10; k /= 10; } return sum; } public static void main(String[] args){new C817().run();} private byte[] bufferArray = new byte[1024]; private int bufLength = 0; private int bufCurrent = 0; InputStream inputStream; PrintWriter out; public void run() { inputStream = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } int nextByte() { if(bufLength==-1) throw new InputMismatchException(); if(bufCurrent>=bufLength) { bufCurrent = 0; try {bufLength = inputStream.read(bufferArray);} catch(IOException e) { throw new InputMismatchException();} if(bufLength<=0) return -1; } return bufferArray[bufCurrent++]; } boolean isSpaceChar(int x) {return (x<33 || x>126);} boolean isDigit(int x) {return (x>='0' && x<='9');} int nextNonSpace() { int x; while((x=nextByte())!=-1 && isSpaceChar(x)); return x; } int ni() { long ans = nl(); if ( Integer.MIN_VALUE <= ans && ans <= Integer.MAX_VALUE ) return (int)ans; throw new InputMismatchException(); } long nl() { long ans = 0; boolean neg = false; int x = nextNonSpace(); if(x=='-') { neg = true; x = nextByte(); } while(!isSpaceChar(x)) { if(isDigit(x)) { ans = ans*10 + x -'0'; x = nextByte(); } else throw new InputMismatchException(); } return neg ? -ans:ans; } String ns() { StringBuilder sb = new StringBuilder(); int x = nextNonSpace(); while(!isSpaceChar(x)) { sb.append((char)x); x = nextByte(); } return sb.toString(); } char nc() { return (char)nextNonSpace();} double nd() { return (double)Double.parseDouble(ns()); } char[] ca() { return ns().toCharArray();} char[] ca(int n) { char[] ans = new char[n]; int p =0; int x = nextNonSpace(); while(p<n) { ans[p++] = (char)x; x = nextByte(); } return ans; } int[] ia(int n) { int[] ans = new int[n]; for(int i=0;i<n;i++) ans[i]=ni(); return ans; } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.*; import java.util.*; public class A { String fileName = "<name>"; public TreeSet<Integer> set = new TreeSet<>(); public int getLowerDist(int x) { Integer higher = set.higher(x); Integer lower = set.lower(x); if (higher == null) return lower; if (lower == null) return higher; if (Math.abs(x - higher) < Math.abs(x - lower)) { return higher; } else { return lower; } } public void solve() throws IOException { int n = nextInt(); int d = nextInt(); int[] a = new int[n]; Set<Integer> ans = new HashSet<>((int) 1e6, 1f); for (int i = 0; i < n; i++) { a[i] = nextInt(); set.add(a[i]); } for (int i = 0; i < n; i++) { int pos1 = a[i] + d; int pos2 = a[i] - d; if (!set.contains(pos1) && Math.abs(pos1 - getLowerDist(pos1)) == d) { ans.add(pos1); } if (!set.contains(pos2) && Math.abs(pos2 - getLowerDist(pos2)) == d) { ans.add(pos2); } } out.print(ans.size()); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new A().run(); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] P = new int[n]; int[] check=new int[n]; for (int i = 1; i < n; i++) { P[i] = scanner.nextInt(); P[i]--; check[P[i]]++; } int[] leaves = new int[n]; for (int i=0;i<n;i++) { if(check[i]==0){ leaves[P[i]]++; } } for (int i = 0; i < n; i++) { if (check[i]>0&&leaves[i]<3) { System.out.println("No"); return; } } System.out.println("Yes"); } }
linear
913_B. Christmas Spruce
CODEFORCES
import javax.swing.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.StringTokenizer; public class A { public static void main(String[] args) { FastScanner scanner = new FastScanner(); long x = scanner.nextLong(); long k = scanner.nextLong(); if (x==0) { System.out.println("0"); return; } BigInteger M = BigInteger.valueOf(1000_000_000L+7); BigInteger modus = BigInteger.valueOf(x).multiply(BigInteger.valueOf(2)).subtract(BigInteger.ONE).mod(M); BigInteger operandi = BigInteger.valueOf(2).modPow(BigInteger.valueOf(k), M); BigInteger result = modus.multiply(operandi).mod(M).add(BigInteger.ONE).mod(M); System.out.println(result); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static long lcm(long a, long b, long gcd) { return a * (b / gcd); } public 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; } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class FireAgain { static int dx[] = { 0, 0, 1, -1 }; static int dy[] = { 1, -1, 0, 0 }; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new File("input.txt")); BufferedWriter write = new BufferedWriter(new FileWriter("output.txt")); int n = sc.nextInt(); int m = sc.nextInt(); boolean[][] v = new boolean[n][m]; int k = sc.nextInt(); Queue<Integer> q = new LinkedList<Integer>(); for (int i = 0; i < k; i++) { int x = sc.nextInt() - 1; int y = sc.nextInt() - 1; q.add(x); q.add(y); v[x][y] = true; } int lastx = 0; int lasty = 0; while (!q.isEmpty()) { lastx = q.poll(); lasty = q.poll(); for (int i = 0; i < 4; i++) { int r = lastx + dx[i]; int c = lasty + dy[i]; if (r >= 0 && c >= 0 && r < n && c < m && !v[r][c]) { v[r][c] = true; q.add(r); q.add(c); } } } write.write((lastx + 1) + " " + (lasty + 1)); write.close(); } }
cubic
35_C. Fire Again
CODEFORCES
import static java.util.Arrays.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import java.util.*; import java.math.*; import java.io.*; public class C implements Runnable { String file = "input"; boolean TEST = false; void solve() throws IOException { rows = nextInt(); cols = nextInt(); if(cols > rows) { int t = rows; rows = cols; cols = t; } dp = new int[rows][cols][1 << cols][1 << cols][1 << cols]; for(int i = 0; i < rows; i++) for(int j = 0; j < cols; j++) for(int k = 0; k < 1 << cols; k++) for(int u = 0; u < 1 << cols; u++) for(int v = 0; v < 1 << cols; v++) dp[i][j][k][u][v] = -1; out.println(go(0, 0, 0, 0, 0)); } int rows, cols; int[][][][][] dp; int INF = 1 << 20; int go(int i, int j, int a, int b, int c) { if(i == rows) { return a == 0 && b == 0 && c == 0 ? 0 : -INF; } if(i + 1 == rows && b != 0 && c != 0) return -INF; if(i + 2 == rows && c != 0) return -INF; if(j == cols) { return go(i + 1, 0, b, c, 0); } if(dp[i][j][a][b][c] != -1) return dp[i][j][a][b][c]; if(!test(a, j, -1, -1)) return go(i, j + 1, a, b, c); int res = -INF; //1 if(test(a, j, -1, -1)) res = max(res, go(i, j + 1, set(a, j, -1, -1), b, c)); //2 if(test(a, j, -1, -1) && test(b, j, -1, -1)) res = max(res, go(i, j + 1, set(a, j, -1, -1), set(b, j, -1, -1), c) + 1); //3 if(j + 2 <= cols && test(a, j, j + 1, -1)) res = max(res, go(i, j + 2, set(a, j, j + 1, -1), b, c) + 1); //4 if(j + 3 <= cols && test(a, j, j + 1, j + 2)) res = max(res, go(i, j + 2, set(a, j, j + 1, j + 2), b, c) + 2); //5 if(test(a, j, -1, -1) && test(b, j, -1, -1) && test(c, j, -1, -1)) res = max(res, go(i, j + 1, set(a, j, -1, -1), set(b, j, -1, -1), set(c, j, -1, -1)) + 2); //6 if(j - 1 >= 0 && test(a, j, -1, -1) && test(b, j - 1, j, -1) && test(c, j, -1, -1)) res = max(res, go(i, j + 1, set(a, j, -1, -1), set(b, j - 1, j, -1), set(c, j, -1, -1)) + 3); //7 if(j + 2 <= cols && test(a, j, -1, -1) && test(b, j, j + 1, -1) && test(c, j, -1, -1)) res = max(res, go(i, j + 1, set(a, j, -1, -1), set(b, j, j + 1, -1), set(c, j, -1, -1)) + 3); //8 if(j + 3 <= cols && test(a, j, j + 1, j + 2) && test(b, j + 1, -1, -1)) res = max(res, go(i, j + 3, set(a, j, j + 1, j + 2), set(b, j + 1, -1, -1), c) + 3); //9 if(j + 2 <= cols && j - 1 >= 0 && test(b, j - 1, j, j + 1)) res = max(res, go(i, j + 1, set(a, j, -1, -1), set(b, j - 1, j, j + 1), c) + 3); //10 if(j + 2 <= cols && j - 1 >= 0 && test(b, j - 1, j, j + 1) && test(c, j, -1, -1)) res = max(res, go(i, j + 1, set(a, j, -1, -1), set(b, j - 1, j, j + 1), set(c, j, -1, -1)) + 4); //11 if(j + 2 <= cols && test(b, j, j + 1, -1)) res = max(res, go(i, j + 1, set(a, j, -1, -1), set(b, j, j + 1, -1), c) + 2); //12 if(j - 1 >= 0 && test(b, j - 1, j, -1)) res = max(res, go(i, j + 1, set(a, j, -1, -1), set(b, j - 1, j, -1), c) + 2); //13 if(j + 2 <= cols && test(a, j, j + 1, -1) && test(b, j, -1, -1)) res = max(res, go(i, j + 2, set(a, j, j + 1, -1), set(b, j, -1, -1), c) + 2); //14 if(j + 2 <= cols && test(a, j, j + 1, -1) && test(b, j + 1, -1, -1)) res = max(res, go(i, j + 2, set(a, j, j + 1, -1), set(b, j + 1, -1, -1), c) + 2); return dp[i][j][a][b][c] = res; } int set(int a, int i, int j, int k) { if(i != -1) a |= 1 << i; if(j != -1) a |= 1 << j; if(k != -1) a |= 1 << k; return a; } boolean test(int a, int i, int j, int k) { if(i != -1 && (a >> i & 1) != 0) return false; if(j != -1 && (a >> j & 1) != 0) return false; if(k != -1 && (a >> k & 1) != 0) return false; return true; } String next() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(input.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } void print(Object... o) { System.out.println(deepToString(o)); } void gcj(Object o) { String s = String.valueOf(o); out.println("Case #" + test + ": " + s); System.out.println("Case #" + test + ": " + s); } BufferedReader input; PrintWriter out; StringTokenizer st; int test; void init() throws IOException { if(TEST) input = new BufferedReader(new FileReader(file + ".in")); else input = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedOutputStream(System.out)); } public static void main(String[] args) throws IOException { new Thread(null, new C(), "", 1 << 20).start(); } public void run() { try { init(); if(TEST) { int runs = nextInt(); for(int i = 0; i < runs; i++) solve(); } else solve(); out.close(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }
np
111_C. Petya and Spiders
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.*; public class Main { static int N; static int [][] dp; static int M = (int)(1e9 + 7); static ArrayList<Integer> l; static int f(int idx, int b) { if(idx == l.size()) return 1; if(dp[idx][b] != -1) return dp[idx][b]; long ret = f(idx + 1, b + l.get(idx)); if(b > 0) ret += f(idx, b - 1); return dp[idx][b] = (int) (ret % M); } public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(); N = sc.nextInt(); int [] val = new int[N]; for(int i = 0; i < N; ++i) if(sc.next().charAt(0) == 's') val[i] = 0; else val[i] = 1; l = new ArrayList<Integer>(); l.add(val[0]); for(int i = 1; i < N; ++i) if(val[i] == val[i - 1] && val[i] == 1) { int prev = l.get(l.size() - 1); l.set(l.size() - 1, ++prev); } else if(val[i - 1] == 0){ l.add(val[i]); } // System.out.println(l); dp = new int[l.size() + 1][N + 1]; for(int i = 0; i <= l.size(); ++i) Arrays.fill(dp[i], -1); System.out.println(f(0, 0)); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class RationalResistance { public static void main(String args[]) throws IOException{ BufferedReader f= new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st=new StringTokenizer(f.readLine()); long a=Long.parseLong(st.nextToken()); long b=Long.parseLong(st.nextToken()); long sum = 0; while(a!= 0 && b!= 0){ if (a > b){ long val = a / b; sum += val; a -= val * b; } else{ long val = b / a; sum += val; b -= val * a; } } out.println(sum); out.close(); System.exit(0); } }
constant
343_A. Rational Resistance
CODEFORCES
import java.math.BigInteger; import java.util.*; public class A { private static Scanner in; final int M = 1000000009; public void run() { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int z = n - m; if (z >= n / k) { System.out.println(m); return; } int f = n - k * z; int last = f % k + (k - 1) * z; f /= k; int ans = BigInteger.ONE.shiftLeft(f + 1).remainder(BigInteger.valueOf(M)).intValue(); System.out.println(((ans + M - 2L) * k + last) % M); } public static void main(String[] args) { Locale.setDefault(Locale.US); in = new Scanner(System.in); new A().run(); in.close(); } }
logn
338_A. Quiz
CODEFORCES
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long itrIdx = 0; long itr = 0; long num = 0; while(itrIdx < n){ itrIdx += (itr+1)*(Math.pow(10,itr+1) - Math.pow(10,itr)); num+= (Math.pow(10,itr+1) - Math.pow(10,itr)); itr++; } itrIdx -= itr*(Math.pow(10,itr)-Math.pow(10,itr-1)); num -= (Math.pow(10,itr)-Math.pow(10,itr-1)); long lastNum = num + ((n-itrIdx)/itr); long lastNumIndex = itrIdx + (itr* (lastNum-num)); if(lastNumIndex == n){ lastNumIndex = lastNumIndex-itr; lastNum -=1; } String nextNum = String.valueOf(lastNum+=1); System.out.println(nextNum.charAt((int) (n-lastNumIndex-1))); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class AAA { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); String a=""; String b=""; for(int i=0;i<1129;i++) { a+="1"; b+="8"; } a+="9"; b+="1"; System.out.println(a); System.out.println(b); } }
constant
1028_B. Unnatural Conditions
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Contest { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Contest().run(); } void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } public void run() { try { long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time(ms) = " + (t2 - t1)); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } class MyComparator implements Comparable<MyComparator> { int x; int y; public MyComparator(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(MyComparator a) { if (x == a.x) { return (y - a.y); } return x - a.x; } } public static boolean isPrime(int num) { if (num > 2 && num % 2 == 0) { //System.out.println(num + " is not prime"); return false; } int top = (int) Math.sqrt(num) + 1; for (int i = 3; i < top; i += 2) { if (num % i == 0) { //System.out.println(num + " is not prime"); return false; } } //System.out.println(num + " is prime"); return true; } private static int lowerBound(int[] a, int low, int high, int element) { while (low < high) { int middle = low + (high - low) / 2; if (element > a[middle]) { low = middle + 1; } else { high = middle; } } return low; } private static int upperBound(int[] a, int low, int high, int element) { while (low < high) { int middle = low + (high - low) / 2; if (a[middle] > element) { high = middle; } else { low = middle + 1; } } return low; } public void solve() throws IOException { int num_a = readInt(); int[] array = new int[num_a]; for (int i = 0; i < num_a; i++) { array[i] = readInt(); } int result = 0; Arrays.sort(array); for (int i = 0; i < array.length; i++) { if (array[i] == -1) { continue; } for (int j = 0; j < array.length; j++) { if (array[j] != -1 && array[j] % array[i] == 0 && j != i) { //System.out.println(array[j]); array[j] = -1; //result++; } } result++; } System.out.println(result); } /** * * @param a * @param b * @return */ private BigInteger lcm(BigInteger a, BigInteger b) { return a.multiply(b.divide(a.gcd(b))); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws InterruptedException{ FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); long n = scan.nextLong(), s = scan.nextLong(); long lo = 1, hi = n+1; for(int bs = 0; bs < 100; bs++) { long mid = (lo+hi)>>1; long mid2 = mid; long c = 0; while(mid > 0) { c += mid%10; mid /= 10; } if(mid2-c < s) lo = mid2; else hi = mid2; } out.println(n-lo); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n){ long[] a = new long[n]; for(int i = 0; i < n; i++) a[i] = nextLong(); return a; } public double[] nextDoubleArray(int n){ double[] a = new double[n]; for(int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char[][] nextGrid(int n, int m){ char[][] grid = new char[n][m]; for(int i = 0; i < n; i++) grid[i] = next().toCharArray(); return grid; } } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.BufferedReader; 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.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.StringTokenizer; public class P { static int N, M, K; static int dx[] = { 0, 0, 1, -1, 1, 1, -1, -1 }; static int dy[] = { 1, -1, 0, 0, 1, -1, 1, -1 }; static Pair[] b; static boolean isValid(int x, int y) { return x >= 0 && y >= 0 && x < N && y < M; } static class Pair { int x, y; Pair(int i, int j) { x = i; y = j; } } static Pair bfs() { Queue<Pair> q = new LinkedList<Pair>(); int[][] dist = new int[N][M]; for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) dist[i][j] = -1; for (int i = 0; i < K; i++) { dist[b[i].x][b[i].y] = 0; q.add(b[i]); } while (!q.isEmpty()) { Pair cur = q.remove(); for (int d = 0; d < 4; d++) { int X = cur.x + dx[d]; int Y = cur.y + dy[d]; if (isValid(X, Y) && dist[X][Y] == -1) { dist[X][Y] = dist[cur.x][cur.y] + 1; Pair P = new Pair(X, Y); q.add(P); } } } int max = -1; Pair MX = null; for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { if (dist[i][j] > max) { max = dist[i][j]; MX = new Pair(i + 1, j + 1); } } return MX; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner("input.txt"); PrintWriter out = new PrintWriter("output.txt"); // Scanner sc = new Scanner(System.in); // PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); M = sc.nextInt(); K = sc.nextInt(); b = new Pair[K]; for (int i = 0; i < K; i++) b[i] = new Pair(sc.nextInt() - 1, sc.nextInt() - 1); Pair last = bfs(); out.println((last.x) + " " + (last.y)); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String f) throws FileNotFoundException { br = new BufferedReader(new FileReader(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 String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } 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 int[] nextIntArray1(int n) throws IOException { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } public int[] nextIntArraySorted(int n) throws IOException { int[] a = nextIntArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); int t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); 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 long[] nextLongArray1(int n) throws IOException { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } public long[] nextLongArraySorted(int n) throws IOException { long[] a = nextLongArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); long t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class ProblemA_23 { final boolean ONLINE_JUDGE=System.getProperty("ONLINE_JUDGE")!=null; BufferedReader in; PrintWriter out; StringTokenizer tok=new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in=new BufferedReader(new InputStreamReader(System.in)); out =new PrintWriter(System.out); } else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ tok=new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } public static void main(String[] args){ new ProblemA_23().run(); } public void run(){ try{ long t1=System.currentTimeMillis(); init(); solve(); out.close(); long t2=System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } void solve() throws IOException{ String s = readString(); for (int length = s.length() - 1; length > 0; length--){ for (int i = 0; i < s.length() - length; i++){ if (s.lastIndexOf(s.substring(i, i + length)) > i){ out.print(length); return; } } } out.print(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.lang.*; import java.io.*; import java.util.*; import java.math.*; public class A implements Runnable{ public void run() { int n = nextInt(); int[] arr = new int[n]; boolean allOne = true; for (int i = 0; i < n; ++i) { arr[i] = nextInt(); if (arr[i] != 1) { allOne = false; } } Arrays.sort(arr); if (!allOne) { out.print("1 "); } for (int i = 0; i < n-1; ++i) { out.print(arr[i] + " "); } if (allOne) { out.print("2"); } out.println(); out.flush(); } private static BufferedReader br = null; private static PrintWriter out = null; private static StringTokenizer stk = null; public static void main(String[] args) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); (new Thread(new A())).start(); } private void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } private String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } private Integer nextInt() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Integer.parseInt(stk.nextToken()); } private Long nextLong() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Long.parseLong(stk.nextToken()); } private String nextWord() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return (stk.nextToken()); } private Double nextDouble() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Double.parseDouble(stk.nextToken()); } }
nlogn
135_A. Replacement
CODEFORCES
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.Scanner; /** * * @author RezaM */ public class A { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); if (n % 2 == 0) { System.out.println(4 + " " + (n - 4)); } else { System.out.println(9 + " " + (n - 9)); } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.StringJoiner; import java.util.StringTokenizer; import java.util.function.Function; public class Main { static String S; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); S = sc.next(); System.out.println(solve()); } static int solve() { int ans = -1; int time = 1; int n = S.length(); for (int i = 1; i < n*2; i++) { if( S.charAt((i-1)%n) != S.charAt(i%n) ) { time++; } else { ans = Math.max(time, ans); time = 1; } } ans = Math.max(time, ans); if( ans == n*2 ) { return n; } else { return ans; } } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static <A> void writeLines(A[] as, Function<A, String> f) { PrintWriter pw = new PrintWriter(System.out); for (A a : as) { pw.println(f.apply(a)); } pw.flush(); } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } }
linear
1025_C. Plasticine zebra
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class C { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = null; private void solution() throws IOException { int n = nextInt(); int[] mas = new int[n]; for (int i = 0; i < n; i++) { mas[i] = nextInt(); } Arrays.sort(mas); if (mas[n - 1] == 1) { mas[n - 1] = 2; } else { mas[n - 1] = 1; } Arrays.sort(mas); for (int i = 0; i < n; i++) { System.out.print(mas[i] + " "); } } String nextToken() throws IOException { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(bf.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public static void main(String args[]) throws IOException { new C().solution(); } }
nlogn
135_A. Replacement
CODEFORCES
/** * Created with IntelliJ IDEA. * User: brzezinsky * Date: 12/16/12 * Time: 7:44 PM * To change this template use File | Settings | File Templates. */ import java.io.*; import java.util.*; import java.util.StringTokenizer; public class E extends Thread { public E(String inputFileName, String outputFileName) { try { if (inputFileName != null) { this.input = new BufferedReader(new FileReader(inputFileName)); } else { this.input = new BufferedReader(new InputStreamReader(System.in)); } if (outputFileName != null) { this.output = new PrintWriter(outputFileName); } else { this.output = new PrintWriter(System.out); } this.setPriority(Thread.MAX_PRIORITY); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } } private void solve() throws Throwable { long l = nextLong(), r = nextLong(); output.println(Math.max(Long.highestOneBit(l ^ r) * 2 - 1, 0L)); } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.close(); } } public static void main(String... args) { new E(null, null).start(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } private double nextDouble() throws IOException { return Double.parseDouble(next()); } private long nextLong() throws IOException { return Long.parseLong(next()); } private String next() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private StringTokenizer tokens; private BufferedReader input; private PrintWriter output; }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc =new Scanner(System.in); long n = sc.nextLong(), k = sc.nextLong(); long ans = 0, sum = 0; while(ans < n) { if(sum - (n-ans) == k) break; ans++; sum += ans; } sc.close(); System.out.println(n-ans); } }
logn
1195_B. Sport Mafia
CODEFORCES
//q4 import java.io.*; import java.util.*; import java.math.*; public class q4 { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); int query = in.nextInt(); while (query -- > 0) { int n = in.nextInt(); int k = in.nextInt(); char[] arr = new char[n]; //slot all n into char array String code = in.next(); for (int i = 0; i < n; i++) { arr[i] = code.charAt(i); } //R, G, B cycle int r = 0; int g = 0; int b = 0; for (int i = 0; i < k; i++) { if (i % 3 == 0) { if (arr[i] == 'R') {g++; b++;} else if (arr[i] == 'G') {r++; b++;} else {r++; g++;} //if is 'B' } else if (i % 3 == 1) { if (arr[i] == 'G') {g++; b++;} else if (arr[i] == 'B') {r++; b++;} else {r++; g++;} //if is 'R' } else { //if mod 3 is 2 if (arr[i] == 'B') {g++; b++;} else if (arr[i] == 'R') {r++; b++;} else {r++; g++;} //if is 'G' } } //starting from kth position, if different then add 1, and check (j-k)th position int rMin = r; int gMin = g; int bMin = b; for (int j = k; j < n; j++) { //R cycle if ((j % 3 == 0 && arr[j] != 'R') || (j % 3 == 1 && arr[j] != 'G') || (j % 3 == 2 && arr[j] != 'B')) { r++; } //R cycle if (((j - k) % 3 == 0 && arr[j - k] != 'R') || ((j - k) % 3 == 1 && arr[j - k] != 'G') || ((j - k) % 3 == 2 && arr[j - k] != 'B')) { r--; } rMin = Math.min(r, rMin); //G cycle if ((j % 3 == 0 && arr[j] != 'G') || (j % 3 == 1 && arr[j] != 'B') || (j % 3 == 2 && arr[j] != 'R')) { g++; } if (((j - k) % 3 == 0 && arr[j - k] != 'G') || ((j - k) % 3 == 1 && arr[j - k] != 'B') || ((j - k) % 3 == 2 && arr[j - k] != 'R')) { g--; } gMin = Math.min(gMin, g); //B cycle if ((j % 3 == 0 && arr[j] != 'B') || (j % 3 == 1 && arr[j] != 'R') || (j % 3 == 2 && arr[j] != 'G')) { b++; } if (((j - k) % 3 == 0 && arr[j - k] != 'B') || ((j - k) % 3 == 1 && arr[j - k] != 'R') || ((j - k) % 3 == 2 && arr[j - k] != 'G')) { b--; } bMin = Math.min(bMin, b); } out.println(Math.min(Math.min(rMin, gMin), bMin)); } out.flush(); } }
quadratic
1196_D2. RGB Substring (hard version)
CODEFORCES
import java.util.*; public class Solution { public void doMain() throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(); boolean[][] adj = new boolean[n][n]; for (int i=0; i<m; i++) { int a = sc.nextInt()-1, b = sc.nextInt()-1; adj[a][b] = adj[b][a] = true; } long res = 0; for (int st=0; st+1<n; st++) { //System.out.println("st="+st); long[][] numWays = new long[1<<(n-st-1)][n-st-1]; for (int i=st+1; i<n; i++) if (adj[st][i]) numWays[1<<(i-st-1)][i-st-1] = 1; for (int mask=1; mask < (1<<(n-st-1)); mask++) { boolean simple = ((mask & (mask-1)) == 0); for (int last=0; last<n-st-1; last++) if (numWays[mask][last]!=0) { if (adj[last+st+1][st] && !simple) res += numWays[mask][last]; for (int next=0; next<n-st-1; next++) if (adj[last+st+1][next+st+1] && (mask & (1<<next)) == 0) numWays[mask | (1<<next)][next] += numWays[mask][last]; } } } System.out.println(res/2); } public static void main(String[] args) throws Exception { (new Solution()).doMain(); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author anand.oza */ 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); E1RotateColumnsEasyVersion solver = new E1RotateColumnsEasyVersion(); solver.solve(1, in, out); out.close(); } static class E1RotateColumnsEasyVersion { public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); for (int i = 0; i < t; i++) { solve(in, out); } } private void solve(InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); int[][] a = new int[n][]; for (int i = 0; i < n; i++) { a[i] = in.readIntArray(m); } out.println(solve(n, m, a)); } private int solve(int n, int m, int[][] a) { Cell[] cells = new Cell[n * m]; for (int i = 0, index = 0; i < n; i++) { for (int j = 0; j < m; j++) { cells[index++] = new Cell(i, j, a[i][j]); if (index == cells.length) break; } } Arrays.sort(cells, Comparator.comparingInt(cell -> -cell.x)); HashSet<Integer> colset = new HashSet<>(); for (int i = 0; colset.size() < n && colset.size() < m; i++) { colset.add(cells[i].j); } ArrayList<Integer> cols = new ArrayList<>(); cols.addAll(colset); int answer = 0; for (long perm = 0; perm < pow(n, cols.size() - 1); perm++) { long p = perm; int[] offset = new int[cols.size()]; for (int col = 0; col < cols.size(); col++) { offset[col] = (int) (p % n); p /= n; } int sum = 0; for (int row = 0; row < n; row++) { int max = 0; for (int col = 0; col < cols.size(); col++) { int cur = a[(row + offset[col]) % n][cols.get(col)]; max = Math.max(max, cur); } sum += max; } answer = Math.max(answer, sum); } return answer; } private long pow(int base, int exponent) { long p = 1; for (int i = 0; i < exponent; i++) { p *= base; } return p; } private class Cell { final int i; final int j; final int x; private Cell(int i, int j, int x) { this.i = i; this.j = j; this.x = x; } } } 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 int[] readIntArray(int n) { int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = nextInt(); } return x; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; public class Main { public static void main(String[] args) throws Exception { int n = nextInt(); int[] mas = new int[n]; for(int i = 0; i<n; i++) { mas[i] = nextInt(); } Arrays.sort(mas); if(mas[n-1] == 1) { for(int i = 0; i<n-1; i++) { out.print(1 + " "); } out.println(2); out.flush(); exit(); } out.print("1 "); for(int i = 0; i<n-1; i++) { out.print(mas[i] + " "); } out.println(); out.flush(); } ///////////////////////////////////////////////////////////////// // IO ///////////////////////////////////////////////////////////////// private static StreamTokenizer in; private static PrintWriter out; private static BufferedReader inB; private static boolean FILE=false; private static int nextInt() throws Exception{ in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception{ in.nextToken(); return in.sval; } static{ try { out = new PrintWriter(FILE ? (new FileOutputStream("output.txt")) : System.out); inB = new BufferedReader(new InputStreamReader(FILE ? new FileInputStream("input.txt") : System.in)); } catch(Exception e) {e.printStackTrace();} in = new StreamTokenizer(inB); } ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// // pre - written ///////////////////////////////////////////////////////////////// private static void println(Object o) throws Exception { out.println(o); out.flush(); } private static void exit(Object o) throws Exception { println(o); exit(); } private static void exit() { System.exit(0); } private static final int INF = Integer.MAX_VALUE; private static final int MINF = Integer.MIN_VALUE; ////////////////////////////////////////////////////////////////// }
nlogn
135_A. Replacement
CODEFORCES
import java.util.Scanner; public class dwl { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] lr = sc.nextLine().split(" "); long l = Long.valueOf(lr[0]); long r = Long.valueOf(lr[1]); if (r - l <= 1 || (l == 1 && (r - l) == 2) || (l % 2 != 0 && (r - l) < 3)) System.out.println(-1); else { if (l == 1) System.out.println(2 + " " + 3 + " " + 4); else { if (l % 2 == 0) { String res = ""; res += l + " "; res += (l + 1) + " "; res += (l + 2) + " "; res = res.trim(); System.out.println(res); } else { String res = ""; res += (l + 1) + " "; res += (l + 2) + " "; res += (l + 3) + " "; res = res.trim(); System.out.println(res); } } } } }
constant
483_A. Counterexample
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; public class ProblemA { public static void main(String[] args) throws Exception{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); int n = Integer.parseInt(reader.readLine()); String [] split = reader.readLine().split("\\s+"); int value; int [] count = new int[2]; int [] pos = new int[2]; for(int i = 0; i < split.length; i++){ value = Integer.parseInt(split[i]); count[value % 2] ++; pos[value % 2] = i + 1; } writer.println((count[0] == 1) ? pos[0] : pos[1]); writer.flush(); writer.close(); } }
linear
25_A. IQ test
CODEFORCES
import java.util.*; import java.io.*; public class C994{ static double area(double x1,double y1,double x2,double y2,double x3,double y3){ return Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } public static void main(String args[])throws IOException{ Scanner sc=new Scanner(new BufferedReader(new InputStreamReader(System.in))); PrintWriter pw=new PrintWriter(System.out); int x11=sc.nextInt(); int y11=sc.nextInt(); int x12=sc.nextInt(); int y12=sc.nextInt(); int x13=sc.nextInt(); int y13=sc.nextInt(); int x14=sc.nextInt(); int y14=sc.nextInt(); double x1c=(x11+x12+x13+x14)/4.0; double y1c=(y11+y12+y13+y14)/4.0; int x21=sc.nextInt(); int y21=sc.nextInt(); int x22=sc.nextInt(); int y22=sc.nextInt(); int x23=sc.nextInt(); int y23=sc.nextInt(); int x24=sc.nextInt(); int y24=sc.nextInt(); double x2c=(x21+x22+x23+x24)/4.0; double y2c=(y21+y22+y23+y24)/4.0; double a1=area(x11,y11,x12,y12,x13,y13)+area(x11,y11,x13,y13,x14,y14); double a2=area(x21,y21,x22,y22,x23,y23)+area(x21,y21,x23,y23,x24,y24); if(a1==area(x11,y11,x12,y12,x21,y21)+area(x11,y11,x21,y21,x14,y14)+area(x21,y21,x12,y12,x13,y13)+area(x21,y21,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a1==area(x11,y11,x12,y12,x22,y22)+area(x11,y11,x22,y22,x14,y14)+area(x22,y22,x12,y12,x13,y13)+area(x22,y22,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a1==area(x11,y11,x12,y12,x23,y23)+area(x11,y11,x23,y23,x14,y14)+area(x23,y23,x12,y12,x13,y13)+area(x23,y23,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a1==area(x11,y11,x12,y12,x24,y24)+area(x11,y11,x24,y24,x14,y14)+area(x24,y24,x12,y12,x13,y13)+area(x24,y24,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a1==area(x11,y11,x12,y12,x2c,y2c)+area(x11,y11,x2c,y2c,x14,y14)+area(x2c,y2c,x12,y12,x13,y13)+area(x2c,y2c,x14,y14,x13,y13)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x11,y11)+area(x21,y21,x11,y11,x24,y24)+area(x11,y11,x22,y22,x23,y23)+area(x11,y11,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x12,y12)+area(x21,y21,x12,y12,x24,y24)+area(x12,y12,x22,y22,x23,y23)+area(x12,y12,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x13,y13)+area(x21,y21,x13,y13,x24,y24)+area(x13,y13,x22,y22,x23,y23)+area(x13,y13,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x14,y14)+area(x21,y21,x14,y14,x24,y24)+area(x14,y14,x22,y22,x23,y23)+area(x14,y14,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } if(a2==area(x21,y21,x22,y22,x1c,y1c)+area(x21,y21,x14,y14,x2c,y2c)+area(x1c,y1c,x22,y22,x23,y23)+area(x1c,y1c,x24,y24,x23,y23)){ pw.println("YES"); pw.close(); return; } pw.println("NO"); pw.close(); } }
constant
994_C. Two Squares
CODEFORCES
import javax.sound.sampled.Line; import java.awt.Point; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.io.*; import java.math.BigInteger; import static java.math.BigInteger.*; import java.util.*; public class A{ void solve()throws Exception { int n=nextInt(); int[]a=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); Arrays.sort(a); int[]res=new int[n]; for(int i=0;i<n;i++) { if(i==0) res[i]=1; else res[i]=a[i-1]; } if(a[n-1]==1) res[n-1]=2; for(int i=0;i<n;i++) { if(i==n-1) writer.println(res[i]); else writer.print(res[i]+" "); } } //////////// BufferedReader reader; PrintWriter writer; StringTokenizer stk; void run()throws Exception { reader=new BufferedReader(new InputStreamReader(System.in)); stk=null; writer=new PrintWriter(new PrintWriter(System.out)); solve(); reader.close(); writer.close(); } int nextInt()throws Exception { return Integer.parseInt(nextToken()); } long nextLong()throws Exception { return Long.parseLong(nextToken()); } double nextDouble()throws Exception { return Double.parseDouble(nextToken()); } String nextString()throws Exception { return nextToken(); } String nextLine()throws Exception { return reader.readLine(); } String nextToken()throws Exception { if(stk==null || !stk.hasMoreTokens()) { stk=new StringTokenizer(nextLine()); return nextToken(); } return stk.nextToken(); } public static void main(String[]args) throws Exception { new A().run(); } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.util.*; public class ed817Q3 { public static void main(String[] args){ InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t = 1; for(int zxz=0;zxz<t;zxz++){ // my code starts here long n = in.nextLong(); long s = in.nextLong(); long start=s,end=n; long ans=n+1; while(start<=end){ long mid = start+(end-start)/2; if(mid-digitSum(mid)>=s){ ans = mid; end = mid-1; } else{ start=mid+1; } } System.out.println(n-ans+1); // my code ends here } } static int digitSum(long n){ int sum=0; while(n>0){ sum+=n%10; n=n/10; } return sum; } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } 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); } } }
logn
817_C. Really Big Numbers
CODEFORCES
/** * Created by Aminul on 3/14/2019. */ import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import static java.lang.Math.max; public class E_2 { public static void main(String[] args) throws Exception { FastReader in = new FastReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(), k = in.nextInt(), N = (int) 5e6 + 1; int left = 0, right = 0; int a[] = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); if (a[i] == k) left++; } int f[] = new int[N + 1]; int ans = 0; for (int i = n; i >= 1; i--) { if (a[i] == k) left--; f[a[i]]++; f[a[i]] = max(f[a[i]], 1 + right); ans = max(ans, f[a[i]] + left); if (a[i] == k) right++; } pw.println(ans); pw.close(); } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } static class FastReader { InputStream is; private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; public FastReader(InputStream is) { this.is = is; } public int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } public int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = (num << 3) + (num << 1) + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } } }
linear
1082_E. Increasing Frequency
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class CodeForces { class Pair<K, V> { K first; V second; public Pair(K k, V v) { first = k; second = v; } } private boolean contain(int set, int i) { return (set & (1<<i)) > 0; } private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a%b); } private long pow(long a, long p) { if (p == 0) return 1; long b = pow(a, p/2); b = b * b; if (p % 2 == 1) b *= a; return b % mod; } private static boolean isSame(double a, double b) { return Math.abs(a - b) < 1e-10; } private static void swapBoolean(boolean[] p, int i, int j) { boolean tmp = p[i]; p[i] = p[j]; p[j] = tmp; } private static void swap(int[] p, int i, int j) { int tmp = p[i]; p[i] = p[j]; p[j] = tmp; } private static int countOne(int a) { if (a == 0) return 0; return countOne(a & (a-1)) + 1; } private static int sdiv(int a, int b) { return (a +b -1) / b; } private int[] retran(int index) { int[] res = new int[2]; res[0] = index / M; res[1] = index % M; return res; } private int tran(int x, int y) { return x * M + y; } private boolean inTable(int x, int y) { return x>=0 && x< N && y >= 0 && y < M; } int N; int R; int[][] C = new int[10][10]; int M; int mod = 1_000_000_007; long IMPO; int ans; int[] dx = new int[]{1,0, -1, 0}; int[] dy = new int[]{0, -1, 0, 1}; Map<String, Boolean> dp = new HashMap<>(); class Edge { int u; int v; int start; int duration; public Edge(int u, int v, int l, int d) { this.u = u; this.v = v; this.start = l; this.duration = d; } } List<List<Integer>> graph = new ArrayList<>(); List<Edge> edges = new ArrayList<>(); int[] parent; boolean[] visited; public void run(Scanner scanner) throws IOException { long k = scanner.nextLong(); int len = 1; long number = 9; for (int i = 0; true; i++) { if (len * number < k) { k -= len * number; len ++; number *= 10; } else { break; } } number /= 9; StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 9; i++) { if (len * number < k) { k -= len * number; } else { sb.append(i); break; } } for (int i = 1; i < len; i++) { number /= 10; for (int j = 0; j <= 9; j++) { if (len * number < k) { k -= len * number; } else { sb.append(j); break; } } } System.out.println(sb.charAt((int) k - 1)); } public static void main(String[] args) throws NumberFormatException, IOException { // String fileName = "C://Users/user/eclipse-workspace/algo/example.txt"; // String outFile = "C://Users/user/eclipse-workspace/algo/example-out.txt"; // String fileName = "C://Users/user/eclipse-workspace/algo/A-small-practice.in"; // String outFile = "C://Users/user/eclipse-workspace/algo/A-small-out.txt"; // String fileName = "C://Users/user/eclipse-workspace/algo/A-large-practice.in"; // String outFile = "C://Users/user/eclipse-workspace/algo/A-large-out.txt"; // String fileName = "/Users/mobike/IdeaProjects/algo/B-small-practice.in"; // String outFile = "/Users/mobike/IdeaProjects/algo/B-small-out.txt"; // String fileName = "/Users/mobike/IdeaProjects/algo/B-large-practice.in"; // String outFile = "/Users/mobike/IdeaProjects/algo/B-large-out.txt"; // String fileName = "C://Users/user/eclipse-workspace/algo/C-small-practice.in"; // String outFile = "C://Users/user/eclipse-workspace/algo/C-small-out.txt"; // String fileName = "C://Users/user/eclipse-workspace/algo/D-small-practice.in"; // String outFile = "C://Users/user/eclipse-workspace/algo/D-small-out.txt"; // String fileName = "C://Users/user/eclipse-workspace/algo/D-large-practice.in"; // String outFile = "C://Users/user/eclipse-workspace/algo/D-large-out.txt"; Scanner scanner = new Scanner(System.in); // int T = scanner.nextInt(); // for (int i = 1; i <= T; i++) { CodeForces jam = new CodeForces(); jam.run(scanner); // } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import javax.print.attribute.standard.PrinterMessageFromOperator; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws Exception { new Main().run();} // int[] h,ne,to,wt; // int ct = 0; // int n; // void graph(int n,int m){ // h = new int[n]; // Arrays.fill(h,-1); //// sccno = new int[n]; //// dfn = new int[n]; //// low = new int[n]; //// iscut = new boolean[n]; // ne = new int[2*m]; // to = new int[2*m]; // wt = new int[2*m]; // ct = 0; // } // void add(int u,int v,int w){ // to[ct] = v; // ne[ct] = h[u]; // wt[ct] = w; // h[u] = ct++; // } // // int color[],dfn[],low[],stack[] = new int[1000000],cnt[]; // int sccno[]; // boolean iscut[]; // int time = 0,top = 0; // int scc_cnt = 0; // // // 有向图的强连通分量 // void tarjan(int u) { // low[u] = dfn[u]= ++time; // stack[top++] = u; // for(int i=h[u];i!=-1;i=ne[i]) { // int v = to[i]; // if(dfn[v]==0) { // tarjan(v); // low[u]=Math.min(low[u],low[v]); // } else if(sccno[v]==0) { // // dfn>0 but sccno==0, means it's in current stack // low[u]=Math.min(low[u],low[v]); // } // } // // if(dfn[u]==low[u]) { // sccno[u] = ++scc_cnt; // while(stack[top-1]!=u) { // sccno[stack[top-1]] = scc_cnt; // --top; // } // --top; // } // } // // //缩点, topology sort // int[] h1,to1,ne1; // int ct1 = 0; // void point(){ // for(int i=0;i<n;i++) { // if(dfn[i]==0) tarjan(i);//有可能图不连通,所以要循环判断。 // } // // 入度 // int du[] = new int[scc_cnt+1]; // h1 = new int[scc_cnt+1]; // Arrays.fill(h1, -1); // to1 = new int[scc_cnt*scc_cnt]; // ne1 = new int[scc_cnt*scc_cnt]; // // scc_cnt 个点 // // for(int i=1;i<=n;i++) { // for(int j=h[i]; j!=-1; j=ne[j]) { // int y = to[j]; // if(sccno[i] != sccno[y]) { // // add(sccno[i],sccno[y]); // 建新图 // to1[ct1] = sccno[y]; // ne1[ct1] = h[sccno[i]]; // h[sccno[i]] = ct1++; // du[sccno[y]]++; //存入度 // } // } // } // // int q[] = new int[100000]; // int end = 0; // int st = 0; // for(int i=1;i<=scc_cnt;++i){ // if(du[i]==0){ // q[end++] = i; // } // } // // int dp[] = new int[scc_cnt+1]; // while(st<end){ // int cur = q[st++]; // for(int i=h1[cur];i!=-1;i=ne1[i]){ // int y = to[i]; // // dp[y] += dp[cur]; // if(--du[y]==0){ // q[end++] = y; // } // } // } // } // // // // // int fa[]; // int faw[]; // // int dep = -1; // int pt = 0; // void go(int rt,int f,int dd){ // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = f;p++; // while(p>0) { // int cur = stk[p - 1]; // int fp = fk[p - 1]; // int ll = lk[p - 1]; // p--; // // // if (ll > dep) { // dep = ll; // pt = cur; // } // for (int i = h[cur]; i != -1; i = ne[i]) { // int v = to[i]; // if (fp == v) continue; // // stk[p] = v; // lk[p] = ll + wt[i]; // fk[p] = cur; // p++; // } // } // } // int pt1 = -1; // void go1(int rt,int f,int dd){ // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = f;p++; // while(p>0) { // int cur = stk[p - 1]; // int fp = fk[p - 1]; // int ll = lk[p - 1]; // p--; // // // if (ll > dep) { // dep = ll; // pt1 = cur; // } // // fa[cur] = fp; // for (int i = h[cur]; i != -1; i = ne[i]) { // int v = to[i]; // if (v == fp) continue; // faw[v] = wt[i]; // stk[p] = v; // lk[p] = ll + wt[i]; // fk[p] = cur; // p++; // } // } // } // // int r = 0; // int stk[] = new int[301]; // int fk[] = new int[301]; // int lk[] = new int[301]; // void ddfs(int rt,int t1,int t2,int t3,int l){ // // // int p = 0; // stk[p] = rt; // lk[p] = 0; // fk[p] = t3;p++; // while(p>0){ // int cur = stk[p-1]; // int fp = fk[p-1]; // int ll = lk[p-1]; // p--; // r = Math.max(r,ll); // for(int i=h[cur];i!=-1;i=ne[i]){ // int v = to[i]; // if(v==t1||v==t2||v==fp) continue; // stk[p] = v; // lk[p] = ll+wt[i]; // fk[p] = cur;p++; // } // } // // // // } static long mul(long a, long b, long p) { long res=0,base=a; while(b>0) { if((b&1L)>0) res=(res+base)%p; base=(base+base)%p; b>>=1; } return res; } static long mod_pow(long k,long n,long p){ long res = 1L; long temp = k; while(n!=0L){ if((n&1L)==1L){ res = (res*temp)%p; } temp = (temp*temp)%p; n = n>>1L; } return res%p; } int ct = 0; int f[] =new int[200001]; int b[] =new int[200001]; int str[] =new int[200001]; void go(int rt,List<Integer> g[]){ str[ct] = rt; f[rt] = ct; for(int cd:g[rt]){ ct++; go(cd,g); } b[rt] = ct; } int add =0; void go(int rt,int sd,int k,List<Integer> g[],int n){ if(add>n) { return; } Queue<Integer> q =new LinkedList<>(); q.offer(rt); for(int i=1;i<=sd;++i){ int sz =q.size(); if(sz==0) break; int f = (i==1?2:1); while(sz-->0){ int cur = q.poll(); for(int j=0;j<k-f;++j){ q.offer(add); g[cur].add(add);add++; if(add==n+1){ return; } } } } } void solve() { int n = ni(); long s[] = new long[n+1]; for(int i=0;i<n;++i){ s[i+1] = s[i] + ni(); } Map<Long,List<int[]>> mp = new HashMap<>(); for(int i=0;i<n;++i) { for (int j = i; j>=0; --j) { long v = s[i+1]-s[j]; if(!mp.containsKey(v)){ mp.put(v, new ArrayList<>()); } mp.get(v).add(new int[]{j,i}); } } int all = 0;long vv = -1; for(long v:mp.keySet()){ List<int[]> r = mp.get(v); int sz = r.size();int c = 0; int ri = -2000000000; for(int j=0;j<sz;++j){ if(r.get(j)[0]>ri){ ri = r.get(j)[1];c++; } } if(c>all){ all = c; vv = v; } } println(all); List<int[]> r = mp.get(vv); int sz = r.size();int c = 0; int ri = -2000000000; for(int j=0;j<sz;++j){ if(r.get(j)[0]>ri){ ri = r.get(j)[1];println((1+r.get(j)[0])+" "+(1+r.get(j)[1])); } } //N , M , K , a , b , c , d . 其中N , M是矩阵的行列数;K 是上锁的房间数目,(a, b)是起始位置,(c, d)是出口位置 // int n = ni(); // int m = ni(); // int k = ni(); // int a = ni(); // int b = ni(); // int c = ni(); // int d = ni(); // // // char cc[][] = nm(n,m); // char keys[][] = new char[n][m]; // // char ky = 'a'; // for(int i=0;i<k;++i){ // int x = ni(); // int y = ni(); // keys[x][y] = ky; // ky++; // } // int f1[] = {a,b,0}; // // int dd[][] = {{0,1},{0,-1},{1,0},{-1,0}}; // // Queue<int[]> q = new LinkedList<>(); // q.offer(f1); // int ts = 1; // // boolean vis[][][] = new boolean[n][m][33]; // // while(q.size()>0){ // int sz = q.size(); // while(sz-->0) { // int cur[] = q.poll(); // vis[cur[0]][cur[1]][cur[2]] = true; // // int x = cur[0]; // int y = cur[1]; // // for (int u[] : dd) { // int lx = x + u[0]; // int ly = y + u[1]; // if (lx >= 0 && ly >= 0 && lx < n && ly < m && (cc[lx][ly] != '#')&&!vis[lx][ly][cur[2]]){ // char ck =cc[lx][ly]; // if(ck=='.'){ // if(lx==c&&ly==d){ // println(ts); return; // } // if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') { // int cao = cur[2] | (1 << (keys[lx][ly] - 'a')); // q.offer(new int[]{lx, ly, cao}); // vis[lx][ly][cao] = true; // }else { // // q.offer(new int[]{lx, ly, cur[2]}); // } // // }else if(ck>='A'&&ck<='Z'){ // int g = 1<<(ck-'A'); // if((g&cur[2])>0){ // if(lx==c&&ly==d){ // println(ts); return; // } // if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') { // // int cao = cur[2] | (1 << (keys[lx][ly] - 'a')); // q.offer(new int[]{lx, ly, cao}); // vis[lx][ly][cao] = true;; // }else { // // q.offer(new int[]{lx, ly, cur[2]}); // } // } // } // } // } // // } // ts++; // } // println(-1); // int n = ni(); // // HashSet<String> st = new HashSet<>(); // HashMap<String,Integer> mp = new HashMap<>(); // // // for(int i=0;i<n;++i){ // String s = ns(); // int id= 1; // if(mp.containsKey(s)){ // int u = mp.get(s); // id = u; // // } // // if(st.contains(s)) { // // while (true) { // String ts = s + id; // if (!st.contains(ts)) { // s = ts; // break; // } // id++; // } // mp.put(s,id+1); // }else{ // mp.put(s,1); // } // println(s); // st.add(s); // // } // int t = ni(); // // for(int i=0;i<t;++i){ // int n = ni(); // long w[] = nal(n); // // Map<Long,Long> mp = new HashMap<>(); // PriorityQueue<long[]> q =new PriorityQueue<>((xx,xy)->{return Long.compare(xx[0],xy[0]);}); // // for(int j=0;j<n;++j){ // q.offer(new long[]{w[j],0}); // mp.put(w[j],mp.getOrDefault(w[j],0L)+1L); // } // // while(q.size()>=2){ // long f[] = q.poll(); // long y1 = f[1]; // if(y1==0){ // y1 = mp.get(f[0]); // if(y1==1){ // mp.remove(f[0]); // }else{ // mp.put(f[0],y1-1); // } // } // long g[] = q.poll(); // long y2 = g[1]; // if(y2==0){ // y2 = mp.get(g[0]); // if(y2==1){ // mp.remove(g[0]); // }else{ // mp.put(g[0],y2-1); // } // } // q.offer(new long[]{f[0]+g[0],2L*y1*y2}); // // } // long r[] = q.poll(); // println(r[1]); // // // // // } // int o= 9*8*7*6; // println(o); // int t = ni(); // for(int i=0;i<t;++i){ // long a = nl(); // int k = ni(); // if(k==1){ // println(a); // continue; // } // // int f = (int)(a%10L); // int s = 1; // int j = 0; // for(;j<30;j+=2){ // int u = f-j; // if(u<0){ // u = 10+u; // } // s = u*s; // s = s%10; // if(s==k){ // break; // } // } // // if(s==k) { // println(a - j - 2); // }else{ // println(-1); // } // // // // // } // int m = ni(); // h = new int[n]; // to = new int[2*(n-1)]; // ne = new int[2*(n-1)]; // wt = new int[2*(n-1)]; // // for(int i=0;i<n-1;++i){ // int u = ni()-1; // int v = ni()-1; // // } // long a[] = nal(n); // int n = ni(); // int k = ni(); // t1 = new long[200002]; // // int p[][] = new int[n][3]; // // for(int i=0;i<n;++i){ // p[i][0] = ni(); // p[i][1] = ni(); // p[i][2] = i+1; // } // Arrays.sort(p, new Comparator<int[]>() { // @Override // public int compare(int[] x, int[] y) { // if(x[1]!=y[1]){ // return Integer.compare(x[1],y[1]); // } // return Integer.compare(y[0], x[0]); // } // }); // // for(int i=0;i<n;++i){ // int ck = p[i][0]; // // } } // int []h,to,ne,wt; long t1[]; // long t2[]; void update(long[] t,int i,long v){ for(;i<t.length;i+=(i&-i)){ t[i] += v; } } long get(long[] t,int i){ long s = 0; for(;i>0;i-=(i&-i)){ s += t[i]; } return s; } int equal_bigger(long t[],long v){ int s=0,p=0; for(int i=Integer.numberOfTrailingZeros(Integer.highestOneBit(t.length));i>=0;--i) { if(p+(1<<i)< t.length && s + t[p+(1<<i)] < v){ v -= t[p+(1<<i)]; p |= 1<<i; } } return p+1; } static class S{ int l = 0; int r = 0 ; long le = 0; long ri = 0; long tot = 0; long all = 0; public S(int l,int r) { this.l = l; this.r = r; } } static S a[]; static int[] o; static void init(int[] f){ o = f; int len = o.length; a = new S[len*4]; build(1,0,len-1); } static void build(int num,int l,int r){ S cur = new S(l,r); if(l==r){ a[num] = cur; return; }else{ int m = (l+r)>>1; int le = num<<1; int ri = le|1; build(le, l,m); build(ri, m+1,r); a[num] = cur; pushup(num, le, ri); } } // static int query(int num,int l,int r){ // // if(a[num].l>=l&&a[num].r<=r){ // return a[num].tot; // }else{ // int m = (a[num].l+a[num].r)>>1; // int le = num<<1; // int ri = le|1; // pushdown(num, le, ri); // int ma = 1; // int mi = 100000001; // if(l<=m) { // int r1 = query(le, l, r); // ma = ma*r1; // // } // if(r>m){ // int r2 = query(ri, l, r); // ma = ma*r2; // } // return ma; // } // } static long dd = 10007; static void update(int num,int l,long v){ if(a[num].l==a[num].r){ a[num].le = v%dd; a[num].ri = v%dd; a[num].all = v%dd; a[num].tot = v%dd; }else{ int m = (a[num].l+a[num].r)>>1; int le = num<<1; int ri = le|1; pushdown(num, le, ri); if(l<=m){ update(le,l,v); } if(l>m){ update(ri,l,v); } pushup(num,le,ri); } } static void pushup(int num,int le,int ri){ a[num].all = (a[le].all*a[ri].all)%dd; a[num].le = (a[le].le + a[le].all*a[ri].le)%dd; a[num].ri = (a[ri].ri + a[ri].all*a[le].ri)%dd; a[num].tot = (a[le].tot + a[ri].tot + a[le].ri*a[ri].le)%dd; //a[num].res[1] = Math.min(a[le].res[1],a[ri].res[1]); } static void pushdown(int num,int le,int ri){ } int gcd(int a,int b){ return b==0?a: gcd(b,a%b);} InputStream is;PrintWriter out; void run() throws Exception {is = System.in;out = new PrintWriter(System.out);solve();out.flush();} private byte[] inbuf = new byte[2]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try {lenbuf = is.read(inbuf);} catch (IOException e) {throw new InputMismatchException();} if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++];} private boolean isSpaceChar(int c) {return !(c >= 33 && c <= 126);} private int skip() {int b;while((b = readByte()) != -1 && isSpaceChar(b));return b;} private double nd() {return Double.parseDouble(ns());} private char nc() {return (char) skip();} private char ncc() {int b;while((b = readByte()) != -1 && !(b >= 32 && b <= 126));return (char)b;} private String ns() {int b = skip();StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b);b = readByte(); } return sb.toString();} private char[] ns(int n) {char[] buf = new char[n];int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b;b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p);} private String nline() {int b = skip();StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b);b = readByte(); } return sb.toString();} private char[][] nm(int n, int m) {char[][] a = new char[n][];for (int i = 0; i < n; i++) a[i] = ns(m);return a;} private int[] na(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = ni();return a;} private long[] nal(int n) { long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nl();return a;} private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')){}; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') num = (num << 3) + (num << 1) + (b - '0'); else return minus ? -num : num; b = readByte();}} private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')){}; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') num = num * 10 + (b - '0'); else return minus ? -num : num; b = readByte();}} void print(Object obj){out.print(obj);} void println(Object obj){out.println(obj);} void println(){out.println();} }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
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; /** * Built using CHelper plug-in * Actual solution is at the top * * @author pandusonu */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public int mod = (int) Math.pow(10, 9) + 7; public void solve(int testNumber, InputReader in, PrintWriter out) { // out.print("Case #" + testNumber + ": "); int n = in.readInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.readString().charAt(0) == 'f' ? 1 : 0; } long[][] ans = new long[n][n + 2]; ans[0][0] = 1; int indent = 0; if (a[0] == 1) indent++; for (int i = 1; i < n; i++) { if (a[i - 1] == 1) { for (int j = indent - 1; j >= 1; j--) { ans[i][j] = ans[i - 1][j - 1]; } ans[i][indent] = 1; } else { for (int j = indent; j >= 0; j--) { ans[i][j] = (ans[i][j + 1] + ans[i - 1][j]) % mod; } } indent += a[i]; }/* for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { out.print(ans[i][j]+" "); } out.println(); }*/ long aa = 0; for (int i = 0; i < n + 2; i++) { aa = (aa + ans[n - 1][i]) % mod; } out.println(aa); } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { try { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) return -1; } } catch (IOException e) { throw new RuntimeException(e); } return buf[curChar++]; } public int readInt() { return (int) readLong(); } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); if (c == -1) throw new RuntimeException(); } boolean negative = false; if (c == '-') { negative = true; 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 negative ? (-res) : (res); } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
quadratic
909_C. Python Indentation
CODEFORCES
public class pregunta1 { public static void main(String[] args) { System.out.println("25"); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.io.IOException; import java.util.StringTokenizer; /* * @author Tnascimento */ public class MaeDosDragoes { public static PrintWriter saida = new PrintWriter(System.out, false); public static class Escanear { BufferedReader reader; StringTokenizer tokenizer; public Escanear() { this(new InputStreamReader(System.in)); } public Escanear(Reader in) { reader = new BufferedReader(in); } String proximo() { if (tokenizer == null || !tokenizer.hasMoreElements()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } int proximoNum() { return Integer.parseInt(proximo()); } } public static void main(String[] args) { Escanear escanear = new Escanear(); int proximoInt = escanear.proximoNum(); long[] aux = new long[proximoInt]; double proximoDouble = escanear.proximoNum(); for(Integer i = 0; i < proximoInt; i++) { for(Integer j =0; j < proximoInt; j++) { Integer val = escanear.proximoNum(); if (val.equals(1) || i.equals(j)) { aux[i] |= 1L << j; } } } int esquerda = proximoInt/2; int direita = proximoInt - esquerda; int maiorMascara = 1 << esquerda; int[] depois = new int[1 << esquerda]; Integer mascara = 1; while (mascara < maiorMascara) { int mascaraAtual = mascara; for(int j = 0; j < esquerda; j++) { if (((1 << j) & mascara) > 0) { mascaraAtual &= aux[j + direita] >> direita; depois[mascara] = Math.max(depois[mascara], depois[mascara ^ (1 << j)]); } } if (mascara.equals(mascaraAtual)) { depois[mascara] = Math.max(depois[mascara],Integer.bitCount(mascara)); } mascara++; } // for(int mascara = 1; mascara < maiorMascara; mascara++) { // int mascaraAtual = mascara; // for(int j = 0; j < esquerda; j++) { // if (((1 << j) & mascara) > 0) { // mascaraAtual &= aux[j + direita] >> direita; // depois[mascara] = Math.max(depois[mascara], depois[mascara ^ (1 << j)]); // } // } // if (mascara == mascaraAtual) { // depois[mascara] = Math.max(depois[mascara],Integer.bitCount(mascara)); // } // } int auxiliar = 0; int mascaraMaxima = 1 << direita; for(int masc = 0; masc < mascaraMaxima; masc++) { int mascaraCorrente = masc; int mascaraValor = maiorMascara -1; for(int j = 0; j < direita; j++) { if (((1 << j) & masc) > 0) { mascaraCorrente &= (aux[j] & (mascaraMaxima-1)); mascaraValor &= aux[j] >> direita; } } if (mascaraCorrente != masc) continue; auxiliar = Math.max(auxiliar, Integer.bitCount(masc) + depois[mascaraValor]); } proximoDouble/=auxiliar; saida.println(proximoDouble * proximoDouble * (auxiliar * (auxiliar-1))/2); saida.flush(); } }
np
839_E. Mother of Dragons
CODEFORCES
import java.io.*; import java.util.*; public class taskA { void solve() throws IOException { long a = nextLong(); long b = nextLong(); long ans = 0; while (a != 0 && b != 0) { if (a > b) { ans += a / b; a %= b; } else { long c = b % a; ans += b / a; b = a; a = c; } } out.println(ans); } BufferedReader br; StringTokenizer st; PrintWriter out; void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // br = new BufferedReader(new FileReader(new File("taskA.in"))); // out = new PrintWriter("taskA.out"); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new taskA().run(); } String nextToken() throws IOException { while ((st == null) || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; public class a { public static class Pair implements Comparable<Pair> { int f, s; public Pair(int f, int s) { this.f = f; this.s = s; } @Override public int compareTo(Pair o) { return s - o.s; } }; public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s[] = in.readLine().split(" "); long r = Long.parseLong(s[0]); long l = Long.parseLong(s[1]); if (r % 2 == 0) { if (l - r+1 < 3) { out.println(-1); } else { out.println(r + " " + (r + 1) + " " + (r + 2)); } } else { if (l - r+1 < 4) { out.println(-1); } else { out.println((r + 1) + " " + (r + 2) + " " + (r + 3)); } } out.close(); } }
constant
483_A. Counterexample
CODEFORCES
import java.lang.*; import java.io.*; import java.util.*; import java.math.*; public class Solution implements Runnable{ private static BufferedReader br = null; private static PrintWriter out = null; private static StringTokenizer stk = null; public static void main(String[] args) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); (new Thread(new Solution())).start(); } private void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } private String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } private Integer nextInt() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Integer.parseInt(stk.nextToken()); } private Long nextLong() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Long.parseLong(stk.nextToken()); } private String nextWord() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return (stk.nextToken()); } private Double nextDouble() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Double.parseDouble(stk.nextToken()); } public void run() { int n = nextInt(); int k = nextInt(); boolean[] isP = new boolean[2*n]; Arrays.fill(isP, true); isP[0] = isP[1] = false; for (int i = 0; i <= n; ++i) { if (isP[i]) { for (int j = i+i; j <= n; j+=i) { isP[j] = false; } } } ArrayList<Integer> p = new ArrayList<Integer>(); for (int i = 0; i <= n; ++i) { if (isP[i]) { p.add(i); } } int cnt = 0; for (int i = 0; i < p.size(); ++i) { int num = p.get(i) - 1; for (int j = 0; j < p.size() - 1; ++j) { if (p.get(j) + p.get(j+1) == num) { ++cnt; break; } } } if (cnt >= k) { out.println("YES"); } else { out.println("NO"); } out.flush(); } }
linear
17_A. Noldbach problem
CODEFORCES
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; public class Test { static PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int[][] a = new int[12][2000]; int[][] e = new int[12 * 2000][3]; Integer[] se = new Integer[12 * 2000]; boolean[] used = new boolean[2000]; int[] dp = new int[1 << 12]; int[] one = new int[1 << 12]; static int readInt() { int ans = 0; boolean neg = false; try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (c == '-') { start = true; neg = true; continue; } else if (c >= '0' && c <= '9') { start = true; ans = ans * 10 + c - '0'; } else if (start) break; } } catch (IOException e) { } return neg ? -ans : ans; } static long readLong() { long ans = 0; boolean neg = false; try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (c == '-') { start = true; neg = true; continue; } else if (c >= '0' && c <= '9') { start = true; ans = ans * 10 + c - '0'; } else if (start) break; } } catch (IOException e) { } return neg ? -ans : ans; } static String readLine() { StringBuilder b = new StringBuilder(); try { boolean start = false; for (int c = 0; (c = System.in.read()) != -1; ) { if (Character.isLetterOrDigit(c)) { start = true; b.append((char) c); } else if (start) break; } } catch (IOException e) { } return b.toString(); } public static void main(String[] args) { Test te = new Test(); te.start(); writer.flush(); } void start() { int t = readInt(); while (t-- > 0) { int n = readInt(), m = readInt(); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { a[i][j] = readInt(); int k = i * m + j; e[k][0] = a[i][j]; e[k][1] = j; e[k][2] = i; } for (int i = n * m - 1; i >= 0; i--) se[i] = i; Arrays.sort( se, 0, n * m, (i, j) -> { int[] x = e[i], y = e[j]; return x[0] == y[0] ? (x[1] == y[1] ? Integer.compare(x[2], y[2]) : Integer.compare(x[1], y[1])) : Integer.compare(x[0], y[0]); }); Arrays.fill(used, 0, m, false); Arrays.fill(dp, 0, 1 << n, -1); dp[0] = 0; int cc = 0; for (int x = n * m - 1; x >= 0; x--) { int c = e[se[x]][1]; if (used[c]) continue; used[c] = true; cc++; if (cc > n) break; Arrays.fill(one, 0, 1 << n, 0); for (int i = (1 << n) - 1; i > 0; i--) { for (int r = 0; r < n; r++) { int sum = 0; for (int j = 0; j < n; j++) if (((i >> j) & 1) != 0) sum += a[(j + r) % n][c]; one[i] = Math.max(one[i], sum); } } for (int i = (1 << n) - 1; i >= 0; i--) { int u = (1 << n) - 1 - i; int p = u; if (dp[i] >= 0) while (p > 0) { dp[i | p] = Math.max(dp[i | p], dp[i] + one[p]); p = (p - 1) & u; } } } writer.println(dp[(1 << n) - 1]); } } }
np
1209_E2. Rotate Columns (hard version)
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import java.util.PriorityQueue; import static java.lang.Math.*; public class solution implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 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() { 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 { public boolean isSpaceChar(int ch); } } static int mod = (int)1e9+7; public static long fastexpo(long pow) { long expo = 2; long ans = 1; while(pow!=0) { if((pow&1)==1) { ans = (ans*expo)%mod; } expo = (expo*expo)%mod; pow = pow>>1; } return ans; } public static void main(String args[]) throws Exception { new Thread(null, new solution(),"Main",1<<26).start(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); long x = sc.nextLong(); if(x==0) { out.println(0); out.close(); return; } long k = sc.nextLong(); long a = ((fastexpo(k+1)%mod)*(x%mod))%mod; long b = (-1*fastexpo(k)%mod+mod)%mod; long ans = (a+b+1)%mod; out.println(ans); out.close(); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
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; /** * 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; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); CNastyaAndAWardrobe solver = new CNastyaAndAWardrobe(); solver.solve(1, in, out); out.close(); } static class CNastyaAndAWardrobe { public void solve(int testNumber, FastScanner in, PrintWriter out) { long x = in.nextLong(); long k = in.nextLong(); if (x == 0) { out.println(0); } else { long mod = (long) (1e9 + 7); long ans = (((((2 * x - 1) % mod)) * power(2, k, mod)) % mod) + 1; ans %= mod; out.println(ans); } } long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) > 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } } static class FastScanner { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public long nextLong() { return Long.parseLong(next()); } 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(); } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class round569d2b { public static void main(String args[]) { FastScanner in = new FastScanner(System.in); int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } if (n % 2 == 0) { for (int i = 0; i < n; i++) { if (arr[i] >= 0) { arr[i] = -1*arr[i]-1; } } } else { int max = Integer.MIN_VALUE; int maxIndex = 0; for (int i = 0; i < n; i++) { int elem = arr[i]; if (elem < 0) { elem = -1*elem-1; } if (elem > max) { max = elem; maxIndex = i; } } for (int i = 0; i < n; i++) { if (i == maxIndex) { if (arr[i] < 0) { arr[i] = -1*arr[i]-1; } } else { if (arr[i] >= 0) { arr[i] = -1*arr[i]-1; } } } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n ;i++) { sb.append(arr[i] + " "); } System.out.println(sb); } // ====================================================================================== // =============================== Reference Code ======================================= // ====================================================================================== static int greatestDivisor(int n) { int limit = (int) Math.sqrt(n); int max = 1; for (int i = 2; i <= limit; i++) { if (n % i == 0) { max = Integer.max(max, i); max = Integer.max(max, n / i); } } return max; } // Method to return all primes smaller than or equal to // n using Sieve of Eratosthenes static boolean[] 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. boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; prime[0] = false; prime[1] = false; 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; } } return prime; } // Binary search for number greater than or equal to target // returns -1 if number not found private static int bin_gteq(int[] a, int key) { int low = 0; int high = a.length; int max_limit = high; while (low < high) { int mid = low + (high - low) / 2; if (a[mid] < key) { low = mid + 1; } else high = mid; } return high == max_limit ? -1 : high; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static class Tuple<X, Y> { public final X x; public final Y y; public Tuple(X x, Y y) { this.x = x; this.y = y; } public String toString() { return "(" + x + "," + y + ")"; } } static class Tuple3<X, Y, Z> { public final X x; public final Y y; public final Z z; public Tuple3(X x, Y y, Z z) { this.x = x; this.y = y; this.z = z; } public String toString() { return "(" + x + "," + y + "," + z + ")"; } } static Tuple3<Integer, Integer, Integer> gcdExtended(int a, int b, int x, int y) { // Base Case if (a == 0) { x = 0; y = 1; return new Tuple3(0, 1, b); } int x1 = 1, y1 = 1; // To store results of recursive call Tuple3<Integer, Integer, Integer> tuple = gcdExtended(b % a, a, x1, y1); int gcd = tuple.z; x1 = tuple.x; y1 = tuple.y; // Update x and y using results of recursive // call x = y1 - (b / a) * x1; y = x1; return new Tuple3(x, y, gcd); } // Returns modulo inverse of a // with respect to m using extended // Euclid Algorithm. Refer below post for details: // https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/ static int inv(int a, int m) { int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply extended Euclid Algorithm while (a > 1) { // q is quotient q = a / m; t = m; // m is remainder now, process // same as euclid's algo m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1; } // k is size of num[] and rem[]. // Returns the smallest number // x such that: // x % num[0] = rem[0], // x % num[1] = rem[1], // .................. // x % num[k-2] = rem[k-1] // Assumption: Numbers in num[] are pairwise // coprime (gcd for every pair is 1) static int findMinX(int num[], int rem[], int k) { // Compute product of all numbers int prod = 1; for (int i = 0; i < k; i++) prod *= num[i]; // Initialize result int result = 0; // Apply above formula for (int i = 0; i < k; i++) { int pp = prod / num[i]; result += rem[i] * inv(pp, num[i]) * pp; } return result % prod; } /** * Source: Matt Fontaine */ static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int chars; public FastScanner(InputStream stream) { this.stream = stream; } int read() { if (chars == -1) throw new InputMismatchException(); if (curChar >= chars) { curChar = 0; try { chars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (chars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } 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 String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
linear
1180_B. Nick and Array
CODEFORCES
// upsolve with rainboy import java.io.*; import java.util.*; public class CF1187G extends PrintWriter { CF1187G() { super(System.out); } static class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; int k, l; byte[] bb = new byte[1 << 15]; byte getc() { if (k >= l) { k = 0; try { l = in.read(bb); } catch (IOException e) { l = 0; } if (l <= 0) return -1; } return bb[k++]; } int nextInt() { byte c = 0; while (c <= 32) c = getc(); int a = 0; while (c > 32) { a = a * 10 + c - '0'; c = getc(); } return a; } } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1187G o = new CF1187G(); o.main(); o.flush(); } static final int INF = 0x3f3f3f3f; ArrayList[] aa_; int n_, m_; int[] pi, kk, bb; int[] uu, vv, cost, cost_; int[] cc; void init() { aa_ = new ArrayList[n_]; for (int u = 0; u < n_; u++) aa_[u] = new ArrayList<Integer>(); pi = new int[n_]; kk = new int[n_]; bb = new int[n_]; uu = new int[m_]; vv = new int[m_]; cost = new int[m_]; cost_ = new int[m_]; cc = new int[m_ * 2]; m_ = 0; } void link(int u, int v, int cap, int cos) { int h = m_++; uu[h] = u; vv[h] = v; cost[h] = cos; cc[h << 1 ^ 0] = cap; aa_[u].add(h << 1 ^ 0); aa_[v].add(h << 1 ^ 1); } void dijkstra(int s) { Arrays.fill(pi, INF); pi[s] = 0; TreeSet<Integer> pq = new TreeSet<>((u, v) -> pi[u] != pi[v] ? pi[u] - pi[v] : kk[u] != kk[v] ? kk[u] - kk[v] : u - v); pq.add(s); Integer first; while ((first = pq.pollFirst()) != null) { int u = first; int k = kk[u] + 1; ArrayList<Integer> adj = aa_[u]; for (int h_ : adj) if (cc[h_] > 0) { int h = h_ >> 1; int p = pi[u] + ((h_ & 1) == 0 ? cost_[h] : -cost_[h]); int v = u ^ uu[h] ^ vv[h]; if (pi[v] > p || pi[v] == p && kk[v] > k) { if (pi[v] < INF) pq.remove(v); pi[v] = p; kk[v] = k; bb[v] = h_; pq.add(v); } } } } void push(int s, int t) { int c = INF; for (int u = t, h_, h; u != s; u ^= uu[h] ^ vv[h]) { h = (h_ = bb[u]) >> 1; c = Math.min(c, cc[h_]); } for (int u = t, h_, h; u != s; u ^= uu[h] ^ vv[h]) { h = (h_ = bb[u]) >> 1; cc[h_] -= c; cc[h_ ^ 1] += c; } } int edmonds_karp(int s, int t) { System.arraycopy(cost, 0, cost_, 0, m_); while (true) { dijkstra(s); if (pi[t] == INF) break; push(s, t); for (int h = 0; h < m_; h++) { int u = uu[h], v = vv[h]; if (pi[u] != INF && pi[v] != INF) cost_[h] += pi[u] - pi[v]; } } int c = 0; for (int h = 0; h < m_; h++) c += cost[h] * cc[h << 1 ^ 1]; return c; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); int[] ii = new int[k]; for (int h = 0; h < k; h++) ii[h] = sc.nextInt() - 1; ArrayList[] aa = new ArrayList[n]; for (int i = 0; i < n; i++) aa[i] = new ArrayList<Integer>(); for (int h = 0; h < m; h++) { int i = sc.nextInt() - 1; int j = sc.nextInt() - 1; aa[i].add(j); aa[j].add(i); } int t = n + k + 1; n_ = n * t + 1; m_ = k + (m * 2 * k + n) * (t - 1); init(); for (int i = 0; i < n; i++) { ArrayList<Integer> adj = aa[i]; for (int s = 0; s < t - 1; s++) { int u = i * t + s; for (int j : adj) { int v = j * t + s + 1; for (int x = 1; x <= k; x++) link(u, v, 1, c + (x * 2 - 1) * d); } } } for (int i = 0; i < n; i++) for (int s = 0; s < t - 1; s++) { int u = i * t + s, v = u + 1; link(u, v, k, i == 0 ? 0 : c); } for (int h = 0; h < k; h++) link(n_ - 1, ii[h] * t + 0, 1, 0); println(edmonds_karp(n_ - 1, 0 * t + t - 1)); } }
cubic
1187_G. Gang Up
CODEFORCES
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args){ Scanner s= new Scanner(System.in); int n=s.nextInt();StringBuilder sb=new StringBuilder(); long[] a=new long[n/2]; for(int i=0;i<n/2;i++){ a[i]=s.nextLong(); }int j=0;long[] a2=new long[n/2];long[] a1=new long[n/2]; a1[j]=a[a.length-1]/2; a2[j]=a[a.length-1]-a[a.length-1]/2; for(int i=(n-1)/2-1;i>=0;i--){ // a1[j]=a[i]/2;a2[j++]=a[i]-a[i]/2; long n1=a1[j]; if((a[i]-n1)<a2[j]){ a2[j+1]=a2[j++];a1[j]=a[i]-a2[j]; }else{a1[++j]=n1;a2[j]=a[i]-n1;} }int k=0;//int[] ans=new int[2*n]; for(int i=(n-1)/2;i>=0;i--) sb.append(a1[i]+" "); for(int i=0;i<n/2;i++) sb.append(a2[i]+" "); System.out.println(sb.toString()); } }
linear
1093_C. Mishka and the Last Exam
CODEFORCES
import java.io.*; import java.util.*; public class Main { public void solve() throws IOException { int n = nextInt(); output.println(n / 2 * 3); } public void run() throws IOException { input = new BufferedReader(new InputStreamReader(System.in)); output = new PrintWriter(System.out); solve(); input.close(); output.close(); } BufferedReader input; PrintWriter output; StringTokenizer tok; String nextToken() throws IOException { while(tok == null || !tok.hasMoreTokens()) tok = new StringTokenizer(input.readLine()); return tok.nextToken(); } int nextInt() throws IOException { return Integer.valueOf(nextToken()); } long nextLong() throws IOException { return Long.valueOf(nextToken()); } double nextDouble() throws IOException { return Double.valueOf(nextToken()); } public static void main(String[] args) throws IOException { new Main().run(); } }
constant
84_A. Toy Army
CODEFORCES
import java.util.*; public class B138 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a[] = new int[100004]; int b[] = new int[100004]; int n, m, ans = 0, dau, cuoi=-1; n = sc.nextInt(); m = sc.nextInt(); for(int i=0;i<100004;i++) a[i] = 0; for(int i=0;i<n;i++){ b[i] = sc.nextInt(); if(a[b[i]]==0){ a[b[i]] = 1; ans++; if(ans==m){ cuoi = i+1; break; } } } for(int i=cuoi-1;i>=00;i--){ if(a[b[i]]==1){ a[b[i]] = 0; ans--; if(ans==0){ System.out.println((i+1)+" "+cuoi); System.exit(0); } } } System.out.println("-1 -1"); } }
linear
224_B. Array
CODEFORCES
import java.io.*; import java.util.*; public class TaskA { public static void main(String[] args) { new TaskA(System.in, System.out); } static class Solver implements Runnable { int n, d; long[] arr; // BufferedReader in; InputReader in; PrintWriter out; void solve() throws IOException { n = in.nextInt(); d = in.nextInt(); arr = in.nextLongArray(n); Set<Long> set = new HashSet<>(); for (int i = 0; i < n; i++) { if (i == 0) set.add(arr[i] - d); else { long left = arr[i] - d; if (left - arr[i - 1] >= d) set.add(left); } if (i == n - 1) set.add(arr[i] + d); else { long right = arr[i] + d; if (arr[i + 1] - right >= d) set.add(right); } } out.println(set.size()); } void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } // uncomment below line to change to BufferedReader // public Solver(BufferedReader in, PrintWriter out) public Solver(InputReader in, PrintWriter out) { this.in = in; this.out = out; } @Override public void run() { try { solve(); } catch (IOException e) { e.printStackTrace(); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; 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 & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int arraySize) { int array[] = new int[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextInt(); return array; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } long result = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); result *= 10; result += c & 15; c = read(); } while (!isSpaceChar(c)); return result * sign; } public long[] nextLongArray(int arraySize) { long array[] = new long[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextLong(); return array; } public float nextFloat() { float result, div; byte c; result = 0; div = 1; c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean isNegative = (c == '-'); if (isNegative) c = (byte) read(); do { result = result * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') result += (c - '0') / (div *= 10); if (isNegative) return -result; return result; } public double nextDouble() { double ret = 0, div = 1; byte c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean neg = (c == '-'); if (neg) c = (byte) read(); do { ret = ret * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } public 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 String nextLine() { int c = read(); StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (!isNewLine(c)); return result.toString(); } public boolean isNewLine(int c) { return c == '\n'; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } public InputReader(InputStream stream) { this.stream = stream; } } static class CMath { static long power(long number, long power) { if (number == 1 || number == 0 || power == 0) return 1; if (power == 1) return number; if (power % 2 == 0) return power(number * number, power / 2); else return power(number * number, power / 2) * number; } static long modPower(long number, long power, long mod) { if (number == 1 || number == 0 || power == 0) return 1; number = mod(number, mod); if (power == 1) return number; long square = mod(number * number, mod); if (power % 2 == 0) return modPower(square, power / 2, mod); else return mod(modPower(square, power / 2, mod) * number, mod); } static long moduloInverse(long number, long mod) { return modPower(number, mod - 2, mod); } static long mod(long number, long mod) { return number - (number / mod) * mod; } static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } static long min(long... arr) { long min = arr[0]; for (int i = 1; i < arr.length; i++) min = Math.min(min, arr[i]); return min; } static long max(long... arr) { long max = arr[0]; for (int i = 1; i < arr.length; i++) max = Math.max(max, arr[i]); return max; } static int min(int... arr) { int min = arr[0]; for (int i = 1; i < arr.length; i++) min = Math.min(min, arr[i]); return min; } static int max(int... arr) { int max = arr[0]; for (int i = 1; i < arr.length; i++) max = Math.max(max, arr[i]); return max; } } static class Utils { static boolean nextPermutation(int[] arr) { for (int a = arr.length - 2; a >= 0; --a) { if (arr[a] < arr[a + 1]) { for (int b = arr.length - 1; ; --b) { if (arr[b] > arr[a]) { int t = arr[a]; arr[a] = arr[b]; arr[b] = t; for (++a, b = arr.length - 1; a < b; ++a, --b) { t = arr[a]; arr[a] = arr[b]; arr[b] = t; } return true; } } } } return false; } } public TaskA(InputStream inputStream, OutputStream outputStream) { // uncomment below line to change to BufferedReader // BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Thread thread = new Thread(null, new Solver(in, out), "TaskA", 1 << 29); try { thread.start(); thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } finally { in.close(); out.flush(); out.close(); } } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.*; import java.util.*; public class Main { void solve(Scanner in, PrintWriter out) { long a = in.nextLong(); out.println(25); } void run() { Locale.setDefault(Locale.US); try ( Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); ) { solve(in, out); } } public static void main(String args[]) { new Main().run(); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.util.Scanner; public class B{ public static void main(String args[]){ Scanner input = new Scanner(System.in); long n = input.nextLong(); long k = input.nextLong(); System.out.println(solve(n, k)); input.close(); } public static long solve(long n, long k){ long dis = n - k; if(n == 1) return 0; if((((k - 2) * ((k - 2) + 1)) / 2) + 1 <= dis) return -1; if(k >= n) return 1; // long ans = 2; long now = (((k - 2) * ((k - 2) + 1)) / 2) + 1 + k; long dist = Math.abs(now - n); long delta = 1 + 8 * dist; double ret = (1 + Math.sqrt(delta)) / 2; // now = (((k - 2) * ((k - 2) + 1)) / 2) + 1 + k; dist = Math.abs(now - k); delta = 1 + 8 * dist; double nret = (1 + Math.sqrt(delta)) / 2; // double back = nret - ret; ans = (long) back; return ans + 2; } }
logn
287_B. Pipeline
CODEFORCES
import java.util.*; import java.io.*; public class A{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int ans = 0; for(int i = 1; i <= n; i++){ ans += ((i*2) <= n) ? i : n-i+1; } System.out.println(ans); } }
linear
909_B. Segments
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) { arr[i] = s.nextInt(); } int parity = 0; for(int i = 0; i < n; i++) { int count = 0; for(int j = i + 1; j < n; j++) { if(arr[j] < arr[i]) { parity ^= 1; } } } int m = s.nextInt(); for(int i = 0; i < m; i++) { int l = s.nextInt(), r = s.nextInt(); if(((r - l + 1) / 2) % 2 == 1) { parity ^= 1; } System.out.println(parity == 1 ? "odd" : "even"); } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class A { @SuppressWarnings("unchecked") private static void solve() throws IOException { ArrayList<Num> c = new ArrayList<Num>(); n = nextInt(); a = nextInt(); b = nextInt(); for(int i = 0; i < n; i++) { int next = nextInt(); boolean found = false; for(int j = 0; j < c.size(); j++) { if(c.get(j).num == next) { c.get(j).freq++; found = true; break; } } if(!found) c.add(new Num(next)); } Collections.sort(c); int below = 0; int above = n; boolean f = false; for(int i = 0; i < c.size(); i++) { below += c.get(i).freq; above -= c.get(i).freq; if(below == b && above == a) { if(i == c.size()) break; System.out.println(c.get(i+1).num - c.get(i).num); f = true; break; } } if(!f) System.out.println(0); } static int n; static int a; static int b; public static void main(String[] args) { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(239); } } static BufferedReader br; static StringTokenizer st; static PrintWriter out; static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } } class Num implements Comparable<Num> { int num; int freq; Num(int n) { num = n; freq = 1; } public int compareTo(Num other) { return this.num - other.num; } }
nlogn
169_A. Chores
CODEFORCES
// Problem : G1. Playlist for Polycarp (easy version) // Contest : Codeforces - Codeforces Round #568 (Div. 2) // URL : https://codeforces.com/contest/1185/problem/G1 // Memory Limit : 256 MB // Time Limit : 5000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) import java.io.*; import java.util.*; import java.util.stream.*; public class a implements Runnable{ public static void main(String[] args) { new Thread(null, new a(), "process", 1<<26).start(); } public void run() { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); //PrintWriter out = new PrintWriter("file.out"); Task solver = new Task(); //int t = scan.nextInt(); int t = 1; for(int i = 1; i <= t; i++) solver.solve(i, scan, out); out.close(); } static class Task { static final int inf = Integer.MAX_VALUE; public void solve(int testNumber, FastReader sc, PrintWriter pw) { //CHECK FOR QUICKSORT TLE //***********************// //CHECK FOR INT OVERFLOW //***********************// int n = sc.nextInt(); int m = sc.nextInt(); tup[] arr = new tup[n]; for(int i = 0; i < n; i++) { arr[i] = new tup(sc.nextInt(), sc.nextInt()-1); } List<Integer>[] arr2 = Stream.generate(ArrayList::new).limit(16).toArray(List[]::new); for(int i = 1; i < (1<<n); i++) { int t = i; int bits = 0; while(t > 0) { if((t & 1) == 1) bits ++; t>>=1; } arr2[bits].add(i); } int[][] dp = new int[1<<n][3]; dp[0] = new int[]{1, 1, 1}; long c = 0; for(int i = 1; i <= n; i++) { for(int x : arr2[i]) { int totallen = 0; ArrayList<Integer> active = new ArrayList<>(); for(int j = 0; j < n; j++) { if((x & (1 << j)) > 0){ active.add(j); totallen += arr[j].a; } } for(int y : active) { if(i == 1) dp[x][arr[y].b]++; else dp[x][arr[y].b] += dp[x - (1<<y)][(arr[y].b+1)%3] + dp[x - (1<<y)][(arr[y].b+2)%3]; dp[x][arr[y].b] %= 1000000007; } if(totallen == m) { c += dp[x][0] + dp[x][1] + dp[x][2]; c %= 1000000007; } } } pw.println(c); } } static long binpow(long a, long b, long m) { a %= m; long res = 1; while (b > 0) { if ((b & 1) == 1) res = res * a % m; a = a * a % m; b >>= 1; } return res; } static void sort(int[] x){ shuffle(x); Arrays.sort(x); } static void sort(long[] x){ shuffle(x); Arrays.sort(x); } static class tup implements Comparable<tup>{ int a, b; tup(int a,int b){ this.a=a; this.b=b; } @Override public int compareTo(tup o){ return Integer.compare(o.b,b); } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(i + 1); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(i + 1); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } 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; } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class A { public static void main(String[] args) throws Exception{ String str = new Scanner(System.in).next(); Set<String> set = new HashSet<String>(); String max = ""; for(int l = 1; l < str.length(); ++l){ for(int i = 0; i < str.length()-l; ++i){ String substr = str.substring(i, i+l); if(!set.contains(substr) && str.indexOf(substr) != str.lastIndexOf(substr)){ set.add(substr); if(substr.length() > max.length()){ max = substr; } } } } System.out.println(max.length()); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; public class Main { static int inf = (int) 1e9 + 7; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); int n = nextInt(); int a[] = new int [n]; for(int i = 0;i < n;i++) a[i] = nextInt(); int ans = 0; boolean b[] = new boolean[n]; Arrays.sort(a); for(int i = 0;i < n;i++) { if (!b[i]) { for(int j = i;j < n;j++) { if (a[j] % a[i] == 0) b[j] = true; } ans++; } } pw.println(ans); pw.close(); } static BufferedReader br; static StringTokenizer st = new StringTokenizer(""); static PrintWriter pw; static String next() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int n = in.nextInt(); int d = in.nextInt(); int[]a = new int[n]; int ans=2; for (int i =0;i<n;i++) { a[i] = in.nextInt(); } for (int i =0;i<n-1;i++) { if (a[i+1]-a[i]==2*d) ans++; if (a[i+1]-a[i]>2*d) ans+=2; } out.printLine(ans); out.flush(); } } class pair implements Comparable { int key; int value; public pair(Object key, Object value) { this.key = (int)key; this.value=(int)value; } @Override public int compareTo(Object o) { pair temp =(pair)o; return key-temp.key; } } class Graph { int n; ArrayList<Integer>[] adjList; public Graph(int n) { this.n = n; adjList = new ArrayList[n]; for (int i = 0; i < n; i++) adjList[i] = new ArrayList<>(); } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 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 { 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 { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } 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 String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public 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; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.*; import java.util.*; import java.lang.Math.*; public class A111 { public static void main(String args[])throws Exception { Scanner in=new Scanner(System.in); // br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(System.out); int n,i,j,k=0,l; n=in.nextInt(); int a[]=new int[n]; int sum=0,sum1=0; for(i=0;i<n;i++) { a[i]=in.nextInt(); sum+=a[i]; } Arrays.sort(a); for(j=n-1;j>=0;j--) { sum1+=a[j]; k++; if(sum1*2>sum) break; } pw.println(k); pw.flush(); } }
nlogn
160_A. Twins
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable { public static void main(String[] args) { new Thread(null, new Main(), "Check2", 1 << 28).start();// to increse stack size in java } static long mod = (long) (1e9 + 7); public void run() { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); long n = in.nextLong(); long k = in.nextLong(); long ans= 0; for (long i=1;i<=Math.min(100000,n);i++){ long left = i; long right = n-i; long sum = left * (left + 1); sum /= 2; if (sum - right ==k){ ans = right; } } w.println(ans); w.close(); } void debug(Object...args) { System.out.println(Arrays.deepToString(args)); } static class pair implements Comparable<pair>{ int a; int b; pair(int a,int b){ this.a = a; this.b = b; } public int compareTo(pair o){ if(this.b != o.b)return this.b - o.b; return this.a - o.a; } } long modinv(long a,long b) { long p=power(b,mod-2,mod); p=a%mod*p%mod; p%=mod; return p; } long power(long x,long y,long mod){ if(y==0)return 1%mod; if(y==1)return x%mod; long res=1; x=x%mod; while(y>0) { if((y%2)!=0){ res=(res*x)%mod; } y=y/2; x=(x*x)%mod; } return res; } long gcd(long a,long b){ if(b==0)return a; return gcd(b,a%b); } void sev(int a[],int n){ for(int i=2;i<=n;i++)a[i]=i; for(int i=2;i<=n;i++){ if(a[i]!=0){ for(int j=2*i;j<=n;){ a[j]=0; j=j+i; } } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars){ curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 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); } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.util.Scanner; public class Main { public static long power(long a, long b, long c){ if(b == 0){ return 1; } a %= c; if(b % 2 == 0){ return power((a % c * a % c) % c, b / 2, c); }else{ return (a % c * power((a % c * a % c) % c, b / 2, c) % c) % c; } } public static void main(String[] args) { Scanner s = new Scanner(System.in); long x = s.nextLong(), k = s.nextLong() + 1, mod = (long)Math.pow(10, 9) + 7; long ans; if(x == 0){ System.out.println(0); return; } // if(x != 0){ ans = ((power(2, k % (mod - 1), mod) % mod) * (x % mod)) % mod; /* }else{ ans = 0; } */ans = (ans - power(2, (k - 1) % (mod - 1), mod) % mod + 2 * mod) % mod; System.out.println((ans + 1) % mod); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.HashMap; import java.util.Map; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Tibor */ public class test{ // static java.io.InputStreamReader converter = new java.io.InputStreamReader(System.in); // static java.io.BufferedReader in = new java.io.BufferedReader(converter); // // public static String readLine() { // String s = ""; // try { // // s = in.readLine(); // } catch (Exception e) { // System.out.println("Error! Exception: " + e); // } // return s; // } static StreamTokenizer in = new StreamTokenizer(new BufferedReader( new InputStreamReader(System.in))); static PrintWriter out = new PrintWriter(System.out); // static { // in.ordinaryChars('-', '-'); // in.ordinaryChars('+', '+'); // in.wordChars('-', '-'); // in.wordChars('+', '+'); // } static int nextInt() { try { in.nextToken(); } catch (IOException ex) { Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex); } return (int) in.nval; } static String nextString() { try { in.nextToken(); } catch (IOException ex) { Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex); } return in.sval; } public static void main(String args[]) throws Exception { int n = nextInt(); long k = nextInt(); long a[] = new long[n + 1]; Map<Long, Long> drb = new HashMap<Long, Long>(); int elso = 1; long sk = 0; long sm = 0; long minjo = Long.MAX_VALUE; long minjoh = Long.MAX_VALUE; Vector<long[]> ret = new Vector<long[]>(); for (int i = 1; i <= n; i++) { a[i] = nextInt(); if (/*a[i - 1] <= a[i]*/true) { sm += a[i]; if (drb.containsKey(a[i])) { drb.put(a[i], drb.get(a[i]) + 1); } else { drb.put(a[i], (long) 1); sk++; } while (sk > k || drb.get(a[elso]) > 1) { long s = drb.get(a[elso]); if (s == 1) { drb.remove(a[elso]); sk--; } else { drb.put(a[elso], s - 1); } sm -= a[elso]; elso++; } if (sk == k) { if (minjo > sm) { minjo = sm; ret.clear(); minjoh = i - elso; } if (minjo == sm) { if (minjoh > i - elso) { ret.clear(); minjoh = i - elso; } ret.add(new long[]{elso, i}); } } } else { elso = i; drb.clear(); drb.put(a[i], (long) 1); sk = 1; sm = a[i]; if (k == 1) { if (minjo > sm) { minjo = sm; ret.clear(); } if (minjo == sm) { ret.add(new long[]{elso, i}); } } } } for (long[] r : ret) { System.out.print(r[0] + " "); System.out.print(r[1] + " "); break; } if (ret.size() == 0) { System.out.print(-1 + " "); System.out.print(-1 + " "); } } }
linear
224_B. Array
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class TaskB { void run() { FastReader in = new FastReader(System.in); // FastReader in = new FastReader(new FileInputStream("input.txt")); PrintWriter out = new PrintWriter(System.out); // PrintWriter out = new PrintWriter(new FileOutputStream("output.txt")); long n = in.nextLong(); long k = in.nextLong(); long a = 1; long b = -(2 * n + 3); long c = n * n + n - 2 * k; long d = b * b - 4 * a * c; long ans1 = (-b + (long) Math.sqrt(d)) / 2; long ans2 = (-b - (long) Math.sqrt(d)) / 2; if (ans1 >= 0 && ans1 <= n) { out.println(ans1); } else { out.println(ans2); } out.close(); } class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } Integer nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } Double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(nextLine()); return st.nextToken(); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } public static void main(String[] args) { new TaskB().run(); } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class B { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(System.in); long n = sc.nextLong(), k = sc.nextLong(); // BufferedReader rd = new BufferedReader(new // InputStreamReader(System.in)); // StringTokenizer t = new StringTokenizer(rd.readLine(), " "); // int n = Integer.parseInt(rd.readLine()); if (n == 1) { System.out.println(0); return; } if (n <= k) { System.out.println(1); return; } long seg = (((k + 1) * (k) / 2) - 1); seg += (2 - k); if (seg < n) { System.out.println(-1); return; } // long sum = k; // long out = 0l; long s = 1, f = k; long mid = (s + f) / 2; while (s + 1 < f) { long seg_m = (((mid + k - 1) * (k - mid) / 2)); // seg += (2 - mid); // long sum_m = seg - seg_m; if (seg_m >= n - 1) { // if (n - mid < out || out == 0) { // out = n - mid - 1; // } s = mid; } else f = mid; mid = (s + f) / 2; } // for (long i = k - 1; sum < n && i >= 2; i--) { // sum += i - 1; // out++; // // if (sum >= n) // // break; // } System.out.println(k - s); } }
logn
287_B. Pipeline
CODEFORCES
import java.util.*; public class paintTheNumbers { public static void main (String [] args){ Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int [] arr = new int[n]; for(int i = 0; i < n; i++){ arr[i] = scanner.nextInt(); } System.out.print(paint(arr)); } public static int paint(int [] arr){ Arrays.sort(arr); HashSet<Integer> set = new HashSet<>(); int num = arr[0]; set.add(num); for(int i = 1; i < arr.length; i++){ if(!divBySet(set, arr[i])){ set.add(arr[i]); } } return set.size(); } /** * * @param set * @param a * @return */ public static boolean divBySet(HashSet<Integer> set, int a){ for(int s: set){ if(a % s == 0){ return true; } } return false; } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class F11141 { static class Solver { ArrayList<int[]> ranges[]; HashMap<Long, Integer> hm = new HashMap<>(); int id(long s) { if (!hm.containsKey(s)) hm.put(s, hm.size()); return hm.get(s); } // max disjoint range set in ranges[r] int[] memo; int go(int r) { memo[N] = 0; int last = N; for(int[] a : ranges[r]) { while(a[0] < last) { memo[last - 1] = memo[last]; last--; } memo[a[0]] = Math.max(memo[a[0]], Math.max(memo[a[0]], 1 + memo[a[1] + 1])); last = a[0]; } return memo[last]; } ArrayDeque<int[]> ans = new ArrayDeque<>(); void go2(int r) { memo[N] = 0; int last = N; int minAt[] = new int[N], oo = 987654321; Arrays.fill(minAt, oo); for(int[] a : ranges[r]) { minAt[a[0]] = Math.min(minAt[a[0]], a[1] - a[0]); while(a[0] < last) { memo[last - 1] = memo[last]; last--; } memo[a[0]] = Math.max(memo[a[0]], Math.max(memo[a[0]], 1 + memo[a[1] + 1])); last = a[0]; } while(0 < last) { memo[last - 1] = memo[last]; last--; } int k = 0; for(; k < N;) { if(minAt[k] == oo || memo[k] != 1 + memo[k + minAt[k] + 1]) k++; else { ans.push(new int[] {k, k + minAt[k]}); k += minAt[k] + 1; } } } @SuppressWarnings("unchecked") Solver() { ranges = new ArrayList[2250001]; for (int i = 0; i < ranges.length; i++) ranges[i] = new ArrayList<>(); } int N, LID; long[] a; void solve(Scanner s, PrintWriter out) { N = s.nextInt(); a = new long[N + 1]; for (int i = 1; i <= N; i++) a[i] = s.nextLong() + a[i - 1]; for (int i = N; i >= 1; i--) for (int j = i; j <= N; j++) { int x = id(a[j] - a[i - 1]); ranges[x].add(new int[] { i - 1, j - 1 }); } int best = 0, bid = -1; memo = new int[N + 1]; Arrays.sort(ranges, (a, b) -> b.size() - a.size()); for(int i = 0; i < ranges.length; i++, LID++) { if(ranges[i].size() <= best) break; int ans = go(i); if(ans > best) { best = ans; bid = i; } } // backtrack on bid out.println(best); go2(bid); while(!ans.isEmpty()) { int[] c = ans.pop(); out.println(++c[0] + " " + ++c[1]); } } } public static void main(String[] args) { Scanner s = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); Solver solver = new Solver(); solver.solve(s, out); out.close(); } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class D911{ void solve() { int n = ni(); int[] a = ia(n); int Q = ni(); String[] ans = {"even", "odd"}; int cur = merge(a, 0, n - 1) % 2; while(Q-->0) { int l = ni(), r = ni(); cur ^= (r - l + 1) / 2 % 2; out.println(ans[cur]); } } int merge(int[] a, int l, int r) { if(l >= r) return 0; int mid = l + r >> 1; int v1 = merge(a, l, mid); int v2 = merge(a, mid + 1, r); int[] rep = new int[r-l+1]; int ptr0 = 0, ptr1 = l, ptr2 = mid + 1; long len = mid-l+1; int ret = 0; while(ptr1<=mid && ptr2<=r) { if(a[ptr1] <= a[ptr2]) { len--; rep[ptr0++] = a[ptr1++]; } else { ret += len; rep[ptr0++] = a[ptr2++]; } } while(ptr1 <= mid) rep[ptr0++] = a[ptr1++]; while(ptr2 <= r) rep[ptr0++] = a[ptr2++]; for(int i=0;i<ptr0;i++) a[l+i] = rep[i]; return v1 + v2 + ret; } public static void main(String[] args){new D911().run();} private byte[] bufferArray = new byte[1024]; private int bufLength = 0; private int bufCurrent = 0; InputStream inputStream; PrintWriter out; public void run() { inputStream = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } int nextByte() { if(bufLength == -1) throw new InputMismatchException(); if(bufCurrent >= bufLength) { bufCurrent = 0; try {bufLength = inputStream.read(bufferArray);} catch(IOException e) { throw new InputMismatchException();} if(bufLength <= 0) return -1; } return bufferArray[bufCurrent++]; } boolean isSpaceChar(int x) {return (x < 33 || x > 126);} boolean isDigit(int x) {return (x >= '0' && x <= '9');} int nextNonSpace() { int x; while((x=nextByte()) != -1 && isSpaceChar(x)); return x; } int ni() { long ans = nl(); if (ans >= Integer.MIN_VALUE && ans <= Integer.MAX_VALUE) return (int)ans; throw new InputMismatchException(); } long nl() { long ans = 0; boolean neg = false; int x = nextNonSpace(); if(x == '-') { neg = true; x = nextByte(); } while(!isSpaceChar(x)) { if(isDigit(x)) { ans = ans * 10 + x -'0'; x = nextByte(); } else throw new InputMismatchException(); } return neg ? -ans : ans; } String ns() { StringBuilder sb = new StringBuilder(); int x = nextNonSpace(); while(!isSpaceChar(x)) { sb.append((char)x); x = nextByte(); } return sb.toString(); } char nc() { return (char)nextNonSpace();} double nd() { return (double)Double.parseDouble(ns()); } char[] ca() { return ns().toCharArray();} char[][] ca(int n) { char[][] ans = new char[n][]; for(int i=0;i<n;i++) ans[i] = ca(); return ans; } int[] ia(int n) { int[] ans = new int[n]; for(int i=0;i<n;i++) ans[i] = ni(); return ans; } void db(Object... o) {System.out.println(Arrays.deepToString(o));} }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.*; import java.io.*; public class GG { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = scanner.nextInt(); int M = scanner.nextInt(); int K = scanner.nextInt(); int C = scanner.nextInt(); int D = scanner.nextInt(); MinCostMaxFlowSolver solver = new EdmondsKarp(); int[] people = new int[K]; for(int i = 0; i < K; i++) people[i] = scanner.nextInt()-1; Node src = solver.addNode(); Node snk = solver.addNode(); int amt = 150; Node[][] timeNodes = new Node[N][amt]; for(int i = 0; i < N; i++) { for(int j = 1; j < amt; j++) { timeNodes[i][j] = solver.addNode(); if (j > 1) solver.link(timeNodes[i][j-1], timeNodes[i][j], Integer.MAX_VALUE, 0); } } for(int i = 0; i < K; i++) { solver.link(src, timeNodes[people[i]][1], 1, 0); } for(int i = 1; i < amt; i++) { for(int j = 0; j < K; j++) { solver.link(timeNodes[0][i], snk, 1, C*i-C); } } for(int i =0; i < M; i++) { int a = scanner.nextInt()-1; int b = scanner.nextInt()-1; for(int j = 1; j < amt-1; j++) { int prev = 0; for(int k = 1; k <= K; k++) { solver.link(timeNodes[a][j], timeNodes[b][j + 1], 1, D*k*k- prev); solver.link(timeNodes[b][j], timeNodes[a][j + 1], 1, D*k*k - prev); prev = D * k * k; } } } long[] ret = solver.getMinCostMaxFlow(src, snk); out.println(ret[1]); out.flush(); } public static class Node { // thou shall not create nodes except through addNode() private Node() { } List<Edge> edges = new ArrayList<Edge>(); int index; // index in nodes array } public static class Edge { boolean forward; // true: edge is in original graph Node from, to; // nodes connected long flow; // current flow final long capacity; Edge dual; // reference to this edge's dual long cost; // only used for MinCost. protected Edge(Node s, Node d, long c, boolean f) { forward = f; from = s; to = d; capacity = c; } long remaining() { return capacity - flow; } void addFlow(long amount) { flow += amount; dual.flow -= amount; } } public static abstract class MaxFlowSolver { List<Node> nodes = new ArrayList<Node>(); public void link(Node n1, Node n2, long capacity) { link(n1, n2, capacity, 1); } public void link(Node n1, Node n2, long capacity, long cost) { Edge e12 = new Edge(n1, n2, capacity, true); Edge e21 = new Edge(n2, n1, 0, false); e12.dual = e21; e21.dual = e12; n1.edges.add(e12); n2.edges.add(e21); e12.cost = cost; e21.cost = -cost; } void link(int n1, int n2, long capacity) { link(nodes.get(n1), nodes.get(n2), capacity); } protected MaxFlowSolver(int n) { for (int i = 0; i < n; i++) addNode(); } protected MaxFlowSolver() { this(0); } public abstract long getMaxFlow(Node src, Node snk); public Node addNode() { Node n = new Node(); n.index = nodes.size(); nodes.add(n); return n; } } static abstract class MinCostMaxFlowSolver extends MaxFlowSolver { // returns [maxflow, mincost] abstract long [] getMinCostMaxFlow(Node src, Node snk); // unavoidable boiler plate MinCostMaxFlowSolver () { this(0); } MinCostMaxFlowSolver (int n) { super(n); } } static class EdmondsKarp extends MinCostMaxFlowSolver { EdmondsKarp () { this(0); } EdmondsKarp (int n) { super(n); } long minCost; @Override public long [] getMinCostMaxFlow(Node src, Node snk) { long maxflow = getMaxFlow(src, snk); return new long [] { maxflow, minCost }; } static final long INF = Long.MAX_VALUE/4; @Override public long getMaxFlow(Node src, Node snk) { final int n = nodes.size(); final int source = src.index; final int sink = snk.index; long flow = 0; long cost = 0; long[] potential = new long[n]; // allows Dijkstra to work with negative edge weights while (true) { Edge[] parent = new Edge[n]; // used to store an augmenting path long[] dist = new long[n]; // minimal cost to vertex Arrays.fill(dist, INF); dist[source] = 0; PriorityQueue<Item> que = new PriorityQueue<Item>(); que.add(new Item(0, source)); while (!que.isEmpty()) { Item item = que.poll(); if (item.dist != dist[item.v]) continue; for (Edge e : nodes.get(item.v).edges) { long temp = dist[item.v] + e.cost + potential[item.v] - potential[e.to.index]; if (e.capacity > e.flow && dist[e.to.index] > temp) { dist[e.to.index] = temp; parent[e.to.index] = e; que.add(new Item(temp, e.to.index)); } } } if (parent[sink] == null) break; for (int i = 0; i < n; i++) if (parent[i] != null) potential[i] += dist[i]; long augFlow = Long.MAX_VALUE; for (int i = sink; i != source; i = parent[i].from.index) augFlow = Math.min(augFlow, parent[i].capacity - parent[i].flow); for (int i = sink; i != source; i = parent[i].from.index) { Edge e = parent[i]; e.addFlow(augFlow); cost += augFlow * e.cost; } flow += augFlow; } minCost = cost; return flow; } static class Item implements Comparable<Item> { long dist; int v; public Item(long dist, int v) { this.dist = dist; this.v = v; } public int compareTo(Item that) { return Long.compare(this.dist, that.dist); } } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } } }
cubic
1187_G. Gang Up
CODEFORCES
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.Arrays; import java.util.InputMismatchException; import java.util.*; import java.io.*; import java.math.*; public class Main6{ static class Pair { int x; int y; int z; public Pair(int x,int y,int z) { this.x= x; this.y= y; this.z=z; } @Override public int hashCode() { final int temp = 14; int ans = 1; ans =x*31+y*13; return ans; } // Equal objects must produce the same // hash code as long as they are equal @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; } } static class Pair1 { String x; int y; int z; } static class Compare { static void compare(Pair arr[], int n) { // Comparator to sort the pair according to second element /* Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.start>p2.start) { return 1; } else if(p1.start==p2.start) { return 0; } else { return -1; } } }); */ } } public static long pow(long a, long b) { long result=1; while(b>0) { if (b % 2 != 0) { result=(result*a)%998244353; b--; } a=(a*a)%998244353; b /= 2; } return result; } public static long fact(long num) { long value=1; int i=0; for(i=2;i<num;i++) { value=((value%mod)*i%mod)%mod; } return value; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } /* public static long lcm(long a,long b) { return a * (b / gcd(a, b)); } */ public static long sum(int h) { return (h*(h+1)/2); } public static void dfs(int parent,boolean[] visited,int[] dp) { ArrayList<Integer> arr=new ArrayList<Integer>(); arr=graph.get(parent); visited[parent]=true; for(int i=0;i<arr.size();i++) { int num=(int)arr.get(i); if(visited[num]==false) { dfs(num,visited,dp); } dp[parent]=Math.max(dp[num]+1,dp[parent]); } } // static int flag1=0; static int[] dis; static int mod=1000000007; static ArrayList<ArrayList<Integer>> graph; public static void bfs(int num,int size) { boolean[] visited=new boolean[size+1]; Queue<Integer> q=new LinkedList<>(); q.add(num); ans[num]=1; visited[num]=true; while(!q.isEmpty()) { int x=q.poll(); ArrayList<Integer> al=graph.get(x); for(int i=0;i<al.size();i++) { int y=al.get(i); if(visited[y]==false) { q.add(y); ans[y]=ans[x]+1; visited[y]=true; } } } } static int[] ans; // static int[] a; public static int[] sort(int[] a) { int n=a.length; ArrayList<Integer> ar=new ArrayList<>(); for(int i=0;i<a.length;i++) { ar.add(a[i]); } Collections.sort(ar); for(int i=0;i<n;i++) { a[i]=ar.get(i); } return a; } static public void main(String args[])throws IOException { int n=i(); int[] a=new int[n]; for(int i=0;i<n;i++) { a[i]=i(); } Arrays.sort(a); boolean[] flag=new boolean[n]; int ans=0; for(int i=0;i<n;i++) { if(flag[i]==false) { ans++; for(int j=0;j<n;j++) { if(a[j]%a[i]==0 && flag[j]==false) { flag[j]=true; } } } } pln(ans+""); } /**/ static InputReader in=new InputReader(System.in); static OutputWriter out=new OutputWriter(System.out); public static long l() { String s=in.String(); return Long.parseLong(s); } public static void pln(String value) { System.out.println(value); } public static int i() { return in.Int(); } public static String s() { return in.String(); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars== -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int Int() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String String() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return String(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.Int(); return array; } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
/** * Created at 22:05 on 2019-09-14 */ import java.io.*; import java.util.*; public class Main { static FastScanner sc = new FastScanner(); static Output out = new Output(System.out); static final int[] dx = {0, 1, 0, -1}; static final int[] dy = {-1, 0, 1, 0}; static final long MOD = (long) (1e9 + 7); static final long INF = Long.MAX_VALUE / 2; static final int e5 = (int) 1e5; public static class Solver { public Solver() { int N = sc.nextInt(); boolean[] flag = new boolean[101]; for (int i=0; i<N; i++) { flag[sc.nextInt()] = true; } int ans = 0; for (int i=1; i<=100; i++) { if (flag[i]) { ans++; for (int j=i*2; j<=100; j+=i) { flag[j] = false; } } } out.println(ans); } public static void sort(int[] a) { shuffle(a); Arrays.sort(a); } public static void sort(long[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(int[] arr){ int n = arr.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = arr[i]; int randomPos = i + rnd.nextInt(n-i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } public static void shuffle(long[] arr){ int n = arr.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = arr[i]; int randomPos = i + rnd.nextInt(n-i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } } public static void main(String[] args) { new Solver(); out.flush(); } static class FastScanner { private InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; public void load() { try { in = new FileInputStream(next()); } catch (Exception e) { e.printStackTrace(); } } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } public boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { return (int) nextLong(); } public int[] nextIntArray(int N, boolean oneBased) { if (oneBased) { int[] array = new int[N + 1]; for (int i = 1; i <= N; i++) { array[i] = sc.nextInt(); } return array; } else { int[] array = new int[N]; for (int i = 0; i < N; i++) { array[i] = sc.nextInt(); } return array; } } public long[] nextLongArray(int N, boolean oneBased) { if (oneBased) { long[] array = new long[N + 1]; for (int i = 1; i <= N; i++) { array[i] = sc.nextLong(); } return array; } else { long[] array = new long[N]; for (int i = 0; i < N; i++) { array[i] = sc.nextLong(); } return array; } } } static class Output extends PrintWriter { private long startTime; public Output(PrintStream ps) { super(ps); } public void print(int[] a, String separator) { for (int i = 0; i < a.length; i++) { if (i == 0) print(a[i]); else print(separator + a[i]); } println(); } public void print(long[] a, String separator) { for (int i = 0; i < a.length; i++) { if (i == 0) print(a[i]); else print(separator + a[i]); } println(); } public void print(String[] a, String separator) { for (int i = 0; i < a.length; i++) { if (i == 0) print(a[i]); else print(separator + a[i]); } println(); } public void print(ArrayList a, String separator) { for (int i = 0; i < a.size(); i++) { if (i == 0) print(a.get(i)); else print(separator + a.get(i)); } println(); } public void start() { startTime = System.currentTimeMillis(); } public void time(String s) { long time = System.currentTimeMillis() - startTime; println(s + "(" + time + ")"); } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class G1 { static int n, T, duration[], type[]; static long dp[][][], mod = (long) 1e9 + 7; public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { solveIt(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }, "Main", 1 << 28).start(); } public static void solveIt() throws Exception { Scanner in = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); n = in.nextInt(); T = in.nextInt(); dp = new long[4][T + 1][1 << n]; duration = new int[n]; type = new int[n]; for (int i = 0; i < n; i++) { duration[i] = in.nextInt(); type[i] = in.nextInt() - 1; } for (long a[][] : dp) for (long b[] : a) Arrays.fill(b, -1); pw.println(solve(3, T, 0)); pw.close(); } static long solve(int lastType, int rem, int mask) { if (rem == 0) return 1; if (rem < 0) return 0; if (dp[lastType][rem][mask] != -1) return dp[lastType][rem][mask]; long res = 0; for (int i = 0; i < n; i++) { if (!check(mask, i) && lastType != type[i] && rem - duration[i] >= 0) { res += solve(type[i], rem - duration[i], set(mask, i)); if (res >= mod) res -= mod; } } return dp[lastType][rem][mask] = res; } static boolean check(int N, int pos) { return (N & (1 << pos)) != 0; } static int set(int N, int pos) { return N = N | (1 << pos); } static int reset(int N, int pos) { return N = N & ~(1 << pos); } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.ArrayList; import java.util.List; import java.util.InputMismatchException; import java.math.BigInteger; import java.util.Iterator; import java.io.*; import java.util.Comparator; import java.util.Arrays; import java.util.Collection; /** * Generated by Contest helper plug-in * Actual solution is at the bottom */ public class Main { public static void main(String[] args) { InputReader in = new StreamInputReader(System.in); PrintWriter out = new PrintWriter(System.out); run(in, out); } public static void run(InputReader in, PrintWriter out) { Solver solver = new TaskC(); solver.solve(1, in, out); Exit.exit(in, out); } } abstract class InputReader { private boolean finished = false; public abstract int read(); public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public void setFinished(boolean finished) { this.finished = finished; } public abstract void close(); } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public StreamInputReader(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 void close() { try { stream.close(); } catch (IOException ignored) { } } } class Exit { private Exit() { } public static void exit(InputReader in, PrintWriter out) { in.setFinished(true); in.close(); out.close(); } } interface Solver { public void solve(int testNumber, InputReader in, PrintWriter out); } class ArrayUtils { public static void fill(int[][] array, int value) { for (int[] row : array) Arrays.fill(row, value); } public static void fill(int[][][] array, int value) { for (int[][] subArray : array) fill(subArray, value); } } class TaskC implements Solver { public void solve(int testNumber, InputReader in, PrintWriter out) { int rowCount = in.readInt(); int columnCount = in.readInt(); out.println(rowCount * columnCount - go(Math.min(rowCount, columnCount), Math.max(rowCount, columnCount))); } private int go(int rowCount, int columnCount) { int[][][] result = new int[columnCount][rowCount][1 << (2 * rowCount)]; ArrayUtils.fill(result, -1); return go(0, 0, (1 << rowCount) - 1, result); } private int go(int column, int row, int mask, int[][][] result) { if (column == result.length) return (mask == 0 ? 0 : Integer.MAX_VALUE / 2); int length = result[column].length; if (row == length) return go(column + 1, 0, mask, result); if (result[column][row][mask] != -1) return result[column][row][mask]; result[column][row][mask] = Integer.MAX_VALUE / 2; if ((mask >> (2 * length - 1) & 1) == 0) result[column][row][mask] = go(column, row + 1, mask * 2 + (column == result.length - 1 ? 0 : 1), result); int newMask = mask; newMask &= ~(1 << (length - 1)); if (row != 0) newMask &= ~(1 << length); if (row != length - 1) newMask &= ~(1 << (length - 2)); newMask *= 2; newMask &= (1 << (2 * length)) - 1; return result[column][row][mask] = Math.min(result[column][row][mask], 1 + go(column, row + 1, newMask, result)); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Solution { BufferedReader in; PrintWriter out; StringTokenizer st; void solve() throws IOException { int n = ni(); int[] v = new int[n]; for (int i = 0; i < n; ++i) v[i] = ni(); Arrays.sort(v); int mn = v[0]; for (int i = 1; i < n; ++i) if (v[i] > mn) { out.println(v[i]); return; } out.println("NO"); } public Solution() throws IOException { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } String ns() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int ni() throws IOException { return Integer.valueOf(ns()); } long nl() throws IOException { return Long.valueOf(ns()); } double nd() throws IOException { return Double.valueOf(ns()); } public static void main(String[] args) throws IOException { new Solution(); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
// Don't place your source in a package import javax.swing.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); 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(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int T=1; for(int t=0;t<T;t++){ int n=Int(); int k=Int(); int A[][]=new int[n][2]; for(int i=0;i<A.length;i++){ A[i][0]=Int(); A[i][1]=Int()-1; } Arrays.sort(A,(a,b)->{ return a[1]-b[1]; }); Solution sol=new Solution(out); sol.solution(A,k); } out.close(); } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution{ PrintWriter out; public Solution(PrintWriter out){ this.out=out; } int mod=1000000007; long dp3[][][][]; public void solution(int A[][],int T){ long res=0; int n=A.length; long dp1[][]=new long[n+1][T+1];//a long dp2[][][]=new long[n+1][n+1][T+1];//bc dp3=new long[n+1][n+1][n+1][3]; //init long f[]=new long[n+1]; f[0]=f[1]=1; for(int i=2;i<f.length;i++){ f[i]=f[i-1]*i; f[i]%=mod; } for(int i=0;i<dp3.length;i++){ for(int j=0;j<dp3[0].length;j++){ for(int k=0;k<dp3[0][0].length;k++){ Arrays.fill(dp3[i][j][k],-1); } } } dp1[0][0]=1; for(int i=0;i<A.length;i++){//a int p=A[i][0],type=A[i][1]; if(type==0){ long newdp[][]=new long[dp1.length][dp1[0].length]; for(int cnt=1;cnt<=n;cnt++){ for(int j=1;j<dp1[0].length;j++){ if(j>=p){ newdp[cnt][j]+=dp1[cnt-1][j-p]; newdp[cnt][j]%=mod; } } } for(int cnt=0;cnt<=n;cnt++){ for(int j=0;j<dp1[0].length;j++){ newdp[cnt][j]+=dp1[cnt][j]; newdp[cnt][j]%=mod; } } dp1=newdp; } else{ break; } } dp2[0][0][0]=1; for(int i=0;i<A.length;i++){//b c int p=A[i][0],type=A[i][1]; if(type!=0){ long newdp[][][]=new long[dp2.length][dp2[0].length][dp2[0][0].length]; for(int a=0;a<dp2.length;a++){ for(int b=0;b<dp2[0].length;b++){ for(int j=0;j<dp2[0][0].length;j++){ if(j>=p){ if(type==1){ if(a-1>=0){ newdp[a][b][j]+=dp2[a-1][b][j-p]; } } else{ if(b-1>=0) { newdp[a][b][j]+=dp2[a][b-1][j-p]; } } } newdp[a][b][j]%=mod; } } } for(int a=0;a<dp2.length;a++){ for(int b=0;b<dp2[0].length;b++){ for(int j=0;j<dp2[0][0].length;j++){ newdp[a][b][j]+=dp2[a][b][j]; newdp[a][b][j]%=mod; } } } dp2=newdp; } } dp3[1][0][0][0]=1; dp3[0][1][0][1]=1; dp3[0][0][1][2]=1; dfs(n,n,n,0);dfs(n,n,n,1);dfs(n,n,n,2); for(int i=0;i<dp3.length;i++){ for(int j=0;j<dp3[0].length;j++){ for(int k=0;k<dp3[0][0].length;k++){ for(int cur=0;cur<3;cur++){ for(int t=0;t<=T;t++){//price int aprice=t; int bcprice=T-t; long cnt1=dp1[i][aprice]; long cnt2=dp2[j][k][bcprice]; long combination=dp3[i][j][k][cur]; long p1=(cnt1*f[i])%mod; long p2=(((f[j]*f[k])%mod)*cnt2)%mod; long p3=(p1*p2)%mod; res+=(p3*combination)%mod; res%=mod; } } } } } /*System.out.println(dp3[1][0][0][0]+" "+dp2[0][0][0]); for(long p[]:dp1){ System.out.println(Arrays.toString(p)); }*/ out.println(res); } public long dfs(int a,int b,int c,int cur){ if(a<0||b<0||c<0){ return 0; } if(a==0&&b==0&&c==0){ return 0; } if(dp3[a][b][c][cur]!=-1)return dp3[a][b][c][cur]; long res=0; if(cur==0){ res+=dfs(a-1,b,c,1); res%=mod; res+=dfs(a-1,b,c,2); res%=mod; } else if(cur==1){ res+=dfs(a,b-1,c,0); res%=mod; res+=dfs(a,b-1,c,2); res%=mod; } else{ res+=dfs(a,b,c-1,0); res%=mod; res+=dfs(a,b,c-1,1); res%=mod; } res%=mod; dp3[a][b][c][cur]=res; return res; } } /* ;\ |' \ _ ; : ; / `-. /: : | | ,-.`-. ,': : | \ : `. `. ,'-. : | \ ; ; `-.__,' `-.| \ ; ; ::: ,::'`:. `. \ `-. : ` :. `. \ \ \ , ; ,: (\ \ :., :. ,'o)): ` `-. ,/,' ;' ,::"'`.`---' `. `-._ ,/ : ; '" `;' ,--`. ;/ :; ; ,:' ( ,:) ,.,:. ; ,:., ,-._ `. \""'/ '::' `:'` ,'( \`._____.-'"' ;, ; `. `. `._`-. \\ ;:. ;: `-._`-.\ \`. '`:. : |' `. `\ ) \ -hrr- ` ;: | `--\__,' '` ,' ,-' free bug dog */
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import static java.util.Arrays.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import java.util.*; import java.math.*; import java.io.*; public class A implements Runnable { String file = "input"; boolean TEST = System.getProperty("ONLINE_JUDGE") == null; void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); int[] b = a.clone(); sortInt(b); int count = 0; for(int i = 0; i < a.length; i++) if(a[i] != b[i]) count++; if(count == 0 || count == 2) out.println("YES"); else out.println("NO"); } Random rnd = new Random(); void sortInt(int[] a) { sortInt(a, 0, a.length - 1); } void sortInt(int[] a, int from, int to) { if(from >= to) return; int i = from - 1; int p = rnd.nextInt(to - from + 1) + from; int t = a[p]; a[p] = a[to]; a[to] = t; for(int j = from; j < to; j++) if(a[j] <= a[to]) { i++; t = a[i]; a[i] = a[j]; a[j] = t; } t = a[i + 1]; a[i + 1] = a[to]; a[to] = t; sortInt(a, i + 2, to); while(i >= 0 && a[i] == a[i + 1]) i--; sortInt(a, from, i); } String next() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(input.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } void print(Object... o) { System.out.println(deepToString(o)); } void gcj(Object o) { String s = String.valueOf(o); out.println("Case #" + test + ": " + s); System.out.println("Case #" + test + ": " + s); } BufferedReader input; PrintWriter out; StringTokenizer st; int test; void init() throws IOException { if(TEST) input = new BufferedReader(new FileReader(file + ".in")); else input = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedOutputStream(System.out)); } public static void main(String[] args) throws IOException { new Thread(null, new A(), "", 1 << 22).start(); } public void run() { try { init(); if(TEST) { int runs = nextInt(); for(int i = 0; i < runs; i++) solve(); } else solve(); out.close(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.*; import java.math.*; import java.io.*; public class CF1068A { public CF1068A() { FS scan = new FS(); long n = scan.nextLong(), m = scan.nextLong(), k = scan.nextLong(), l = scan.nextLong(); long ceil = (k + l + m - 1) / m; if(k + l <= n && ceil * m <= n) System.out.println(ceil); else System.out.println(-1); } class FS { 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(Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { new CF1068A(); } }
constant
1068_A. Birthday
CODEFORCES
import java.io.InputStreamReader; import java.util.Scanner; public class Hexadecimal { public static void main(String [] args){ Scanner s = new Scanner(new InputStreamReader(System.in)); int x = s.nextInt(); System.out.println(x + " " + 0 + " " + 0); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.*; import java.nio.CharBuffer; import java.util.NoSuchElementException; public class P1195B { public static void main(String[] args) { SimpleScanner scanner = new SimpleScanner(System.in); PrintWriter writer = new PrintWriter(System.out); int n = scanner.nextInt(); int k = scanner.nextInt(); int l = 0; int r = n; int ans = 0; while (l <= r) { int eat = (l + r) >> 1; int lastPut = n - eat; long totalPut = (long) (lastPut + 1) * lastPut / 2; long remain = totalPut - eat; if (remain == k) { ans = eat; break; } else if (remain > k) l = eat + 1; else r = eat - 1; } writer.println(ans); writer.close(); } private static class SimpleScanner { private static final int BUFFER_SIZE = 10240; private Readable in; private CharBuffer buffer; private boolean eof; SimpleScanner(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); buffer = CharBuffer.allocate(BUFFER_SIZE); buffer.limit(0); eof = false; } private char read() { if (!buffer.hasRemaining()) { buffer.clear(); int n; try { n = in.read(buffer); } catch (IOException e) { n = -1; } if (n <= 0) { eof = true; return '\0'; } buffer.flip(); } return buffer.get(); } void checkEof() { if (eof) throw new NoSuchElementException(); } char nextChar() { checkEof(); char b = read(); checkEof(); return b; } String next() { char b; do { b = read(); checkEof(); } while (Character.isWhitespace(b)); StringBuilder sb = new StringBuilder(); do { sb.append(b); b = read(); } while (!eof && !Character.isWhitespace(b)); return sb.toString(); } int nextInt() { return Integer.valueOf(next()); } long nextLong() { return Long.valueOf(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.*; import java.util.*; public class Problem911D { public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), i, j; int ar[] = new int[n]; int inv = 0; for(i = 0; i < n; i++) { ar[i] = sc.nextInt(); } for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { if(i > j && ar[i] < ar[j]) { inv = (inv + 1) % 2; } } } int q = sc.nextInt(); for(i = 0; i < q; i++) { int l = sc.nextInt(); int r = sc.nextInt(); int c = ( ((r-l)*(r-l+1))/2 ) % 2; inv = (inv + c) % 2; if(inv == 0) System.out.println("even"); else System.out.println("odd"); } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { private void solve() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(), m = nextInt(); boolean[][] used = new boolean[n + 1][m + 1]; for (int j = 1; j <= (m + 1) / 2; j++) { int x1 = 1, x2 = n; for (int i = 1; i <= n; i++) { if (x1 <= n && !used[x1][j]) { out.println(x1 + " " + j); used[x1++][j] = true; } if (x2 > 0 && !used[x2][m - j + 1]) { out.println(x2 + " " + (m - j + 1)); used[x2--][m - j + 1] = true; } } } out.close(); } public static void main(String[] args) { new D().solve(); } private BufferedReader br; private StringTokenizer st; private PrintWriter out; private String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return st.nextToken(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } }
quadratic
1179_B. Tolik and His Uncle
CODEFORCES
import java.util.*; import java.io.*; public class C { static FastIO f; public static void main(String args[]) throws IOException { f = new FastIO(); int t, n, a, i; Node r, p, c; t = f.ni(); while(t-->0) { n = f.ni(); r = p = new Node(-1, null); // f.out("1\n"); for(i = 0; i < n; i++) { a = f.ni(); if(a != 1) { while(a != p.i + 1) p = p.p; p = p.p; } // if(a == p.i + 1) // p = p.p; // else if(p.p != null && a == p.p.i + 1) // p = p.p.p; c = new Node(a, p); p.c.add(c); p = c; } dfs(r, ""); } f.flush(); } public static void dfs(Node n, String s) throws IOException { String t; if(n.i == -1) t = s; else { t = s + n.i + "."; f.out(s + n.i + "\n"); } for(Node c : n.c) dfs(c, t); } static class Node { int i; Node p; ArrayList<Node> c; Node(int x, Node y) { i = x; p = y; c = new ArrayList<>(); } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { Node that = (Node)obj; return super.equals(obj); } @Override public String toString() { return "[" + "PARAMETERS" + "]"; } } public static class FastIO { BufferedReader br; BufferedWriter bw, be; StringTokenizer st; public FastIO() { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out)); be = new BufferedWriter(new OutputStreamWriter(System.err)); st = new StringTokenizer(""); } private void read() throws IOException { st = new StringTokenizer(br.readLine()); } public String ns() throws IOException { while(!st.hasMoreTokens()) read(); return st.nextToken(); } public int ni() throws IOException { return Integer.parseInt(ns()); } public long nl() throws IOException { return Long.parseLong(ns()); } public float nf() throws IOException { return Float.parseFloat(ns()); } public double nd() throws IOException { return Double.parseDouble(ns()); } public char nc() throws IOException { return ns().charAt(0); } public int[] nia(int n) throws IOException { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = ni(); return a; } public long[] nla(int n) throws IOException { long[] a = new long[n]; for(int i = 0; i < n; i++) a[i] = nl(); return a; } public char[] nca() throws IOException { return ns().toCharArray(); } public void out(String s) throws IOException { bw.write(s); } public void flush() throws IOException { bw.flush(); be.flush(); } public void err(String s) throws IOException { be.write(s); } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.Scanner; //import java.util.Scanner; public class SingleWildcard { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input =new Scanner(System.in); int a = input.nextInt(); int b = input.nextInt(); char[] s1 =new char[a]; s1 = input.next().toCharArray(); char[] s2 = new char[b]; s2 = input.next().toCharArray(); boolean condition = false; for(int i=0; i<a;i++){ if(s1[i]=='*'){ condition= true; break; } } if(!condition){ if(match(s1,s2)){ System.out.println("YES"); } else System.out.println("NO"); return; } else{ int i=0; if(s1.length-1>s2.length){ System.out.println("NO"); return; } while(i<s1.length && i<s2.length && s1[i]==s2[i]){ i++; } int j=s2.length-1; int k = s1.length-1; while(j>=0 && k>=0 && s1[k]==s2[j] && i<=j){ j--; k--; } //System.out.println(i); if(i==k && i>=0 && i<s1.length && s1[i]=='*' ){ System.out.println("YES"); return; } System.out.println("NO"); } } static boolean match(char[] s1,char[] s2){ if(s1.length!=s2.length)return false; for(int i=0; i<s1.length;i++){ if(s1[i]!=s2[i])return false; } return true; } }
linear
1023_A. Single Wildcard Pattern Matching
CODEFORCES
import java.util.*; public class Main { public static class Pair implements Comparable<Pair> { int k, x; public Pair(int k) { this.k = k; } public void update(int x) { this.x = Math.max(this.x, x); } public int compareTo(Pair other) { if (x != other.x) { return other.x - x; } return k - other.k; } } public static int sum(int[] arr) { int sum = 0; for (int x : arr) { sum += x; } return sum; } public static int[] join(int[] a, int[] b) { int n = a.length; int[] best = new int[n]; int sum = 0; for (int shift = 0; shift < n; shift++) { int[] curr = new int[n]; for (int i = 0; i < n; i++) { curr[i] = Math.max(a[i], b[(i + shift) % n]); } int now = sum(curr); if (now > sum) { sum = now; best = curr; } } return best; } public static int n; public static int[] pow; public static int[][] dp, real; public static void calc(int mask) { int[] best = new int[n]; int sum = 0; for (int i = 0; i < n; i++) { if ((mask & pow[i]) != 0) { int to = mask ^ pow[i]; int[] init = new int[n]; for (int j = 0; j < n; j++) { init[j] = real[j][i]; } int[] curr = join(dp[to], init); int s = sum(curr); if (s > sum) { sum = s; best = curr; } } } dp[mask] = best; } public static void main(String[] args) { pow = new int[15]; pow[0] = 1; for (int i = 1; i < pow.length; i++) { pow[i] = pow[i - 1] * 2; } Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { n = in.nextInt(); int m = in.nextInt(); int[][] arr = new int[n][m]; for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { arr[j][k] = in.nextInt(); } } Pair[] best = new Pair[m]; for (int j = 0; j < m; j++) { best[j] = new Pair(j); for (int k = 0; k < n; k++) { best[j].update(arr[k][j]); } } Arrays.sort(best); real = new int[n][n]; for (int j = 0; j < n; j++) { for (int k = 0; k < Math.min(n, m); k++) { real[j][k] = arr[j][best[k].k]; } } dp = new int[1 << n][]; Stack<Integer>[] min = new Stack[n + 1]; for (int j = 0; j <= n; j++) { min[j] = new Stack<>(); } for (int j = 0; j < dp.length; j++) { int cnt = 0; for (int k = 0; k < n; k++) { if ((j & pow[k]) != 0) { cnt++; } } min[cnt].add(j); } for (int j = 0; j < min.length; j++) { for (int x : min[j]) { if (j == 0) { dp[x] = new int[n]; } else { calc(x); } } } System.out.println(sum(dp[dp.length - 1])); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.*; import java.util.*; public class A { public A () throws IOException { int N = sc.nextInt(); int [] A = new int [N]; for (int n = 0; n < N; ++n) A[n] = sc.nextInt(); solve(N, A); } public void solve (int N, int [] A) { //start(); Arrays.sort(A); int S1 = 0; for (int n = 0; n < N; ++n) S1 += A[n]; int S2 = 0; for (int n = N - 1; n >= 0; --n) { S2 += A[n]; if (S2 > S1 - S2) exit(N - n); } } //////////////////////////////////////////////////////////////////////////////////// static MyScanner sc; static long t; static void print (Object o) { System.out.println(o); } static void exit (Object o) { print(o); //print2((millis() - t) / 1000.0); System.exit(0); } static void run () throws IOException { sc = new MyScanner (); new A(); } public static void main(String[] args) throws IOException { run(); } static long millis() { return System.currentTimeMillis(); } static void start() { t = millis(); } static class MyScanner { String next() throws IOException { newLine(); return line[index++]; } int nextInt() throws IOException { return Integer.parseInt(next()); } String nextLine() throws IOException { line = null; return r.readLine(); } ////////////////////////////////////////////// private final BufferedReader r; MyScanner () throws IOException { this(new BufferedReader(new InputStreamReader(System.in))); } MyScanner(BufferedReader r) throws IOException { this.r = r; newLine(); } private String [] line; private int index; private void newLine() throws IOException { if (line == null || index == line.length) { line = r.readLine().split(" "); index = 0; } } } }
nlogn
160_A. Twins
CODEFORCES
import java.util.*; public class c8 { static int n; static int[] ds; static int[][] g; public static void main(String[] args) { Scanner input = new Scanner(System.in); int x = input.nextInt(), y = input.nextInt(); n = input.nextInt(); int[] xs = new int[n], ys = new int[n]; for(int i = 0; i<n; i++) { xs[i] = input.nextInt(); ys[i] = input.nextInt(); } ds = new int[n]; g = new int[n][n]; for(int i = 0; i<n; i++) { ds[i] = (x - xs[i]) * (x - xs[i]) + (y - ys[i]) * (y - ys[i]); for(int j = 0; j<n; j++) { g[i][j] = (xs[i] - xs[j]) * (xs[i] - xs[j]) + (ys[i] - ys[j]) * (ys[i] - ys[j]); } } int[] dp = new int[1<<n]; Arrays.fill(dp, 987654321); dp[0] = 0; for(int i = 0; i<(1<<n); i++) { if(dp[i] == 987654321) continue; for(int a = 0; a<n; a++) { if((i & (1<<a)) > 0) continue; dp[i | (1<<a)] = Math.min(dp[i | (1<<a)], dp[i] + 2*ds[a]); for(int b = a+1; b<n; b++) { if((i & (1<<b)) > 0) continue; dp[i | (1<<a) | (1<<b)] = Math.min(dp[i | (1<<a) | (1<<b)], dp[i] + ds[a] + ds[b] + g[a][b]); } break; } } Stack<Integer> stk = new Stack<Integer>(); stk.add(0); int i = (1<<n) - 1; //System.out.println(Arrays.toString(dp)); trace: while(i > 0) { //System.out.println(i); for(int a = 0; a<n; a++) { if((i & (1<<a)) == 0) continue; if( dp[i] == dp[i - (1<<a)] + 2*ds[a]) { stk.add(a+1); stk.add(0); i -= (1<<a); continue trace; } for(int b = a+1; b<n; b++) { if((i & (1<<b)) == 0) continue; if(dp[i] == dp[i - (1<<a) - (1<<b)] + ds[a] + ds[b] + g[a][b]) { stk.add(a+1); stk.add(b+1); stk.add(0); i -= (1<<a) + (1<<b); continue trace; } } //break; } } System.out.println(dp[(1<<n) - 1]); while(!stk.isEmpty()) System.out.print(stk.pop()+" "); } }
np
8_C. Looking for Order
CODEFORCES
import java.util.Scanner; public class Solution { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; ++i) { arr[i] = scanner.nextInt(); } boolean isOdd = false; if ((arr[0] % 2 == 0 && arr[1] % 2 == 0) || (arr[0] % 2 == 0 && arr[2] % 2 == 0) || (arr[1] % 2 == 0 && arr[2] % 2 == 0)) { isOdd = true; } if (isOdd) { for (int i = 0; i < n; ++i) { if (arr[i] % 2 == 1) { System.out.println(i + 1); break; } } } else { for (int i = 0; i < n; ++i) { if (arr[i] % 2 == 0) { System.out.println(i + 1); break; } } } } }
linear
25_A. IQ test
CODEFORCES
import com.sun.org.apache.xerces.internal.util.SynchronizedSymbolTable; import jdk.management.cmm.SystemResourcePressureMXBean; import java.awt.*; import java.io.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.util.List; import java.math.*; public class Newbie { static InputReader sc = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { solver s = new solver(); int t = 1; while (t > 0) { s.solve(); t--; } out.close(); } /* static class descend implements Comparator<pair1> { public int compare(pair1 o1, pair1 o2) { if (o1.pop != o2.pop) return (int) (o1.pop - o2.pop); else return o1.in - o2.in; } }*/ static class InputReader { public BufferedReader br; public StringTokenizer token; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream), 32768); token = null; } public String next() { while (token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static class card { long a; int cnt; int i; public card(long a, int cnt, int i) { this.a = a; this.cnt = cnt; this.i = i; } } static class ascend implements Comparator<pair> { public int compare(pair o1, pair o2) { return o1.a - o2.a; } } static class extra { static boolean v[] = new boolean[100001]; static List<Integer> l = new ArrayList<>(); static int t; static void shuffle(long a[]) { List<Long> l = new ArrayList<>(); for (int i = 0; i < a.length; i++) l.add(a[i]); Collections.shuffle(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static long gcd(long a, long b) { if (b == 0) return a; else return gcd(b, a % b); } static boolean valid(int i, int j, int r, int c) { if (i >= 0 && i < r && j >= 0 && j < c) return true; else return false; } static void seive() { for (int i = 2; i < 100001; i++) { if (!v[i]) { t++; l.add(i); for (int j = 2 * i; j < 100001; j += i) v[j] = true; } } } static int binary(long a[], long val, int n) { int mid = 0, l = 0, r = n - 1, ans = 0; while (l <= r) { mid = (l + r) >> 1; if (a[mid] == val) { r = mid - 1; ans = mid; } else if (a[mid] > val) r = mid - 1; else { l = mid + 1; ans = l; } } return (ans + 1); } static long fastexpo(int x, int y) { long res = 1; while (y > 0) { if ((y & 1) == 1) { res *= x; } y = y >> 1; x = x * x; } return res; } static long lfastexpo(int x, int y, int p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) { res = (res * x) % p; } y = y >> 1; x = (x * x) % p; } return res; } } static class pair { int a; int b; public pair(int a, int i) { this.a = a; this.b = i; } } static class pair1 { pair p; int in; public pair1(pair a, int n) { this.p = a; this.in = n; } } static long m = (long) 1e9 + 7; static class solver { void solve() { int n = sc.nextInt(); int ans=0; int a[]=new int[2*n]; for (int i = 0; i < 2 * n; i++) { a[i]=sc.nextInt(); } for(int i=0;i<2*n;i++) { if(a[i]>0) { int j=0; for(j=i+1;a[i]!=a[j];j++) { if(a[j]>0) ans++; } a[j]=0; } } System.out.println(ans); } } }
quadratic
995_B. Suit and Tie
CODEFORCES
import java.util.*; import java.math.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //System.out.println(f(1,100,30)); String S[]=br.readLine().split(" "); int N=Integer.parseInt(S[0]); int x=Integer.parseInt(S[1]); int y=Integer.parseInt(S[2]); int c=Integer.parseInt(S[3]); int lo=0; //System.out.println(Long.MAX_VALUE); int hi=1000000000; while(hi-lo>=10) { int steps=(hi+lo)/2; //System.out.println("checking "+steps+" hi= "+hi+" lo = "+lo); long total=f(x,y,steps)+f(N-x+1,y,steps)+f(N-x+1,N-y+1,steps)+f(x,N-y+1,steps); //System.out.println(f(x,y,steps)+" "+f(N-x+1,y,steps)+" "+f(N-x+1,N-y+1,steps)+" "+f(x,N-y+1,steps)); total-=3; //x,y total-=Math.min(steps,x-1); //left total-=Math.min(steps,y-1); //down total-=Math.min(steps,N-x); //right total-=Math.min(steps,N-y); //up //System.out.println("total = "+total); if(total>=c) hi=steps+1; else lo=steps-1; } for(int steps=lo;steps<=hi;steps++) { //System.out.println("checking "+steps); long total=f(x,y,steps)+f(N-x+1,y,steps)+f(N-x+1,N-y+1,steps)+f(x,N-y+1,steps); total-=3; //x,y total-=Math.min(steps,x-1); //left total-=Math.min(steps,y-1); //down total-=Math.min(steps,N-x); //right total-=Math.min(steps,N-y); //up //System.out.println("total = "+total); if(total>=c) { System.out.println(steps); return; } } } public static long f(long a, long b, long steps) { //System.out.println("f("+a+","+b+","+steps+")"); steps++; long A=Math.min(a,b); long B=Math.max(a,b); long ans=0; if(steps>=(A+B)) { //System.out.println("case 1"); ans= A*B; } else if(steps<=A) { //System.out.println("case 2"); ans= (steps*(steps+1))/2; } else if(steps>A&&steps<=B) { //System.out.println("case 3"); ans= (A*(A+1))/2+(steps-A)*A; } else if(steps>B) { //System.out.println("case 4"); ans= (A*(A+1))/2+(B-A)*A+(steps-B)*A-((steps-B)*(steps-B+1))/2; } //System.out.println("\treturning "+ans); return ans; } } //must declare new classes here
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.util.Random; import java.util.Arrays; import java.util.StringTokenizer; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStreamReader; import java.io.File; public class Task{ static final boolean readFromFile = false; static final String fileInputName = "input.txt", fileOutputName = "output.txt"; public static void main(String args[]){ FileInputStream fileInputStream; FileOutputStream fileOutputStream; InputStream inputStream = System.in; OutputStream outputStream = System.out; if (readFromFile){ try{ fileInputStream = new FileInputStream(new File(fileInputName)); fileOutputStream = new FileOutputStream(new File(fileOutputName)); }catch (FileNotFoundException e){ throw new RuntimeException(e); } } PrintWriter out = new PrintWriter((readFromFile)?fileOutputStream:outputStream); InputReader in = new InputReader((readFromFile)?fileInputStream:inputStream); Solver s = new Solver(in, out); s.solve(); out.close(); } } class Solver{ private PrintWriter out; private InputReader in; public void solve(){ int n = in.nextInt(); double t = in.nextDouble(), a[] = new double[n], x[] = new double[n]; for (int i=0;i<n;i++){ x[i] = in.nextDouble(); a[i] = in.nextDouble(); } int ans = 2; for (int i=0;i<n-1;i++) for (int j=i+1;j<n;j++) if (x[j]<x[i]){ double buf = x[i];x[i]=x[j];x[j]=buf; buf = a[i]; a[i]=a[j];a[j]=buf; } for (int i=0;i<n-1;i++){ if (x[i]+a[i]/2+t<x[i+1]-a[i+1]/2) ans += 2; if (x[i]+a[i]/2+t==x[i+1]-a[i+1]/2) ans++; } out.println(ans); } Solver(InputReader in, PrintWriter out){ this.in = in; this.out = out; } } class InputReader{ StringTokenizer tok; BufferedReader buf; InputReader(InputStream in){ tok = null; buf = new BufferedReader(new InputStreamReader(in)); } InputReader(FileInputStream in){ tok = null; buf = new BufferedReader(new InputStreamReader(in)); } public String next(){ while (tok==null || !tok.hasMoreTokens()){ try{ tok = new StringTokenizer(buf.readLine()); }catch (IOException e){ throw new RuntimeException(e); } } return tok.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public float nextFloat(){ return Float.parseFloat(next()); } public String nextLine(){ try{ return buf.readLine(); }catch (IOException e){ return null; } } }
nlogn
15_A. Cottage Village
CODEFORCES
//package round81; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class B { Scanner in; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int k = ni(); int a = ni(); int[] lv = new int[n]; int[] lo = new int[n]; for(int i = 0;i < n;i++){ lv[i] = ni(); lo[i] = ni(); } out.printf("%.9f", rec(lv, lo, n, 0, k, a)); } double rec(int[] lv, int[] lo, int n, int pos, int k, int a) { if(pos == n){ int h = n/2+1; double gp = 0; for(int i = 0;i < 1<<n;i++){ if(Integer.bitCount(i) >= h){ double p = 1.0; for(int j = 0;j < n;j++){ if(i<<31-j<0){ p *= (double)lo[j] / 100; }else{ p *= (double)(100-lo[j]) / 100; } } gp += p; }else{ double p = 1.0; int sl = 0; for(int j = 0;j < n;j++){ if(i<<31-j<0){ p *= (double)lo[j] / 100; }else{ p *= (double)(100-lo[j]) / 100; sl += lv[j]; } } gp += p * a/(a+sl); } } return gp; }else{ int o = lo[pos]; double max = 0; for(int i = 0;i <= k && lo[pos] <= 100;i++){ max = Math.max(max, rec(lv, lo, n, pos+1, k-i, a)); lo[pos]+=10; } lo[pos] = o; return max; } } void run() throws Exception { in = oj ? new Scanner(System.in) : new Scanner(INPUT); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new B().run(); } int ni() { return Integer.parseInt(in.next()); } long nl() { return Long.parseLong(in.next()); } double nd() { return Double.parseDouble(in.next()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
np
105_B. Dark Assembly
CODEFORCES
/** * Created by IntelliJ IDEA. * User: Taras_Brzezinsky * Date: 8/13/11 * Time: 6:10 PM * To change this template use File | Settings | File Templates. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.io.IOException; public class DarkAssembly extends Thread { public DarkAssembly() { this.input = new BufferedReader(new InputStreamReader(System.in)); this.output = new PrintWriter(System.out); this.setPriority(Thread.MAX_PRIORITY); } static class Senator { int loyalty; int level; public Senator(int level, int loyalty) { this.level = level; this.loyalty = loyalty; } } private static double doIt(Senator[] senators, int A) { double probability = .0; for (int mask = 0; mask < (1 << senators.length); ++mask) { int sum = A; double current = 1.0; for (int i = 0; i < senators.length; ++i) { if ((mask & (1 << i)) != 0) { current *= .01 * senators[i].loyalty; } else { current *= .01 * (100 - senators[i].loyalty); sum += senators[i].level; } } if (Integer.bitCount(mask) > senators.length / 2) { probability += current; } else { probability += current * (double) A / sum; } } return probability; } private static double go(Senator[] senators, int candies, int A, int current) { if (current == senators.length) { return doIt(senators, A); } else { double result = go(senators, candies, A, current + 1); if (candies > 0 && senators[current].loyalty < 100) { senators[current].loyalty += 10; result = Math.max(result, go(senators, candies - 1, A, current)); senators[current].loyalty -= 10; } return result; } } private void solve() throws Throwable { int n = nextInt(); int k = nextInt(); int A = nextInt(); Senator[] senators = new Senator[n]; for (int i = 0; i < n; ++i) { senators[i] = new Senator(nextInt(), nextInt()); } output.printf("%.10f", go(senators, k, A, 0)); } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { output.flush(); output.close(); } } public static void main(String[] args) { new DarkAssembly().start(); } private String nextToken() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private BufferedReader input; private PrintWriter output; private StringTokenizer tokens = null; }
np
105_B. Dark Assembly
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ out.println(work()); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } long work() { int n=in.nextInt(); int m=in.nextInt(); String str=in.next(); long[] dp=new long[1<<m]; long[][] cnt=new long[m][m]; long[] rec=new long[1<<m]; for(int i=1;i<n;i++) { int n1=str.charAt(i-1)-'a'; int n2=str.charAt(i)-'a'; cnt[n1][n2]++; cnt[n2][n1]++; } for(int i=1;i<1<<m;i++) { dp[i]=9999999999L; long v=0; int b=0;//最低位的1 for(int j=0;j<m;j++) { if((i&(1<<j))>0) { b=j; break; } } for(int j=0;j<m;j++) { if((i&(1<<j))==0) { v+=cnt[b][j]; }else { if(b!=j)v-=cnt[b][j]; } } v+=rec[i-(1<<b)]; for(int j=0;j<m;j++) { if((i&(1<<j))>0) { dp[i]=Math.min(dp[i], dp[i-(1<<j)]+v); } } rec[i]=v; } return dp[(1<<m)-1]; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.io.*; import java.math.BigInteger; import static java.math.BigInteger.*; import java.util.*; public class Solution{ void solve()throws Exception { int n=nextInt(); int[]a=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); int[]b=a.clone(); Arrays.sort(b); int cnt=0; for(int i=0;i<n;i++) if(a[i]!=b[i]) cnt++; if(cnt<=2) System.out.println("YES"); else System.out.println("NO"); } private boolean sorted(int[] a) { for(int i=0;i+1<a.length;i++) if(a[i]>a[i+1]) return false; return true; } //////////// BufferedReader reader; PrintWriter writer; StringTokenizer stk; void run()throws Exception { reader=new BufferedReader(new InputStreamReader(System.in)); // reader=new BufferedReader(new FileReader("input.txt")); stk=null; writer=new PrintWriter(new PrintWriter(System.out)); //writer=new PrintWriter(new FileWriter("output.txt")); solve(); reader.close(); writer.close(); } int nextInt()throws Exception { return Integer.parseInt(nextToken()); } long nextLong()throws Exception { return Long.parseLong(nextToken()); } double nextDouble()throws Exception { return Double.parseDouble(nextToken()); } String nextString()throws Exception { return nextToken(); } String nextLine()throws Exception { return reader.readLine(); } String nextToken()throws Exception { if(stk==null || !stk.hasMoreTokens()) { stk=new StringTokenizer(nextLine()); return nextToken(); } return stk.nextToken(); } public static void main(String[]args) throws Exception { new Solution().run(); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.io.*; import java.util.*; public class Lcm { public static void main(String args[])throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); long n=Long.parseLong(br.readLine()); if(n<=2) System.out.println(n); else { if(n%6==0) { System.out.println(((n-1)*(n-2)*(n-3))); } else if(n%2==0) { System.out.println((n*(n-1)*(n-3))); } else { System.out.println((n*(n-1)*(n-2))); } } } }
constant
235_A. LCM Challenge
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B { public static void main(String[] args){ FastScanner sc = new FastScanner(); long n = sc.nextLong(); int k = sc.nextInt(); if(n==1){ System.out.println(0); return; } n=n-1; int count = 0; long nextK = k-1; while(true){ //System.out.println("n = " + n); if(nextK < 1 || (nextK <= 1 && n >1)){ System.out.println(-1); return; } nextK = Math.min(n, nextK); if(n==nextK){ System.out.println(count+1); return; } //System.out.println("nextK = " + nextK); //search for a of a...nextK long bSum = nextK * (nextK+1)/2; long a = nextK; long decrement = 1; while(bSum - (a-1)*a/2 <= n && a>=1){ a-= decrement; decrement *= 2; } a+=decrement/2; //System.out.println("a = " + a); count += nextK-a+1; //System.out.println("count = " + count); long nDecr = bSum-a*(a-1)/2; //System.out.println("bSum = " + bSum); //System.out.println("nDecr = " + nDecr); n -= nDecr; nextK = a-1; if(n==0){ System.out.println(count); return; } } } public 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()); } } }
logn
287_B. Pipeline
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class Main { public static class pair implements Comparable<pair> { int a; int b; public pair(int pa, int pb) { a = pa; b= pb; } @Override public int compareTo(pair o) { if(this.a < o.a) return -1; if(this.a > o.a) return 1; return Integer.compare(o.b, this.b); } } //int n = Integer.parseInt(in.readLine()); //int n = Integer.parseInt(spl[0]); //String[] spl = in.readLine().split(" "); public static void main (String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] spl = in.readLine().split(" "); long l = Long.parseLong(spl[0]); long r = Long.parseLong(spl[1]); if(l+2 <= r && l%2==0) { System.out.println(l+" "+(l+1)+" "+(l+2)); } else if(l+3<=r && (l+1)%2==0) { System.out.println((l+1)+" "+(l+2)+" "+(l+3)); } else System.out.println(-1); } }
constant
483_A. Counterexample
CODEFORCES
import java.util.*; public class Solution{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int pairs = in.nextInt(); while (pairs > 0){ in.nextLine(); int a = in.nextInt(); int b = in.nextInt(); int count = 0; while (a != 0 && b != 0){ if (b >= a && a != 0){ count += b/a; b = b%a; } if (a > b && b != 0){ count += a/b; a = a%b; } } System.out.println(count); pairs--; } } }
constant
267_A. Subtractions
CODEFORCES