src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Arrays; import java.util.StringTokenizer; public class A { public static void main(String[] args) { try (final Scanner sc = new Scanner(System.in)) { System.out.println(25); } } public static class Scanner implements Closeable { private BufferedReader br; private StringTokenizer tok; public Scanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } private void getLine() { try { while (!hasNext()) { tok = new StringTokenizer(br.readLine()); } } catch (IOException e) { /* ignore */ } } private boolean hasNext() { return tok != null && tok.hasMoreTokens(); } public String next() { getLine(); return tok.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public void close() { try { br.close(); } catch (IOException e) { /* ignore */ } } } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.util.Map; import java.io.BufferedReader; import java.io.FileReader; 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public int[] parse(FastScanner in, int n) { String s = in.next(); int[] temp = new int[n]; for (int i = 0; i < n; ++i) { temp[i] = s.charAt(i) - 'A'; } return temp; } public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int[] s = parse(in, n); Map<Integer, TreeSet<Integer>> map = new HashMap<>(); for (int i = 0; i < n; ++i) { if (map.containsKey(s[i])) { map.get(s[i]).add(i); } else { TreeSet<Integer> temp = new TreeSet<>(); temp.add(i); map.put(s[i], temp); } } int ans = Integer.MAX_VALUE; for (int i = 0; i < n; ++i) { int finalI = i; final Int integer = new Int(); integer.x = i; map.forEach((Integer x, TreeSet set) -> { if (x != s[finalI]) { Integer temp = (Integer) set.higher(finalI); if (temp == null) { integer.x = -2; } else { if (integer.x != -2) integer.x = Integer.max(integer.x, temp); } } else { } }); if (integer.x != -2) { ans = Integer.min(ans, integer.x - i + 1); } } out.print(ans); } public class Int { int x; public Int() { x = -1; } } } static class FastScanner { private BufferedReader br; private StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int r = sc.nextInt(); int d = 2 * r; int[] xCoordinates = new int[n]; double[] yCoordinates = new double[n]; for (int i = 0; i < n; i++) yCoordinates[i] = r; for (int i = 0; i < n; i++) xCoordinates[i] = sc.nextInt(); double y = 0; for (int i = 0; i < n; i++) { y = r; for (int j = 0; j < i; j++) { if (Math.abs(xCoordinates[i] - xCoordinates[j]) <= 2 * r) { int dx = Math.abs(xCoordinates[i] - xCoordinates[j]); double dy = Math.sqrt(d * d - dx * dx); if (dy + yCoordinates[j] > y) y = dy + yCoordinates[j]; } } yCoordinates[i]=y; } for (int i = 0; i < n; i++) System.out.print(yCoordinates[i] + " "); sc.close(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; public class Codeforces911D { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] sp = br.readLine().split(" "); int n = Integer.parseInt(sp[0]); int[] a = new int[n]; sp = br.readLine().split(" "); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(sp[i]); } int inversions = 0; for (int i = 0; i < n-1; i++) { for (int j = i+1; j < n; j++) { if (a[i] > a[j]) { inversions++; } } } inversions = inversions%2; sp = br.readLine().split(" "); int m = Integer.parseInt(sp[0]); for (int i = 0; i < m; i++) { sp = br.readLine().split(" "); int l = Integer.parseInt(sp[0]); int r = Integer.parseInt(sp[1]); if ((r-l+1)%4 == 2 || (r-l+1)%4 == 3) { inversions = 1-inversions; } if (inversions == 1) { System.out.println("odd"); } else { System.out.println("even"); } } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Scanner; public class A { public static void main(String[] args) throws Exception { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); List<Integer> list = new ArrayList<Integer>(), list2; for (; n-- > 0;) { list.add(scan.nextInt()); } list2 = new ArrayList<Integer>(list); Collections.sort(list2, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o1 % 2 - o2 % 2; } }); System.out.println(list.indexOf(list2.get(list2.get(1) % 2 > 0 ? 0 : list2.size() - 1)) + 1); } }
linear
25_A. IQ test
CODEFORCES
import java.awt.*; import java.io.*; import java.math.*; import java.util.*; public class TaskC { public static void main(String[] args) { new TaskC().run(); } void solve(){ int n = in.nextInt(); String s[] = new String[n]; for(int i = 0; i < n; i++) s[i] = in.next(); if(s[n-1].compareTo("f") == 0){ out.println(0); return; } int dp[] = new int[n+2]; int mod = 1000*1000*1000+7; dp[0] = 1; for(int i = n-1; i >= 0; i--){ if(s[i].compareTo("s") == 0){ int ss = 0; for(int j = 0; j <= n; j++){ ss += dp[j]; if(ss>=mod) ss -= mod; dp[j] = ss; } }else{ for(int j = 0; j < n;j++){ dp[j] = dp[j+1]; } dp[n] = 0; } } out.println(dp[0]); } FastScanner in; PrintWriter out; void run() { in = new FastScanner(System.in); out = new PrintWriter(System.out); int tests = 1;//in.nextInt(); while(tests > 0){ solve(); tests--; } out.close(); } class Pair implements Comparable<Pair>{ Integer x, y; public Pair(int x, int y){ this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if(x.compareTo(o.x) == 0) return y.compareTo(o.y); return x.compareTo(o.x); } } class FastScanner { StringTokenizer st; BufferedReader bf; public FastScanner(InputStream is) { bf = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f){ try{ bf = new BufferedReader(new FileReader(f)); } catch(IOException ex){ ex.printStackTrace(); } } String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(bf.readLine()); } catch(Exception ex){ ex.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } int[] readArray(int n){ int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } } }
quadratic
909_C. Python Indentation
CODEFORCES
//package Round14Global; import java.util.*; import java.io.*; public class phoenixandpuzzle { public static void main(String[] args) throws IOException { BufferedReader fin = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(fin.readLine()); StringBuilder fout = new StringBuilder(); HashSet<Integer> dict = new HashSet<Integer>(); int pointer = 1; int area = 0; while(area >= 0) { area = (pointer * pointer) * 2; dict.add(area); pointer ++; } pointer = 1; area = 0; while(area >= 0) { area = (pointer * pointer) * 4; dict.add(area); pointer ++; } while(t-- > 0) { int n = Integer.parseInt(fin.readLine()); if(dict.contains(n)) { fout.append("YES\n"); } else { fout.append("NO\n"); } } System.out.print(fout); } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.util.*; public class Main{ public static void main(String args[]){ Scanner in = new Scanner(System.in); int a[]={4,7,44,47,74,77,444,447,474,477,744,747,774,777}; int n=in.nextInt(); int i=0; boolean yes=false; while((i<14)&&(a[i]<=n)){ if(n%a[i]==0){ System.out.print("YES"); yes=true; break; } i++; } if(!yes) System.out.print("NO"); } }
constant
122_A. Lucky Division
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); int nums[] = new int[n]; StringTokenizer tokenizer = new StringTokenizer(in.readLine(), " "); for (int i = 0; i < n; i++) { nums[i] = Integer.parseInt(tokenizer.nextToken()); } Arrays.sort(nums); int min = nums[0]; int so = -200; for (int i = 1; i < n; i++) { if(nums[i] != min) { so = nums[i]; break; } } if(so != -200) System.out.println(so); else System.out.println("NO"); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); team[] t = new team[n]; for (int i = 0; i < n; i++) t[i] = new team(in.nextInt(), in.nextInt()); Arrays.sort(t); int cnt = 0; team tm = t[t.length - k]; for (int i = t.length - 1; i >= 0; i--) if (tm.equal(t[i])) cnt++; System.out.println(cnt); } static class team implements Comparable<team> { int p, t; public team(int pp, int tt) { p = pp; t = tt; } @Override public int compareTo(team o) { if (p == o.p) return o.t - t; return p - o.p; } public boolean equal(team a) { return a.p == p && a.t == t; } } }
nlogn
166_A. Rank List
CODEFORCES
import java.util.Scanner; public class Main { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(),c; int n = s.length(),a,b; for(int sz = n ; sz >= 1 ; sz--) { for(int i = 0 ; i+sz <= n ; i++) { c = s.substring(i, i+sz); a = s.indexOf(c,0); if(a < 0) continue; b = s.indexOf(c,a+1); if(b < 0) continue; System.out.println(sz); return; } // for j } // for i System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.PrintWriter; import java.util.Scanner; public class n122A { Scanner in; PrintWriter out; void solve() { int n = in.nextInt(); boolean good = false; if (n % 4 == 0) { good = true; } if (n % 7 == 0) { good = true; } if (n % 44 == 0) { good = true; } if (n % 47 == 0) { good = true; } if (n % 74 == 0) { good = true; } if (n % 77 == 0) { good = true; } if (n % 444 == 0) { good = true; } if (n % 447 == 0) { good = true; } if (n % 474 == 0) { good = true; } if (n % 477 == 0) { good = true; } if (n % 744 == 0) { good = true; } if (n % 747 == 0) { good = true; } if (n % 774 == 0) { good = true; } if (n % 777 == 0) { good = true; } if (good) { out.println("YES"); } else { out.println("NO"); } } void run() { in = new Scanner(System.in); out = new PrintWriter(System.out); try { solve(); } finally { out.close(); } } public static void main(String[] args) { new n122A().run(); } }
constant
122_A. Lucky Division
CODEFORCES
import java.util.*; import java.io.*; public class B { public static void main(String[] args) { FastScanner sc = new FastScanner(); int T = sc.nextInt(); while(T-->0) { int n = sc.nextInt(); if(n % 2 == 0 && issq(n/2)) { System.out.println("YES"); } else if(n % 4 == 0 && issq(n/4)) { System.out.println("YES"); } else { System.out.println("NO"); } } } static boolean issq(long x) { long rx = (long)Math.sqrt(x); return rx * rx == x; } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class Code implements Runnable { public static void main(String[] args) throws IOException { new Thread(new Code()).start(); } private void solve() throws IOException { taskB(); } private void taskB() throws IOException { int n = nextInt(), k = nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; ++i) arr[i] = nextInt(); int i = 0; while(i < n - 1 && arr[i] == arr[i + 1]) ++i; if(k == 1) writer.println(1 + " " + 1); else if(k == 2 && i == n - 2) writer.println(n - 1 + " " + n); else { if(i == n - 1) writer.println(-1 + " " + -1); else { int l = i; Map<Integer, Integer> set = new HashMap<Integer, Integer>(n); while(i < n && set.size() < k) { if(set.containsKey(arr[i])) set.put(arr[i], set.get(arr[i]) + 1); else set.put(arr[i], 1); i += 1; } if(set.size() < k) writer.println(-1 + " " + -1); else { while(l < i && i - l > k && set.get(arr[l]) > 1) { set.put(arr[l], set.get(arr[l]) - 1); l += 1; } writer.println((l + 1) + " " + i); } } } } private class Pair<E extends Comparable, V extends Comparable> implements Comparable<Pair<E, V>> { public Pair(E first, V second) { this.first = first; this.second = second; } @Override public int compareTo(Pair<E, V> obj) { if(first.equals(obj.first)) return second.compareTo(obj.second); return first.compareTo(obj.first); } @Override public boolean equals(Object obj) { Pair other = (Pair)obj; return first.equals(other.first) && second.equals(other.second); } public E first; public V second; } @Override public void run() { try { if(in.equals("")) reader = new BufferedReader(new InputStreamReader(System.in)); else reader = new BufferedReader(new FileReader(in)); if(out.equals("")) writer = new PrintWriter(new OutputStreamWriter(System.out)); else writer = new PrintWriter(new FileWriter(out)); solve(); } catch(IOException e) { e.printStackTrace(); } finally { try { reader.close(); writer.close(); } catch(IOException e) { e.printStackTrace(); } } } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private float nextFloat() throws IOException { return Float.parseFloat(nextToken()); } private String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(reader.readLine()); return st.nextToken(); } private String in = "", out = ""; private BufferedReader reader; private PrintWriter writer; private StringTokenizer st; }
linear
224_B. Array
CODEFORCES
import java.io.*; import java.util.*; public class CF { long mod = (long) 1e9 + 9; class Pair { long a, b; public Pair(long a, long b) { super(); this.a = a % mod; this.b = b % mod; } } int k; long pow(long n, long k) { if (k == 0) return 1; long m1 = pow(n, k / 2); m1 = (m1 * m1) % mod; if (k % 2 != 0) m1 = (m1 * n) % mod; return m1; } long st(int n, int m, int k) { int parts = n / k; int used = n - m; if (parts > n - m) { long cur = 0; int counter = 0; int need = parts - (n - m); for (int i = 1; i <= n; i++) { if (counter + 1 == k && need <= 0) { counter = 0; used--; } else { counter++; cur++; if (counter == k) { counter = 0; cur = (cur * 2) % mod; need--; } } } if (used < 0) throw new AssertionError(); return cur; } else { return m; } } long mysol(int n, int m, int k) { this.k = k; int parts = n / k; if (parts > n - m) { long ost = n - (n - m) * k; long power = ost / k; long res = pow(2, power + 1); long cur = ((res - 2 + mod) % mod) * k; cur %= mod; cur += Math.max(0, m - power * k); cur %= mod; return cur; } else { return m; } } void realSolve() throws IOException { int n = in.nextInt(); int m = in.nextInt(); k = in.nextInt(); out.println(mysol(n, m, k)); /*Random rnd = new Random(123); for (int t = 0; t < 10000; t++) { System.err.println(t); int n = rnd.nextInt(100) + 2; int m = rnd.nextInt(n + 1); int k = rnd.nextInt(n - 1) + 2; if (t == 16) { System.err.println("!"); } long r1 = mysol(n, m, k); long r2 = st(n, m, k); if (r1 != r2) throw new AssertionError(r1 + " " + r2); }*/ } private class InputReader { StringTokenizer st; BufferedReader br; public InputReader(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreElements()) { String s; try { s = br.readLine(); } catch (IOException e) { return null; } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } boolean hasMoreElements() { while (st == null || !st.hasMoreElements()) { String s; try { s = br.readLine(); } catch (IOException e) { return false; } st = new StringTokenizer(s); } return st.hasMoreElements(); } long nextLong() { return Long.parseLong(next()); } } InputReader in; PrintWriter out; void solveIO() throws IOException { in = new InputReader(System.in); out = new PrintWriter(System.out); realSolve(); out.close(); } void solve() throws IOException { in = new InputReader(new File("input.txt")); out = new PrintWriter(new File("output.txt")); realSolve(); out.close(); } public static void main(String[] args) throws IOException { new CF().solveIO(); } }
logn
338_A. Quiz
CODEFORCES
import java.io.*; import java.util.*; public class Main { static Scanner in; static PrintWriter out; // static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;} public static void main(String[] args) throws Exception { in = new Scanner(System.in); out = new PrintWriter(System.out); // in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); String s = in.next(); int n = s.length(); int max = 0; for (int i = 1; i < n; i++) { String[] subs = new String[n - i + 1]; for (int j = 0; j + i <= n; j++) subs[j] = s.substring(j, j + i); Arrays.sort(subs); boolean flag = false; for (int j = 0; j < n - i; j++) if (subs[j].equals(subs[j + 1])) flag = true; if (flag) max = Math.max(max, i); } out.println(max); out.close(); } }
cubic
23_A. You're Given a String...
CODEFORCES
/* ID: andrew42 LANG: JAVA TASK: PROG: */ import java.io.*; import java.util.*; import java.lang.*; public class curling { public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); int numD = input.nextInt(); double rad = input.nextInt(); int[] xC = new int[numD]; for (int i = 0; i < numD; i++){ xC[i] = input.nextInt(); } double[] maxY = new double[1001]; for (int i = 0; i < numD; i++){ double h = rad; for (int j = Math.max(1, xC[i]-(int)(2*rad)); j <= Math.min(1000, xC[i]+2*rad); j++){ if (maxY[j] > 0){ h = Math.max(h, Math.sqrt(4*rad*rad-(j-xC[i])*(j-xC[i]))+maxY[j]); } } System.out.print(h + " "); maxY[xC[i]] = h; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.util.regex.*; import java.text.*; import java.math.*; public class Main { Scanner cin; int []prime; int top; void work() { cin=new Scanner(System.in); int n=cin.nextInt(); int k=cin.nextInt(); top=0; prime=new int[2000]; for(int i=2;i<=n;i++) { if(isprime(i)) prime[top++]=i; } int cnt=0; for(int i=0;i<top;i++) { if(cando(prime[i])) cnt++; } if(cnt>=k) System.out.println("YES"); else System.out.println("NO"); } boolean cando(int n) { for(int i=0;i<top-1;i++) { if(prime[i]+prime[i+1]+1==n) return true; } return false; } boolean isprime(int n) { for(int i=2;i*i<=n;i++) if(n%i==0)return false; return true; } public static void main(String args[]) throws Exception { new Main().work(); } }
linear
17_A. Noldbach problem
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class Round364C { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(System.in); n = sc.nextInt(); k = 0; String line = sc.nextLine(); ArrayList<Character> poks = new ArrayList<Character>(); boolean ex[] = new boolean[256]; for(int i=0; i<n; i++) { if(!ex[line.charAt(i)]) { ex[line.charAt(i)] = true; poks.add(line.charAt(i)); } } int l = 0; int r = 0; int dist = 1; int occ[] = new int[256]; occ[line.charAt(0)] = 1; int min = n; while(r < n) { if(dist == poks.size()) min = Math.min(min, r - l + 1); if(l < r && dist == poks.size()) { occ[line.charAt(l)]--; if(occ[line.charAt(l)] == 0) dist--; l++; continue; } if(r < n-1){ occ[line.charAt(r+1)]++; if(occ[line.charAt(r+1)] == 1) dist++; } r++; } System.out.println(min); } static int n,k; static int dp[][][]; static class Scanner { BufferedReader br; StringTokenizer st; Scanner(FileReader f) { br = new BufferedReader(f); } public boolean ready() throws IOException { return br.ready(); } Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.util.*; import java.io.*; public class Quiz { public static final int MOD = 1000000009; public static void main(String[] args) { Scanner in = new Scanner(System.in); long n = in.nextInt(); long m = in.nextInt(); long k = in.nextInt(); long low = Math.min(n - (k * (n - m)), m); if(low < 0) { low = 0; } long result = 0; if(low >= k) { long b = low / k; result += fastExp(2, b + 1); result -= 2; if(result < 0) { result += MOD; } result *= k; result %= MOD; } result += low % k; result %= MOD; result += m - low; result %= MOD; // System.out.println(low); System.out.println(result); } public static long fastExp(int x, long pow) { if(pow == 0) { return 1; } long result = fastExp(x, pow / 2); result *= result; result %= MOD; if(pow % 2 == 1) { result *= x; result %= MOD; } return result; } }
logn
338_A. Quiz
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Vadim Semenov */ 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 final class TaskC { private static final int MODULO = 1_000_000_000 + 7; public void solve(int __, InputReader in, PrintWriter out) { long qty = in.nextLong(); long months = in.nextLong(); if (qty == 0) { out.println(0); return; } qty %= MODULO; long pow = pow(2, months + 1); qty = (qty * pow) % MODULO; long sub = (pow - 2 + MODULO) % MODULO * pow(2, MODULO - 2) % MODULO; qty = (qty - sub + MODULO) % MODULO; out.println(qty); } private long pow(long base, long power) { long result = 1; while (power > 0) { if ((power & 1) != 0) { result = (result * base) % MODULO; } base = (base * base) % MODULO; power >>>= 1; } return result; } } static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public long nextLong() { return Long.parseLong(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } public String readLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
//package round85; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class C3 { Scanner in; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int m = ni(); if(n < m){ int d = n;n = m;m = d; } // n>=m if(m == 1){ out.println(n-(n+2)/3); return; } int[][] dp = new int[n+1][1<<2*m]; int[] fill = new int[1<<m]; int mask = (1<<m)-1; for(int i = 0;i < 1<<m;i++){ fill[i] = (i<<1|i|i>>1)&mask; } for(int i = 0;i < 1<<2*m;i++){ int lower = i&mask; int upper = i>>m; dp[0][i] = (fill[lower]|upper) == mask ? Integer.bitCount(i) : 99999; } for(int i = 1;i <= n-2;i++){ for(int j = 0;j < 1<<2*m;j++){ int lower = j&mask; int upper = j>>m; int min = 99999; for(int k = 0;k < 1<<m;k++){ if((upper|fill[lower]|k) == mask){ min = Math.min(min, dp[i-1][lower<<m|k]); } } dp[i][j] = min + Integer.bitCount(upper); } } int gmin = 99999; for(int i = 0;i < 1<<2*m;i++){ int lower = i&mask; int upper = i>>m; if((fill[upper]|lower) == mask){ gmin = Math.min(gmin, dp[n-2][i]); } } out.println(n*m-gmin); } 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 C3().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
111_C. Petya and Spiders
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { void solve() throws Exception { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int a [] = new int [n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } Arrays.sort(a); if (k >= m) { out.println(0); return; } int sum = k; for (int j = n - 1; j >= 0; j--) { sum--; sum += a[j]; if (sum >= m) { out.println((n - j)); return; } } out.println(-1); } BufferedReader in; PrintWriter out; FastScanner sc; static Throwable uncaught; @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); solve(); } catch (Throwable t) { Solution.uncaught = t; } finally { out.close(); } } public static void main(String[] args) throws Throwable { Thread t = new Thread(null, new Solution(), "", (1 << 26)); t.start(); t.join(); if (uncaught != null) { throw uncaught; } } } class FastScanner { BufferedReader reader; StringTokenizer strTok; public FastScanner(BufferedReader reader) { this.reader = reader; } public String nextToken() throws IOException { while (strTok == null || !strTok.hasMoreTokens()) { strTok = new StringTokenizer(reader.readLine()); } return strTok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
nlogn
257_A. Sockets
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.InputMismatchException; public class Solution1 implements Runnable { static final long MAX = 1000000007L; 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); } } public static void main(String args[]) throws Exception { new Thread(null, new Solution1(),"Solution1",1<<26).start(); } long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } // method to return LCM of two numbers long lcm(long a, long b) { return (a*b)/gcd(a, b); } int root(int a){ while(arr[a] != a){ arr[a] = arr[arr[a]]; a = arr[a]; } return a; } void union(int a,int b){ int xroot = root(a); int yroot = root(b); if(arr[xroot] < arr[yroot]){ arr[xroot] = yroot; }else{ arr[yroot] = xroot; } } boolean find(int a,int b){ int roota = root(a); int rootb = root(b); if(roota == rootb){ return true; }else{ return false; } } int[] arr; final int level = 20; public void run() { InputReader sc= new InputReader(System.in); PrintWriter w= new PrintWriter(System.out); int n = sc.nextInt(); char[] ch = new char[n]; char[] ch2 = new char[n]; ch = sc.next().toCharArray(); ch2 = sc.next().toCharArray(); HashSet<Integer> hset[] = new HashSet[26]; for(int i = 0;i < 26;i++){ hset[i] =new HashSet(); } int count = 0; for(int i = 0;i < ch.length;i++){ if(ch[i] != ch2[i]){ hset[ch[i]-97].add(ch2[i]-97); count++; } } boolean flag = false; int swap1 = -1; int swap2 = -1; int rem = -1; for(int i = 0;i < ch.length;i++){ if(ch[i] != ch2[i]){ if(hset[ch2[i]-97].size() != 0){ swap1 = i; flag = true; if(hset[ch2[i]-97].contains(ch[i]-97)){ rem = i; count-=2; flag = false; break; } } } } if(flag){ count--; w.println(count); for(int i = 0;i < n;i++){ if(i != swap1 && ch[i] == ch2[swap1] && ch[i] != ch2[i]){ w.println((swap1+1) + " " + (i+1)); w.close(); System.exit(0); } } }else{ if(rem == -1){ w.println(count); w.println("-1 -1"); }else{ w.println(count); for(int i = 0;i < n;i++){ if(i != rem && ch[i] == ch2[rem] && ch[rem] == ch2[i] && ch[i] != ch2[i]){ w.println((rem+1) + " " + (i+1)); w.close(); System.exit(0); } } } } w.close(); } boolean fun(long[] prefix,long mid,long temp,long[] arr){ if(temp >= prefix[(int)mid]){ return true; } return false; } static class Pair implements Comparable<Pair>{ int x; int y; Pair(){} Pair(int x,int y){ this.x = x; this.y = y; } public int compareTo(Pair p){ return Long.compare(this.x,p.x); } } }
linear
527_B. Error Correct System
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class _P023A{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; String s; void run(){ s=sc.nextLine(); solve(); } void solve(){ int n=s.length(); int max=0; for(int i=0; i<n; i++){ for(int j=i+1; j<n; j++){ for(int k=0; j+k<n; k++){ if(s.charAt(i+k)!=s.charAt(j+k)){ break; }else{ max=max(max, k+1); } } } } println(max+""); } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } public static void main(String[] args){ Locale.setDefault(Locale.US); new _P023A().run(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.text.DecimalFormat; public class ProblemD { private double survive(int round, int set) { if (sur[round][set] >= 0) return sur[round][set]; double res = 0.0; int count = 0; for(int i=0;i<n;i++) { if ((set & (1 << i)) > 0) { double res2 = 0.0; for(int j=0;j<n;j++) if ((set & (1 << j)) == 0) { res2 += survive(round - 1, set + (1 << j)) * a[i][j]; count++; } res += res2; } } count = (n-round+1) * (n - round) / 2; sur[round][set] = res / count; return sur[round][set]; } int n; double[][] a, sur; public void solve() { boolean oj = true; try { Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("inputD.txt"); Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("outputD.txt"); BufferedReader br = new BufferedReader(reader); PrintWriter out = new PrintWriter(writer); MyTokenizer tok = new MyTokenizer(br.readLine()); n = (int)tok.getNum(); a = new double[n][n]; int all = (1 << n) - 1; sur = new double[n][all + 1]; for(int i=0;i<n;i++) { tok = new MyTokenizer(br.readLine()); for(int j=0;j<n;j++) { a[i][j] = tok.getNum(); } for(int j=0;j<=all;j++) sur[i][j] = -1; } DecimalFormat format = new DecimalFormat("0.000000"); sur[0][all] = 1; double[] res = new double[n]; for(int i=0;i<n;i++) { res[i] = survive(n - 1, 1 << i); String sres = format.format(res[i]).replace(',','.'); out.printf("%s ", sres); } br.close(); out.close(); reader.close(); writer.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { } } public static void main(String[] args) { ProblemD f = new ProblemD(); f.solve(); } private class MyTokenizer { private String s; private int cur; public MyTokenizer(String s) { this.s = s; cur = 0; } public void skip() { while (cur < s.length() && (s.charAt(cur) == ' ' || s.charAt(cur) == '\n')) { cur++; } } public double getNum() { skip(); String snum = ""; while (cur < s.length() && (s.charAt(cur) >= '0' && s.charAt(cur) <= '9' || s.charAt(cur) == '.')) { snum += s.charAt(cur); cur++; } return Double.valueOf(snum); } public String getString() { skip(); String s2 = ""; while (cur < s.length() && (s.charAt(cur) >= 'a' && s.charAt(cur) <= 'z')) { s2 += s.charAt(cur); cur++; } return s2; } public char getCurrentChar() throws Exception { if (cur < s.length()) return s.charAt(cur); else throw new Exception("Current character out of string length"); } public void moveNextChar() { if (cur < s.length()) cur++; } public boolean isFinished() { return cur >= s.length(); } } }
np
16_E. Fish
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class CF1141F { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] split = br.readLine().split(" "); int[] terms = new int[n]; int[] sums = new int[n+1]; for(int i=0; i<n; i++) { terms[i] = Integer.parseInt(split[i]); sums[i+1] = sums[i]+terms[i]; } ArrayList<Block> blocks = new ArrayList<>(); for(int i=0; i<n; i++) for(int j=i; j<n; j++){ int s = sums[j+1]-sums[i]; blocks.add(new Block(i, j, s)); } Collections.sort(blocks); ArrayList<Block> best = new ArrayList<>(); int i = 0; while(i<blocks.size()){ int curSum = blocks.get(i).sum; ArrayList<Block> curBlocks = new ArrayList<>(); while(i<blocks.size() && blocks.get(i).sum==curSum) curBlocks.add(blocks.get(i++)); int[] memo = new int[curBlocks.size()+1]; Arrays.fill(memo, -1); memo[curBlocks.size()] = 0; for(int j=curBlocks.size()-1; j>=0; j--){ int idx = Collections.binarySearch(curBlocks, new Block(curBlocks.get(j).r+1, curBlocks.get(j).r+1, curBlocks.get(j).sum)); if(idx<0) idx = -(idx+1); memo[j] = Math.max(memo[j+1], 1+memo[idx]); } if(memo[0]>best.size()){ best = new ArrayList<>(); int idx = 0; while(memo[idx]>=1){ if(memo[idx]>memo[idx+1]) best.add(curBlocks.get(idx)); idx++; } } } StringBuilder sb = new StringBuilder(); sb.append(best.size()).append("\n"); for(Block b : best){ sb.append(b.l+1).append(" ").append(b.r+1).append("\n"); } System.out.print(sb); } static class Block implements Comparable<Block>{ int l, r, sum; Block(int a, int b, int c){ l = a; r = b; sum = c; } @Override public int compareTo(Block o) { if(sum==o.sum){ if(l==o.l) return r-o.r; return l-o.l; } return sum-o.sum; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
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.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class A { static int dx[] = { 1, -1, 0, 0 }; static int dy[] = { 0, 0, 1, -1 }; public static void main(String args[]) throws Exception { Scanner sc = new Scanner("input.txt"); PrintWriter out = new PrintWriter("output.txt"); int n = sc.nextInt(), m = sc.nextInt(); int[][] grid = new int[n][m]; for (int[] i : grid) Arrays.fill(i, -1); Queue<Pair> q = new LinkedList<>(); int k = sc.nextInt(); for (int i = 0; i < k; i++) { int x = sc.nextInt() - 1, y = sc.nextInt() - 1; grid[x][y] = 0; q.add(new Pair(x, y)); } Pair p = new Pair(-1, -1); while (!q.isEmpty()) { p = q.poll(); for (int i = 0; i < dx.length; i++) { int tx = p.x + dx[i], ty = p.y + dy[i]; if (tx >= 0 && tx < n && ty >= 0 && ty < m && grid[tx][ty] == -1) { grid[tx][ty] = grid[p.x][p.y] + 1; q.add(new Pair(tx, ty)); } } } out.println(p); out.flush(); out.close(); } static class Pair { int x, y; public Pair(int a, int b) { x = a; y = b; } public String toString() { return x + 1 + " " + (y + 1); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String r) throws FileNotFoundException { br = new BufferedReader(new FileReader(r)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.*; import java.util.*; public class Solution { public static void main (String[] args) throws IOException { boolean online = "true".equals(System.getProperty("ONLINE_JUDGE")); if (online) { in = new InputReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new InputReader(new FileReader("input.txt")); out = new PrintWriter(new File("output.txt")); } new Solution().run(); out.close(); } long sum (int x) { return x * 1l * (x+1) / 2; } int bins (long n, int k) { int l = 1, r = k; while (l < r) { int w = (l+r)/2; long s = sum(k) - sum(w-1); if (s == n) return w; if (s < n) r = w; else l = w+1; } return l; } private void run () { long n = in.nextLong(); int k = in.nextInt(); if (n == 1) { out.println(0); return; } if (1 + sum(k-1) < n) { out.println(-1); return; } int c = bins(n-1,k-1); if (1 + sum(k-1) - sum(c-1) == n) out.println(k-c); else out.println(k-c+1); } private static InputReader in; private static PrintWriter out; } class InputReader { public InputReader (Reader r) { buff = new BufferedReader(r); try { str = new StringTokenizer(buff.readLine()); } catch (IOException e) { e.printStackTrace(); } } public String next () { while (!str.hasMoreTokens()) try { str = new StringTokenizer(buff.readLine()); } catch (IOException e) { e.printStackTrace(); } return str.nextToken(); } public int nextInt () { return Integer.parseInt(this.next()); } public long nextLong () { return Long.parseLong(this.next()); } private static BufferedReader buff; private static StringTokenizer str; }
logn
287_B. Pipeline
CODEFORCES
import java.util.Scanner; public class A338 { public static void main (String args[]){ Scanner in= new Scanner(System.in); long n = in.nextInt(); long m=in.nextInt(); long k=in.nextInt(); long x = n-m; long y=n/k; if(x>=y) System.out.println(m); else { long t= y-x; long ans=0; ans+=k*(pow(t+1)-2); ans%=1000000009; ans+=m-t*k; ans%=1000000009; if(ans<0) ans+=1000000009; System.out.println(ans); } } public static long pow(long m ){ if(m==1) return 2; long x = pow(m/2); x%=1000000009; x*=x; if(m%2!=0) x*=2; x%=1000000009; return (x); } }
logn
338_A. Quiz
CODEFORCES
import java.io.*; import java.util.StringTokenizer; /** * * @author Prateep */ public class JavaApplication1 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB{ public void solve(int testNumber, InputReader in, PrintWriter out){ String base = in.next(); for (int len=base.length()-1;len>=1;len--) for (int i=0;i<base.length()-len+1;i++) for (int j=i+1;j<base.length()-len+1;j++) if (base.substring(i,i+len).equals(base.substring(j,j+len))){ out.println(len); return; } out.println(0); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } }
cubic
23_A. You're Given a String...
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.StringTokenizer; public class C { static ArrayList<Integer> statements; static final int MOD = (int) 1e9 + 7; static int[][] memo; static int solve(int i, int c) { if(i == statements.size()) return 1; if(memo[i][c] != -1) return memo[i][c]; long ans = solve(i + 1, c + statements.get(i)); if(c > 0) ans += solve(i, c - 1); return memo[i][c] = (int) (ans % MOD); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); statements = new ArrayList<>(); char[] c = new char[n]; for (int i = 0; i < n; i++) { c[i] = sc.next().charAt(0); } if(c[0] == 's') statements.add(0); else statements.add(1); for (int i = 1; i < n; i++) { if(c[i - 1] == 'f') { if(c[i] == 'f') statements.set(statements.size() - 1, statements.get(statements.size() - 1) + 1); }else { if(c[i] == 's') statements.add(0); else statements.add(1); } } memo = new int[statements.size()][n + 1]; for(int[] a : memo) Arrays.fill(a, -1); out.println(solve(0, 0)); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class ProblemB { public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] line = s.readLine().split(" "); long n = Long.valueOf(line[0]); long y = Long.valueOf(line[1]); long x = Long.valueOf(line[2]); long c = Long.valueOf(line[3]); long min = 0; long max = n*2L+20; for (int cnt = 0 ; cnt < 300 ; cnt++) { long med = (min+max) / 2L; long ct = isok(med, n, x, y, c); if (ct >= c) { max = med; } else { min = med+1; } } long lst = max; for (long d = -2 ; d <= 2 ; d++) { if (max+d >= 0 && isok(max+d, n, x, y, c) >= c) { lst = Math.min(lst, max+d); } } out.println(lst); out.flush(); } private static long isok(long time, long n, long x, long y, long c) { long total = time * 2 * (time + 1) + 1; long top = y - time; if (top <= 0) { long dy = Math.abs(top)+1; total -= dy*dy; long over = dy - x; if (over >= 1) { total += (1L + over) * over / 2; } over = dy - ((n + 1) - x); if (over >= 1) { total += (1L + over) * over / 2; } } long bottom = y + time; if (bottom > n) { long dy = Math.abs(bottom-n); total -= dy*dy; long over = dy - x; if (over >= 1) { total += (1L + over) * over / 2; } over = dy - ((n + 1) - x); if (over >= 1) { total += (1L + over) * over / 2; } } long left = x - time; if (left <= 0) { long dy = Math.abs(left)+1; total -= dy*dy; } long right = x + time; if (right > n) { long dy = Math.abs(right-n); total -= dy*dy; } return total; } public static void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { long n = in.nextLong(); long s = in.nextLong(); long ans = 0; long i = 0; for (i = s; i <= n; i++) { long t = i - sum(i); if (t >= s) { if (i % 10 == 9) { break; } ans++; } } if (n >= s) { out.println(ans - i + n + 1); } else { out.println(0); } } static long sum(long a) { long sum = 0; while (a != 0) { sum += (a % 10); a /= 10; } return sum; } } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Locale; import java.util.StringTokenizer; public class Solution implements Runnable { public static void main(String[] args) { (new Thread(new Solution())).start(); } BufferedReader in; PrintWriter out; StringTokenizer st; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.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()); } void solve() throws Exception { boolean[] r = new boolean[1010]; Arrays.fill(r, true); r[0] = r[1] = false; for (int i = 2; i < 1010; i++) { if (r[i]) { for (int j = i + i; j < 1010; j += i) { r[j] = false; } } } int[] pr = new int[1010]; int l = 0; for (int i = 2; i < 1010; i++) if (r[i]) pr[l++] = i; int n = nextInt(); int k = nextInt(); int ans = 0; int j = 0; for (int i = 2; i <= n; i++) { if (r[i]) { for (; j < l - 1; j++) { if (i == pr[j] + pr[j + 1] + 1) { ans++; break; } if (i < pr[j] + pr[j + 1] + 1) break; } } } if (ans >= k) out.println("YES"); else out.println("NO"); } public void run() { try { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } catch (Exception e) { e.printStackTrace(); } out.flush(); } }
linear
17_A. Noldbach problem
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Hashtable; import java.util.Scanner; import java.util.TreeSet; public class Main3 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); //BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = sc.nextInt(); String S = sc.next(); HashSet<Character> unique = new HashSet<>(); for(char c : S.toCharArray()){ unique.add(c); } int number = unique.size(); Hashtable<Character, Integer> indexes = new Hashtable<>(); TreeSet<Integer> tree = new TreeSet<>(); int min = N+1; int total = 0; for(int i = 0; i<N; i++){ char c = S.charAt(i); if(!indexes.containsKey(c)){ total++; indexes.put(c, i); tree.add(i); } else{ int old = indexes.get(c); indexes.put(c, i); tree.remove(old); tree.add(i); } if(total == number){ int dist = tree.last() - tree.first() + 1; min = Math.min(dist, min); } } System.out.println(min); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; public class E implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int t = scn.nextInt(); while(t-- > 0) { int n = scn.nextInt(), m = scn.nextInt(); int[][] arr = scn.next2DInt(n, m); int[][] col = new int[m][2]; for(int j = 0; j < m; j++) { int max = 0; for(int i = 0; i < n; i++) { max = Math.max(max, arr[i][j]); } col[j][0] = max; col[j][1] = j; } Arrays.parallelSort(col, (o1, o2) -> o2[0] - o1[0]); m = Math.min(n, m); int[][] lol = new int[n][m]; for(int j = 0; j < m; j++) { for(int i = 0; i < n; i++) { lol[i][j] = arr[i][col[j][1]]; } } int[] row = new int[n]; for(int i = 0; i < n; i++) { row[i] = lol[i][0]; } ans = 0; func(lol, 1, row); out.println(ans); } } int ans; void func(int[][] arr, int col, int[] rowM) { int n = arr.length, m = arr[0].length; if(col >= m) { int rv = 0; for(int a : rowM) { rv += a; } ans = Math.max(ans, rv); return; } int max = 0, ind = -1; for(int i = 0; i < n; i++) { if(arr[i][col] > max) { max = arr[i][col]; ind = i; } } boolean in = false; for(int r = 0; r < n; r++) { if(max <= rowM[r]) { continue; } int rot = (ind - r + n) % n; int[] need = new int[n], copy = Arrays.copyOf(rowM, n); for(int i = 0; i < n; i++) { need[i] = arr[(i + rot) % n][col]; } for(int i = 0; i < n; i++) { arr[i][col] = need[i]; copy[i] = Math.max(rowM[i], arr[i][col]); } ind = r; in = true; func(arr, col + 1, copy); } if(!in) { func(arr, col + 2, rowM); } } public void run() { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) { new Thread(null, new E(), "Main", 1 << 26).start(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; 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++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(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); } 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 * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { 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(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); int c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } long[] shuffle(long[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); long c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } int[] uniq(int[] arr) { arr = scn.shuffle(arr); Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } long[] uniq(long[] arr) { arr = scn.shuffle(arr); Arrays.sort(arr); long[] rv = new long[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } int[] reverse(int[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } long[] reverse(long[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } int[] compress(int[] arr) { int n = arr.length; int[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } long[] compress(long[] arr) { int n = arr.length; long[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { long x = in.nextLong(); long k = in.nextLong(); long max2 = (((x % 1_000_000_007) * (pb(k))) % 1_000_000_007) % 1_000_000_007; long min2 = ((((x - 1) % 1_000_000_007) * pb(k)) % 1_000_000_007 + 1) % 1_000_000_007; if (x == 0) min2 = 0; out.println((max2 + min2) % 1_000_000_007); } long pb(long a) { if (a == 0) return 1; if (a == 1) return 2; long tmp = pb(a / 2); if (a % 2 == 0) return (tmp * tmp) % 1_000_000_007; return (((tmp * tmp) % 1_000_000_007) * 2) % 1_000_000_007; } } static class InputReader { private StringTokenizer tokenizer; private BufferedReader reader; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private void fillTokenizer() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } } public String next() { fillTokenizer(); return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java .util.*; import java .io.*; public class Main{ public static void main(String[]YAHIA_MOSTAFA){ Scanner sc =new Scanner(System.in); long n=sc.nextLong(),x=sc.nextLong(),y=sc.nextLong(); long xb,xw,yb,yw; xw=x-1;yw=y-1;xb=n-x;yb=n-y; if (x==n&&y==n){ System.out.println("Black");return; } long c1=0,c2=0; long f =Math.max(xb,yb); long h =Math.max(xw,yw); //System.out.println(h+" "+f+" "+(h-f)); if (h<=f) System.out.println("White"); else System.out.println("Black"); } }
constant
1075_A. The King's Race
CODEFORCES
import java.util.Scanner; public class d { public static void main(String[] args) { Scanner in = new Scanner(System.in); int size = in.nextInt(); int[] vals = new int[size]; long[] cum = new long[size]; for(int i=0; i<size; i++){ vals[i] = in.nextInt(); int c = 0; for(int j=0; j<i; j++) if(vals[j] > vals[i]) c++; if(i != 0) cum[i] = cum[i-1]+c; else cum[i] = c; } long tot = cum[size-1]; int q = in.nextInt(); int[] nv = new int[size]; for(int i=0; i<q; i++) { int l = in.nextInt()-1; int r = in.nextInt()-1; int n = (r-l); long add = (n*(n+1))/2 - (cum[r] - cum[l]); tot = tot - (cum[r] - cum[l]) + add; if(tot%2 == 0) System.out.println("even"); else System.out.println("odd"); // for(int j=0; j<=r-l; j++) // nv[l+j] = vals[r-j]; // // for(int j=0; j<=r-l; j++) // vals[l+j] = nv[l+j]; } } } /* 3 1 2 3 2 1 2 2 3 4 1 2 4 3 4 1 1 1 4 1 4 2 3 */
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.*; import java.io.*; import java.text.*; //Solution Credits: Taranpreet Singh public class Main{ //SOLUTION BEGIN //Code not meant for understanding, proceed with caution void pre() throws Exception{} void solve(int TC) throws Exception{ int n = ni(); int[] a = new int[n]; for(int i = 0; i< n; i++)a[i] = ni(); HashMap<Long, ArrayList<int[]>> map = new HashMap<>(); for(int i = 0; i< n; i++){ long sum = 0; for(int j = i; j< n; j++){ sum+=a[j]; if(!map.containsKey(sum))map.put(sum, new ArrayList<>()); map.get(sum).add(new int[]{i+1, j+1}); } } int[][] ans = new int[n][];int cur = 0; int[][] tmp = new int[n][];int tc; for(Map.Entry<Long, ArrayList<int[]>> e: map.entrySet()){ int prev = 0; ArrayList<int[]> li = e.getValue(); Collections.sort(li, new Comparator<int[]>(){ public int compare(int[] i1, int[] i2){ if(i1[1]!=i2[1])return Integer.compare(i1[1], i2[1]); return Integer.compare(i1[0], i1[0]); } }); tc = 0; for(int[] p:li){ if(p[0]>prev){ tmp[tc++] = new int[]{p[0],p[1]}; prev = p[1]; } } if(tc>cur){ cur = tc; for(int i = 0; i< tc; i++)ans[i] = new int[]{tmp[i][0], tmp[i][1]}; } } pn(cur); for(int i = 0; i< cur; i++)pn(ans[i][0]+" "+ans[i][1]); } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} long mod = (long)1e9+7, IINF = (long)1e18; final int INF = (int)1e9, MX = (int)2e3+1; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.1415926535897932384626433832792884197169399375105820974944, eps = 1e-8; static boolean multipleTC = false, memory = false; FastReader in;PrintWriter out; void run() throws Exception{ in = new FastReader(); out = new PrintWriter(System.out); int T = (multipleTC)?ni():1; //Solution Credits: Taranpreet Singh pre();for(int t = 1; t<= T; t++)solve(t); out.flush(); out.close(); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str = ""; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; public class java2 { public static void main(String[] args) { Scanner r = new Scanner(System.in); int n=r.nextInt(); int []l=new int[1005]; int []ri=new int[1005]; int []candy=new int[1005]; for(int i=1;i<=n;++i) { l[i]=r.nextInt(); } for(int i=1;i<=n;++i) { ri[i]=r.nextInt(); } for(int i=1;i<=n;++i) { if(l[i]>i-1||ri[i]>n-i) { System.out.println("NO"); System.exit(0); } candy[i]=n-l[i]-ri[i]; } for(int i=1;i<=n;++i) { int left=0,right=0; for(int j=1;j<=i-1;++j) { if(candy[j]>candy[i]) { ++left; } } for(int j=i+1;j<=n;++j) { if(candy[j]>candy[i]) { ++right; } } if(left!=l[i]||right!=ri[i]) { System.out.println("NO"); System.exit(0); } } System.out.println("YES"); for(int i=1;i<=n;++i) { System.out.print(candy[i]+" "); } } }
quadratic
1054_C. Candies Distribution
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws IOException { new A().solve(); } BufferedReader br; StringTokenizer st = new StringTokenizer(""); private void solve() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); String s = nextToken(); int res = 0; for (int i = 0; i < s.length(); i++) { for (int j = i + 1; j < s.length(); j++) { int k = 0; while (k < s.length() - j && s.charAt(i + k) == s.charAt(j + k)) { k++; } res = Math.max(res, k); } } PrintWriter pw = new PrintWriter(System.out); pw.println(res); pw.close(); } String nextToken() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Scanner; public class Solution { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); String s = sc.next(); StringBuilder ans = new StringBuilder(); int count = 0; int open = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { ans.append("("); count++; open++; } else { ans.append(")"); open--; } if (count == k / 2) { break; } } while (open > 0) { ans.append(")"); open--; } System.out.println(ans.toString()); } }
linear
1023_C. Bracket Subsequence
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * Created by pallavi on 22/7/16. */ public class C701 { public static int f(char c) { if (c >= 'a' && c <= 'z') { return c - 'a'; } else { return 26 + c - 'A'; } } public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); char[] ch = reader.readLine().toCharArray(); LinkedList<Integer>[] p = new LinkedList[52]; for (int i = 0; i < 52; i++) { p[i] = new LinkedList<>(); } int[] fc = new int[n]; for (int i = 0; i < n; i++) { int cc = f(ch[i]); p[cc].add(i); fc[i] = cc; } int en = 0; for (int i = 0; i < 52; i++) { if (p[i].size() > 0) en = Math.max(en, p[i].poll()); } int mx = en + 1; for (int i = 0; i < n; i++) { if (p[fc[i]].size() == 0) break; en = Math.max(en, p[fc[i]].poll()); mx = Math.min(mx, en - i); } System.out.println(mx); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; public class A { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void solve() throws IOException { int tot = nextInt(); int ok = nextInt(); int k = nextInt(); int maxBad = tot / k; if (tot - maxBad >= ok) { out.println(ok); return; } int dbl = ok + tot / k - tot; int dblPoints = pow(2, dbl + 1) - 2; while (dblPoints < 0) dblPoints += MOD; dblPoints = (int)((long)dblPoints * k % MOD); int rest = ok - dbl * k; int ans = dblPoints + rest; if (ans >= MOD) ans -= MOD; out.println(ans); } static int pow(int a, int b) { int ret = 1; while (b != 0) { if ((b & 1) == 1) ret = (int)((long)ret * a % MOD); a = (int)((long)a * a % MOD); b >>= 1; } return ret; } static final int MOD = 1000000009; A() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new A(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
logn
338_A. Quiz
CODEFORCES
import java.util.Scanner; public class CF_8C { public static void main(String[] args) { // Hooray bitmasks! I'm good at these :) Scanner in = new Scanner(System.in); // Handbag coordinates.. int hb_x = in.nextInt(), hb_y = in.nextInt(); int n = in.nextInt(); int[] ox = new int[n]; int[] oy = new int[n]; // Dynamic programming: Also store a matrix of the time to reach one // object from the other. // This considers the handbag to be object 0 int[][] dt = new int[n][n]; int[] hbd = new int[n]; for (int i = 0; i < n; i++) { ox[i] = in.nextInt(); oy[i] = in.nextInt(); hbd[i] = (ox[i] - hb_x) * (ox[i] - hb_x) + (oy[i] - hb_y) * (oy[i] - hb_y); } // Compute elapsed times... for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dt[i][j] = (ox[i] - ox[j]) * (ox[i] - ox[j]) + (oy[i] - oy[j]) * (oy[i] - oy[j]); } } // Fill up an array with the amount of time it takes to grab // all objects with the specified bitmask. int[] sofar = new int[1 << n]; int[] masks = new int[1 << n]; sofar[0] = 0; for (int i = 1; i < (1 << n); i++) { sofar[i] = -1; } for (int i = 0; i < (1 << n); i++) { if (sofar[i] != -1) { for (int maskbit = 0; maskbit < n; maskbit++) { // Look for first object in bitmask to grab... if (((1 << maskbit) & i) == 0) { int iffirst = ((1 << maskbit) | i); int fromold = sofar[i] + 2 * hbd[maskbit]; if (sofar[iffirst] == -1 || sofar[iffirst] > fromold) { // A better way to get to position J was found, use it. sofar[iffirst] = fromold; masks[iffirst] = i; } // Find another thing while you're out... for (int otherone = 0; otherone < n; otherone++) { if (((1 << otherone) & iffirst) == 0) { int iffollow = ((1 << otherone) | iffirst); int fromi = sofar[i] + hbd[maskbit] + dt[maskbit][otherone] + hbd[otherone]; // Did we find a better way to get to iffollow state? if (sofar[iffollow] == -1 || sofar[iffollow] > fromi) { sofar[iffollow] = fromi; masks[iffollow] = i; } } } break; } } } } // After all this time, we have an answer. // The minimum time will be the value of sofar at the very end, // which will have the case of if all objects were picked up. // Clever, no? // The logic came from http://www.darrensun.com/codeforces-round-8/ // Wish I could claim it mine, but it is not so. int end_val = (1 << n) - 1; System.out.println(sofar[end_val]); System.out.print(0); while (end_val > 0) { // Which objects were collected in the prvious trip? int diff = end_val ^ masks[end_val]; int obj1 = -1, obj2 = -1; for (int i = 0; i < n; i++) { if (((1 << i) & diff) > 0) { obj2 = obj1; obj1 = i; } } if (obj2 >= 0) { // Two objects were collected this trip, output them both. System.out.print(" " + (obj1 + 1) + " " + (obj2 + 1) + " 0"); } else { // Only one object was collected here. System.out.print(" " + (obj1 + 1) + " 0"); } end_val = masks[end_val]; } in.close(); } }
np
8_C. Looking for Order
CODEFORCES
import java.util.*; import java.io.*; public class X { public static void main(String args[])throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String s1 = br.readLine(); String s2 = br.readLine(); int i=0; char c1,c2; int cost = 0; while(i<n) { c1 = s1.charAt(i); c2 = s2.charAt(i); if(c1 != c2) { if((i+1)<n && s1.charAt(i+1) != s2.charAt(i+1) && s1.charAt(i) != s1.charAt(i+1)) { cost +=1; i++; } else { cost +=1; } } i++; } System.out.println(cost); } }
linear
1037_C. Equalize
CODEFORCES
import java.util.*; public class B { static long sum(long from, long to){ final long d = to - from; return (d*(d + 1))/2 + (d + 1)*from; } static long howMany(long n, long k){ if (n == 1){ return 0; } if (n > (k*(k - 1))/2 + 1){ return -1; } long hi = k - 1; long lo = 1; while (lo < hi){ final long mi = (lo + hi + 1) >> 1; final long sum = sum(mi, k - 1); if (n - 1 - sum < mi){ lo = mi; }else{ hi = mi - 1; } } long res = k - lo; final long sum = sum(lo, k - 1); if (n - 1 - sum > 0){ res++; } return res; } public static void main(String [] args){ try (Scanner s = new Scanner(System.in)){ final long n = s.nextLong(); final long k = s.nextLong(); System.out.println(howMany(n, k)); } } }
logn
287_B. Pipeline
CODEFORCES
import java.io.*; import java.util.*; import javax.lang.model.util.ElementScanner6; public class codef { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer nk=new StringTokenizer(br.readLine()); int n=Integer.parseInt(nk.nextToken()); int k=Integer.parseInt(nk.nextToken()); String st[]=br.readLine().split(" "); int ans[]=new int[n]; int a[]=new int[n]; for(int i=0;i<n;i++) ans[i]=Integer.parseInt(st[i]); for(int i=1;i<n;i++) a[i]=ans[i]-ans[i-1]; a[0]=-1; Arrays.sort(a); int count=0,sum=0; for(int i=0;i<n;i++) if(a[i]<0) count++; else sum=sum+a[i]; k=k-count; int i=n-1; while(k>0 && i>=0) { if(a[i]>-1) { sum=sum-a[i]; k--; } i--; } System.out.println(sum); } }
nlogn
1197_C. Array Splitting
CODEFORCES
import java.util.Scanner; /** * 2013.07.27 No.1 235A LCM Challenge * 数论 n%2 == 0? n%3 == 0? * @author Administrator * */ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); if (n < 3) System.out.println(n); else if (n % 2 != 0) System.out.println((long)n * (n - 1) * (n - 2)); else if(n % 3 != 0) System.out.println((long)n * (n - 1) * (n - 3)); else System.out.println((long)(n - 1) * (n - 2) * (n - 3)); in.close(); } }
constant
235_A. LCM Challenge
CODEFORCES
import java.io.*; import java.util.*; public class B { static FastScanner fs; public static void main(String[] args) { fs=new FastScanner(); int t = fs.nextInt(); while (t-->0) solve(); } public static void solve() { int n = fs.nextInt()*2; int sq = (int)Math.sqrt(n); int sq2 = (int)Math.sqrt(n/2); if (sq*sq==n) System.out.println("YES"); else if (sq2*sq2==n/2.0 && sq2%2==0) System.out.println("YES"); else System.out.println("NO"); } static int gcd(int a, int b) { if (a==0) return b; return gcd(b%a, a); } static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static final Random random =new Random(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } static int[] reverse(int[] a) { int n=a.length; int[] res=new int[n]; for (int i=0; i<n; i++) res[i]=a[n-1-i]; return res; } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc =new Scanner (System.in); long a=sc.nextLong(); long b=sc.nextLong(); if(b-a <=1) System.out.println("-1"); else if(b-a==2 && a%2==1) System.out.println("-1"); else { if(a%2==1) System.out.println((a+1)+" "+(a+2)+" "+(a+3)); else System.out.println((a)+" "+(a+1)+" "+(a+2)); } sc.close(); } }
constant
483_A. Counterexample
CODEFORCES
import java.io.*; import java.util.*; public class tr { static int[][] ad; static boolean []vis; static int []goods; static int[][]sol; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n=sc.nextInt(); int []a=new int [n]; int max=0; for(int i=0;i<n;i++) a[i]=sc.nextInt(); Stack<Integer> s=new Stack<>(); boolean f=true; for(int i=0;i<n;i++) { max=Math.max(max,a[i]); if(!s.isEmpty() && a[i]>s.peek()) f=false; s.push(a[i]); while(!s.isEmpty()) { int high=s.pop(); if(s.isEmpty() || s.peek()!=high) { s.push(high); break; } s.pop(); } // System.out.println(s+" "+max); } //System.out.println(f+" "+max); if(f && s.size()==0) out.println("YES"); else if(f && s.size()==1 && s.peek()==max) out.println("YES"); else out.println("NO"); out.flush(); } static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } static class pair implements Comparable<pair> { int a; int b; pair(int a, int b) { this.a = a; this.b = b; } public String toString() { return a + " " + b; } @Override public int compareTo(pair o) { return o.a-a ; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
linear
1092_D1. Great Vova Wall (Version 1)
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Main{ public static void main(String[] args) { long n,k; Scanner s= new Scanner(System.in); n=s.nextInt(); k=s.nextInt(); System.out.println((int)(n-((-3+Math.sqrt(9+8*(n+k)))/2))); } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.*; import java.util.*; import java.util.Map.Entry; public class E { FastScanner in; PrintWriter out; boolean systemIO = true; public class DSU { int[] sz; int[] p; public DSU(int n) { sz = new int[n]; p = new int[n]; for (int i = 0; i < p.length; i++) { p[i] = i; sz[i] = 1; } } public int get(int x) { if (x == p[x]) { return x; } int par = get(p[x]); p[x] = par; return par; } public boolean unite(int a, int b) { int pa = get(a); int pb = get(b); if (pa == pb) { return false; } if (sz[pa] < sz[pb]) { p[pa] = pb; sz[pb] += sz[pa]; } else { p[pb] = pa; sz[pa] += sz[pb]; } return true; } } public class SegmentTreeAdd { int pow; long[] min; long[] delta; boolean[] flag; public SegmentTreeAdd(long[] a) { pow = 1; while (pow < a.length) { pow *= 2; } flag = new boolean[2 * pow]; min = new long[2 * pow]; delta = new long[2 * pow]; for (int i = 0; i < min.length; i++) { min[i] = Long.MAX_VALUE / 2; } for (int i = 0; i < a.length; i++) { min[pow + i] = a[i]; } for (int i = pow - 1; i > 0; i--) { min[i] = f(min[2 * i], min[2 * i + 1]); } } public long get(int l, int r) { return get(1, 0, pow, l, r); } private long get(int v, int tl, int tr, int l, int r) { push(v, tl, tr); if (l >= tr || r <= tl) { return Long.MAX_VALUE / 2; } if (l <= tl && r >= tr) { return min[v]; } int tm = (tl + tr) / 2; return f(get(2 * v, tl, tm, l, r), get(2 * v + 1, tm, tr, l, r)); } public void set(int l, int r, long x) { set(1, 0, pow, l, r, x); } private void set(int v, int tl, int tr, int l, int r, long x) { push(v, tl, tr); if (l >= tr || r <= tl) { return; } if (l <= tl && r >= tr) { delta[v] += x; flag[v] = true; push(v, tl, tr); return; } int tm = (tl + tr) / 2; set(2 * v, tl, tm, l, r, x); set(2 * v + 1, tm, tr, l, r, x); min[v] = f(min[2 * v], min[2 * v + 1]); } public void push(int v, int tl, int tr) { if (flag[v]) { if (v < pow) { flag[2 * v] = true; flag[2 * v + 1] = true; delta[2 * v] += delta[v]; delta[2 * v + 1] += delta[v]; } flag[v] = false; min[v] += delta[v]; delta[v] = 0; } } public long f(long a, long b) { return Math.min(a, b); } } public class SegmentTreeSet { int pow; int[] sum; int[] delta; boolean[] flag; public SegmentTreeSet(int[] a) { pow = 1; while (pow < a.length) { pow *= 2; } flag = new boolean[2 * pow]; sum = new int[2 * pow]; delta = new int[2 * pow]; for (int i = 0; i < a.length; i++) { sum[pow + i] = a[i]; } } public int get(int v, int tl, int tr, int l, int r) { push(v, tl, tr); if (l > r) { return 0; } if (l == tl && r == tr) { return sum[v]; } int tm = (tl + tr) / 2; return f(get(2 * v, tl, tm, l, Math.min(r, tm)), get(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r)); } public void set(int v, int tl, int tr, int l, int r, int x) { push(v, tl, tr); if (l > tr || r < tl) { return; } if (l <= tl && r >= tr) { delta[v] = x; flag[v] = true; push(v, tl, tr); return; } int tm = (tl + tr) / 2; set(2 * v, tl, tm, l, r, x); set(2 * v + 1, tm + 1, tr, l, r, x); sum[v] = f(sum[2 * v], sum[2 * v + 1]); } public void push(int v, int tl, int tr) { if (flag[v]) { if (v < pow) { flag[2 * v] = true; flag[2 * v + 1] = true; delta[2 * v] = delta[v]; delta[2 * v + 1] = delta[v]; } flag[v] = false; sum[v] = delta[v] * (tr - tl + 1); } } public int f(int a, int b) { return a + b; } } Random random = new Random(); public void shuffle(Pair[] a) { for (int i = 0; i < a.length; i++) { int x = random.nextInt(i + 1); Pair t = a[x]; a[x] = a[i]; a[i] = t; } } public void sort(int[][] a) { for (int i = 0; i < a.length; i++) { Arrays.sort(a[i]); } } public void add(HashMap<Long, Integer> map, long l) { if (map.containsKey(l)) { map.put(l, map.get(l) + 1); } else { map.put(l, 1); } } public void remove(TreeMap<Integer, Integer> map, Integer s) { if (map.get(s) > 1) { map.put(s, map.get(s) - 1); } else { map.remove(s); } } double eps = 1e-10; public int signum(double x) { if (x > eps) { return 1; } if (x < -eps) { return -1; } return 0; } public long abs(long x) { return x < 0 ? -x : x; } public long min(long x, long y) { return x < y ? x : y; } public long max(long x, long y) { return x > y ? x : y; } public long gcd(long x, long y) { while (y > 0) { long c = y; y = x % y; x = c; } return x; } // public class Vector implements Comparable<Vector> { // long x; // long y; // int type; // int number; // // public Vector() { // x = 0; // y = 0; // } // // public Vector(long x, long y, int type, int number) { // this.x = x; // this.y = y; // this.type = type; // this.number = number; // } // // public Vector(long x, long y) { // // } // // public Vector(Point begin, Point end) { // this(end.x - begin.x, end.y - begin.y); // } // // public void orient() { // if (x < 0) { // x = -x; // y = -y; // } // if (x == 0 && y < 0) { // y = -y; // } // } // // public void normalize() { // long gcd = gcd(abs(x), abs(y)); // x /= gcd; // y /= gcd; // } // // public String toString() { // return x + " " + y; // } // // public boolean equals(Vector v) { // return x == v.x && y == v.y; // } // // public boolean collinear(Vector v) { // return cp(this, v) == 0; // } // // public boolean orthogonal(Vector v) { // return dp(this, v) == 0; // } // // public Vector ort(Vector v) { // return new Vector(-y, x); // } // // public Vector add(Vector v) { // return new Vector(x + v.x, y + v.y); // } // // public Vector multiply(long c) { // return new Vector(c * x, c * y); // } // // public int quater() { // if (x > 0 && y >= 0) { // return 1; // } // if (x <= 0 && y > 0) { // return 2; // } // if (x < 0) { // return 3; // } // return 0; // } // // public long len2() { // return x * x + y * y; // } // // @Override // public int compareTo(Vector o) { // if (quater() != o.quater()) { // return quater() - o.quater(); // } // return signum(cp(o, this)); // } // } // public long dp(Vector v1, Vector v2) { // return v1.x * v2.x + v1.y * v2.y; // } // // public long cp(Vector v1, Vector v2) { // return v1.x * v2.y - v1.y * v2.x; // } // public class Line implements Comparable<Line> { // Point p; // Vector v; // // public Line(Point p, Vector v) { // this.p = p; // this.v = v; // } // // public Line(Point p1, Point p2) { // if (p1.compareTo(p2) < 0) { // p = p1; // v = new Vector(p1, p2); // } else { // p = p2; // v = new Vector(); // } // } // // public boolean collinear(Line l) { // return v.collinear(l.v); // } // // public boolean inLine(Point p) { // return hv(p) == 0; // } // // public boolean inSegment(Point p) { // if (!inLine(p)) { // return false; // } // Point p1 = p; // Point p2 = p.add(v); // return p1.x <= p.x && p.x <= p2.x && min(p1.y, p2.y) <= p.y && p.y <= // max(p1.y, p2.y); // } // // public boolean equalsSegment(Line l) { // return p.equals(l.p) && v.equals(l.v); // } // // public boolean equalsLine(Line l) { // return collinear(l) && inLine(l.p); // } // // public long hv(Point p) { // Vector v1 = new Vector(this.p, p); // return cp(v, v1); // } // // public double h(Point p) { // Vector v1 = new Vector(this.p, p); // return cp(v, v1) / Math.sqrt(v.len2()); // } // // public long[] intersectLines(Line l) { // if (collinear(l)) { // return null; // } // long[] ans = new long[4]; // // return ans; // } // // public long[] intersectSegment(Line l) { // long[] ans = intersectLines(l); // if (ans == null) { // return null; // } // Point p1 = p; // Point p2 = p.add(v); // boolean f1 = p1.x * ans[1] <= ans[0] && ans[0] <= p2.x * ans[1] && min(p1.y, // p2.y) * ans[3] <= ans[2] // && ans[2] <= max(p1.y, p2.y) * ans[3]; // p1 = l.p; // p2 = l.p.add(v); // boolean f2 = p1.x * ans[1] <= ans[0] && ans[0] <= p2.x * ans[1] && min(p1.y, // p2.y) * ans[3] <= ans[2] // && ans[2] <= max(p1.y, p2.y) * ans[3]; // if (!f1 || !f2) { // return null; // } // return ans; // } // // @Override // public int compareTo(Line o) { // return v.compareTo(o.v); // } // } public class Rect { long x1; long x2; long y1; long y2; int number; public Rect(long x1, long x2, long y1, long y2, int number) { this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; this.number = number; } } public static class Fenvik { int[] t; public Fenvik(int n) { t = new int[n]; } public void add(int x, int delta) { for (int i = x; i < t.length; i = (i | (i + 1))) { t[i] += delta; } } private int sum(int r) { int ans = 0; int x = r; while (x >= 0) { ans += t[x]; x = (x & (x + 1)) - 1; } return ans; } public int sum(int l, int r) { return sum(r) - sum(l - 1); } } public class SegmentTreeMaxSum { int pow; int[] sum; int[] maxPrefSum; int[] maxSufSum; int[] maxSum; public SegmentTreeMaxSum(int[] a) { pow = 1; while (pow < a.length) { pow *= 2; } sum = new int[2 * pow]; maxPrefSum = new int[2 * pow]; maxSum = new int[2 * pow]; maxSufSum = new int[2 * pow]; for (int i = 0; i < a.length; i++) { sum[pow + i] = a[i]; maxSum[pow + i] = Math.max(a[i], 0); maxPrefSum[pow + i] = maxSum[pow + i]; maxSufSum[pow + i] = maxSum[pow + i]; } for (int i = pow - 1; i > 0; i--) { update(i); } } public int[] get(int v, int tl, int tr, int l, int r) { if (r <= tl || l >= tr) { int[] ans = { 0, 0, 0, 0 }; return ans; } if (l <= tl && r >= tr) { int[] ans = { maxPrefSum[v], maxSum[v], maxSufSum[v], sum[v] }; return ans; } int tm = (tl + tr) / 2; int[] left = get(2 * v, tl, tm, l, r); int[] right = get(2 * v + 1, tm, tr, l, r); int[] ans = { Math.max(left[0], right[0] + left[3]), Math.max(left[1], Math.max(right[1], left[2] + right[0])), Math.max(right[2], left[2] + right[3]), left[3] + right[3] }; return ans; } public void set(int v, int tl, int tr, int x, int value) { if (v >= pow) { sum[v] = value; maxSum[v] = Math.max(value, 0); maxPrefSum[v] = maxSum[v]; maxSufSum[v] = maxSum[v]; return; } int tm = (tl + tr) / 2; if (x < tm) { set(2 * v, tl, tm, x, value); } else { set(2 * v + 1, tm, tr, x, value); } update(v); } public void update(int i) { sum[i] = f(sum[2 * i], sum[2 * i + 1]); maxSum[i] = Math.max(maxSum[2 * i], Math.max(maxSum[2 * i + 1], maxSufSum[2 * i] + maxPrefSum[2 * i + 1])); maxPrefSum[i] = Math.max(maxPrefSum[2 * i], maxPrefSum[2 * i + 1] + sum[2 * i]); maxSufSum[i] = Math.max(maxSufSum[2 * i + 1], maxSufSum[2 * i] + sum[2 * i + 1]); } public int f(int a, int b) { return a + b; } } public class Fraction implements Comparable<Fraction> { long x; long y; public Fraction(long x, long y, boolean needNorm) { this.x = x; this.y = y; if (y < 0) { this.x *= -1; this.y *= -1; } if (needNorm) { long gcd = gcd(this.x, this.y); this.x /= gcd; this.y /= gcd; } } public Fraction clone() { return new Fraction(x, y, false); } public String toString() { return x + "/" + y; } @Override public int compareTo(Fraction o) { long res = x * o.y - y * o.x; if (res > 0) { return 1; } if (res < 0) { return -1; } return 0; } } public class Event implements Comparable<Event> { Fraction f; int type; public Event(Fraction f, int type) { this.f = f; this.type = type; } @Override public int compareTo(Event o) { int c = f.compareTo(o.f); if (c != 0) { return c; } return type - o.type; } } public double sq(double x) { return x * x; } public long sq(long x) { return x * x; } public double hypot2(double x, double y) { return sq(x) + sq(y); } public long hypot2(long x, long y) { return sq(x) + sq(y); } public boolean kuhn(int v, int[][] edge, boolean[] used, int[] mt) { used[v] = true; for (int u : edge[v]) { if (mt[u] < 0 || (!used[mt[u]] && kuhn(mt[u], edge, used, mt))) { mt[u] = v; return true; } } return false; } public int matching(int[][] edge) { int n = edge.length; int[] mt = new int[n]; Arrays.fill(mt, -1); boolean[] used = new boolean[n]; int ans = 0; for (int i = 0; i < n; i++) { if (!used[i] && kuhn(i, edge, used, mt)) { Arrays.fill(used, false); ans++; } } return ans; } double sq2 = Math.sqrt(2); public class MyStack { int[] st; int sz; public MyStack(int n) { this.st = new int[n]; sz = 0; } public boolean isEmpty() { return sz == 0; } public int peek() { return st[sz - 1]; } public int pop() { sz--; return st[sz]; } public void clear() { sz = 0; } public void add(int x) { st[sz++] = x; } public int get(int x) { return st[x]; } } public int[][] readGraph(int n, int m) { int[][] to = new int[n][]; int[] sz = new int[n]; int[] x = new int[m]; int[] y = new int[m]; for (int i = 0; i < m; i++) { x[i] = in.nextInt() - 1; y[i] = in.nextInt() - 1; sz[x[i]]++; sz[y[i]]++; } for (int i = 0; i < to.length; i++) { to[i] = new int[sz[i]]; sz[i] = 0; } for (int i = 0; i < x.length; i++) { to[x[i]][sz[x[i]]++] = y[i]; to[y[i]][sz[y[i]]++] = x[i]; } return to; } public class Pol { double[] coeff; public Pol(double[] coeff) { this.coeff = coeff; } public Pol mult(Pol p) { double[] ans = new double[coeff.length + p.coeff.length - 1]; for (int i = 0; i < ans.length; i++) { for (int j = Math.max(0, i - p.coeff.length + 1); j < coeff.length && j <= i; j++) { ans[i] += coeff[j] * p.coeff[i - j]; } } return new Pol(ans); } public String toString() { String ans = ""; for (int i = 0; i < coeff.length; i++) { ans += coeff[i] + " "; } return ans; } public double value(double x) { double ans = 0; double p = 1; for (int i = 0; i < coeff.length; i++) { ans += coeff[i] * p; p *= x; } return ans; } public double integrate(double r) { Pol p = new Pol(new double[coeff.length + 1]); for (int i = 0; i < coeff.length; i++) { p.coeff[i + 1] = coeff[i] / fact[i + 1]; } return p.value(r); } public double integrate(double l, double r) { return integrate(r) - integrate(l); } } int mod = 1000000007; public int sum(int a, int b) { if (a + b >= mod) { return a + b - mod; } return a + b; } public int diff(int a, int b) { if (a < b) { return a + mod - b; } return a - b; } public int mult(int a, int b) { return (int) ((a * 1L * b) % (1L * mod)); } public int pow(int x, int p) { if (p <= 0) { return 1; } int ans = pow(x, p / 2); ans = mult(ans, ans); if (p % 2 == 1) { ans = mult(ans, x); } return ans; } public int modInv(int x) { return pow(x, mod - 2); } public int c_n_k(int n, int k) { if (n < 0 || k < 0 || n - k < 0) { return 0; } return mult(fact[n], mult(factInv[k], factInv[n - k])); } public class LinAl01 { public class Vector { BitSet vec; BitSet swtch; public Vector(BitSet vec, BitSet swtch) { this.vec = vec; this.swtch = swtch; } public String toString() { String s = ""; for (int i = 0; i < basis.length; i++) { s += (vec.get(i) ? 1 : 0); } s += " "; for (int i = 0; i < basis.length; i++) { s += (swtch.get(i) ? 1 : 0); } return s; } } int n; Vector[] basis; public void update(Vector v) { for (int i = 0; i < n; i++) { if (v.vec.get(i)) { if (basis[i] == null) { basis[i] = v; break; } v.vec.xor(basis[i].vec); v.swtch.xor(basis[i].swtch); } } } public void diagonalize() { for (int i = 0; i < n; i++) { if (basis[i] == null) { continue; } for (int j = 0; j < i; j++) { if (basis[j] != null && basis[j].vec.get(i)) { basis[j].vec.xor(basis[i].vec); basis[j].swtch.xor(basis[i].swtch); } } } } } public class Point implements Comparable<Point> { double x; double y; public Point() { x = 0; y = 0; } public Point(double x, double y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Point p) { return x == p.x && y == p.y; } public double dist2() { return x * x + y * y; } public Point add(Point v) { return new Point(x + v.x, y + v.y); } public Point subtract(Point v) { return new Point(x - v.x, y - v.y); } @Override public int compareTo(Point o) { int z = signum(x + y - o.x - o.y); if (z != 0) { return z; } return signum(x - o.x) != 0 ? signum(x - o.x) : signum(y - o.y); } } public class Circle { Point p; long r; public Circle(Point p, long r) { this.p = p; this.r = r; } public boolean intersect(Line l) { return Math.abs(l.a * p.x + l.b * p.y + l.c) / Math.hypot(l.a, l.b) < r; } public boolean inside(Point p) { return hypot2(p.x - this.p.x, p.y - this.p.y) <= sq(r); } } public class Line { long a; long b; long c; public Line(long a, long b, long c) { if (a < 0 || (a == 0 && b < 0)) { a = -a; b = -b; c = -c; long gcd = gcd(a, Math.abs(b)); a /= gcd; b /= gcd; } this.a = a; this.b = b; this.c = c; } public String toString() { return a + " " + b + " " + c; } // public Line(Point a, Point b) { // this.a = a.y - b.y; // this.b = b.x - a.x; // this.c = a.x * b.y - a.y * b.x; // } } // public long compareDist(Circle a, Circle b, Circle c) { // tangent to a, b; a.r, b.r may be < 0 // long x = b.p.x - a.p.x; // long y = b.p.y - a.p.y; // long r = b.r - a.r; // long dx = c.p.x - a.p.x; // long dy = c.p.y - a.p.y; // long dr = c.r - a.r; // long left = y * dx - x * dy; // long sqrt = x * x + y * y - r * r; // long right = dr * (x * x + y * y) - r * (x * dx + y * dy); // if (sqrt == 0 || left == 0) { // if (right > 0) { // return -1; // } // if (right < 0) { // return 1; // } // return 0; // } // if (right == 0) { // if (left > 0) { // return 1; // } // return -1; // } // if (left > 0 && right < 0) { // return 1; // } // if (left < 0 && right > 0) { // return -1; // } // int mult = 1; // if (left < 0) { // mult = -1; // } // return BigInteger.valueOf(left).pow(2).multiply(BigInteger.valueOf(sqrt)) // .compareTo(BigInteger.valueOf(right).pow(2)) * mult; // } // public boolean inOrTang(Circle a, Circle b, Circle c) { // return compareDist(a, b, c) <= 0 && compareDist(a, b, new Circle(c.p, -c.r)) >= 0; // } // public boolean in(Circle a, Circle b, Circle c) { // return compareDist(a, b, c) < 0 && compareDist(a, b, new Circle(c.p, -c.r)) > 0; // } public long sqr(long a) { return a * a; } // public void tangents(Point c, long r1, long r2, ArrayList<Line> ans) { // long r = r2 - r1; // long z = sqr(c.x) + sqr(c.y); // long delta = z - sqr(r); // if (delta <= 0) { // return; // } // double d = Math.sqrt(Math.abs(delta)); // Line l = new Line((c.x * r + c.y * d) / z, (c.y * r - c.x * d) / z, r1); // if (r1 * r2 >= 0) { // ans.add(new Line(l.a, l.b, l.c + eps)); // ans.add(new Line(l.a, l.b, l.c - eps)); // } else { // double sqrt = Math.hypot(c.x, c.y); // double da = eps * c.y / sqrt; // double db = -eps * c.x / sqrt; // ans.add(new Line(l.a + da, l.b + db, l.c)); // ans.add(new Line(l.a - da, l.b - db, l.c)); // } // } // public ArrayList<Line> tangents(Circle a, Circle b) { // ArrayList<Line> ans = new ArrayList<>(); // for (int i = -1; i <= 1; i += 2) { // for (int j = -1; j <= 1; j += 2) { // tangents(b.p.subtract(a.p), a.r * i, b.r * j, ans); // } // } // for (int i = 0; i < ans.size(); ++i) { // ans.get(i).c -= ans.get(i).a * a.p.x + ans.get(i).b * a.p.y; // } // return ans; // } int[] fact = new int[1000001]; int[] factInv = new int[1000001]; public int[] intersect(int y, int xdown, int ydown, int xup, int yup) { if (yup < y || ydown > y || (ydown == yup)) { return null; } long p = xup * 1L * (y - ydown) + xdown * 1L * (yup - y); if (p < 0) { int[] ans = { -1, 0 }; return ans; } long q = 2 * (yup - ydown); int[] ans = { (int) (p / q), (int) ((p + q - 1) / q) }; return ans; } public void I(int[][] a) { for (int i = 0; i < a.length; i++) { int[] b = new int[a.length]; for (int j = 0; j < b.length; j++) { b[a[i][j]] = j; } a[i] = b; } } public void C(int[][] a) { for (int i = 0; i < a.length; i++) { int[] b = new int[a.length]; for (int j = 0; j < b.length; j++) { b[a[j][i]] = j; } for (int j = 0; j < b.length; j++) { a[j][i] = b[j]; } } } public class SegmentTree { int pow; Pair[] min; public SegmentTree(int[] a) { pow = 1; while (pow < a.length) { pow *= 2; } min = new Pair[2 * pow]; for (int i = 0; i < a.length; i++) { min[pow + i] = new Pair(a[i], i); } for (int i = a.length; i < pow; i++) { min[pow + i] = new Pair(Integer.MAX_VALUE / 2, -1); } for (int i = pow - 1; i > 0; i--) { min[i] = f(min[2 * i], min[2 * i + 1]); } } public Pair get(int l, int r) { return get(1, 0, pow, l, r); } private Pair get(int v, int tl, int tr, int l, int r) { if (l >= tr || r <= tl) { return new Pair(Integer.MAX_VALUE / 2, -1); } if (l <= tl && r >= tr) { return min[v]; } int tm = (tl + tr) / 2; return f(get(2 * v, tl, tm, l, r), get(2 * v + 1, tm, tr, l, r)); } public void set(int x, int value) { set(1, 0, pow, x, value); } private void set(int v, int tl, int tr, int x, int value) { if (x >= tr || x < tl) { return; } if (v >= pow) { min[v] = new Pair(value, -1); return; } int tm = (tl + tr) / 2; set(2 * v, tl, tm, x, value); set(2 * v + 1, tm, tr, x, value); min[v] = f(min[2 * v], min[2 * v + 1]); } public Pair f(Pair a, Pair b) { if (a.compareTo(b) <= 0) { return a.clone(); } return b.clone(); } } public boolean nextPermutation(int[] a) { int n = a.length; for (int i = n - 2; i >= 0; i--) { if (a[i] < a[i + 1]) { for (int d = 1; d <= (n - 1 - i) / 2; d++) { a[i + d] ^= a[n - d]; a[n - d] = a[i + d] ^ a[n - d]; a[i + d] = a[i + d] ^ a[n - d]; } for (int j = i + 1; j < n; j++) { if (a[j] > a[i]) { a[i] ^= a[j]; a[j] = a[i] ^ a[j]; a[i] = a[i] ^ a[j]; return true; } } } } return false; } public class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } public Pair add(Pair p) { return new Pair(x + p.x, y + p.y); } public Pair clone() { return new Pair(x, y); } public String toString() { return x + " " + y; } @Override public int compareTo(Pair o) { if (x < o.x) { return -1; } if (x > o.x) { return 1; } if (y > o.y) { return 1; } if (y < o.y) { return -1; } return 0; } } public double intersection(Pair p1, Pair p2) { return (p2.y - p1.y) * 1.0 / (p1.x - p2.x); } HashMap<Integer, Integer> even = new HashMap<>(); HashMap<Integer, Integer> odd = new HashMap<>(); public void addOdd(int key, int value) { if (odd.containsKey(key)) { odd.put(key, Math.min(odd.get(key), value)); } else { odd.put(key, value); } } public void addEven(int key, int value) { if (even.containsKey(key)) { even.put(key, Math.min(even.get(key), value)); } else { even.put(key, value); } } public void solve() { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); // int n = 500; // int m = 500; // int k = 20; if (k % 2 == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(-1 + " "); } out.println(); } return; } k /= 2; int[][] hor = new int[n][m - 1]; for (int i = 0; i < hor.length; i++) { for (int j = 0; j < hor[0].length; j++) { hor[i][j] = in.nextInt() * 2; // hor[i][j] = random.nextInt(1000000) + 1; } } int[][] vert = new int[n - 1][m]; for (int i = 0; i < vert.length; i++) { for (int j = 0; j < vert[0].length; j++) { vert[i][j] = in.nextInt() * 2; // vert[i][j] = random.nextInt(1000000) + 1; } } long time = System.currentTimeMillis(); int[][][] ans = new int[k + 1][n][m]; for (int l = 1; l <= k; l++) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ans[l][i][j] = Integer.MAX_VALUE; if (i > 0) { ans[l][i][j] = Math.min(ans[l][i][j], ans[l - 1][i - 1][j] + vert[i - 1][j]); } if (j > 0) { ans[l][i][j] = Math.min(ans[l][i][j], ans[l - 1][i][j - 1] + hor[i][j - 1]); } if (i < n - 1) { ans[l][i][j] = Math.min(ans[l][i][j], ans[l - 1][i + 1][j] + vert[i][j]); } if (j < m - 1) { ans[l][i][j] = Math.min(ans[l][i][j], ans[l - 1][i][j + 1] + hor[i][j]); } } } } // for (int i = 0; i < n; i++) { // for (int j = 0; j < m; j++) { // even.clear(); // odd.clear(); // even.put(i * m + j, 0); // for (int l = 0; l < k; l++) { // if (l % 2 == 0) { // odd.clear(); // for (Entry<Integer, Integer> e : even.entrySet()) { // int x = e.getKey() / m; // int y = e.getKey() % m; // int value = e.getValue(); // if (x > 0) { // addOdd((x - 1) * m + y, value + vert[x - 1][y]); // } // if (y > 0) { // addOdd(x * m + y - 1, value + hor[x][y - 1]); // } // if (x < n - 1) { // addOdd((x + 1) * m + y, value + vert[x][y]); // } // if (y < m - 1) { // addOdd(x * m + y + 1, value + hor[x][y]); // } // } // } else { // even.clear(); // for (Entry<Integer, Integer> e : odd.entrySet()) { // int x = e.getKey() / m; // int y = e.getKey() % m; // int value = e.getValue(); // if (x > 0) { // addEven((x - 1) * m + y, value + vert[x - 1][y]); // } // if (y > 0) { // addEven(x * m + y - 1, value + hor[x][y - 1]); // } // if (x < n - 1) { // addEven((x + 1) * m + y, value + vert[x][y]); // } // if (y < m - 1) { // addEven(x * m + y + 1, value + hor[x][y]); // } // } // } // } // ans[i][j] = Integer.MAX_VALUE; // if (k % 2 == 0) { // for (Entry<Integer, Integer> e : even.entrySet()) { // ans[i][j] = Math.min(ans[i][j], e.getValue() * 2); // } // } else { // for (Entry<Integer, Integer> e : odd.entrySet()) { // ans[i][j] = Math.min(ans[i][j], e.getValue() * 2); // } // } // } // } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(ans[k][i][j] + " "); } out.println(); } System.err.println(System.currentTimeMillis() - time); } public void add(HashMap<Integer, Integer> map, int x) { if (map.containsKey(x)) { map.put(x, map.get(x) + 1); } else { map.put(x, 1); } } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA public static void main(String[] arg) { new E().run(); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class A113 { public static void main(String[] args) { new A113().run(); } public void run() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); Team[] teams = new Team[n]; for (int i = 0; i < teams.length; i++) { teams[i] = new Team(in.nextInt(), in.nextInt()); } Arrays.sort(teams); int counter = 1; int index = k-2; while (index >= 0 && teams[index].p == teams[k-1].p && teams[index].t == teams[k-1].t) { index--; counter++; } index = k; while (index < n && teams[index].p == teams[k-1].p && teams[index].t == teams[k-1].t) { index++; counter++; } System.out.println(counter); } private class Team implements Comparable<Team> { int p; int t; public Team(int pp, int tt) { p = pp; t = tt; } @Override public int compareTo(Team o) { if (o.p - this.p == 0) return this.t - o.t; return o.p - this.p; } } }
nlogn
166_A. Rank List
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main implements Runnable { // //////////////////////////////////////////////////// // Solution private int n; private int nn; private int[][] D; private int[] dp; private int[] prev; private void solve() throws Throwable { int xs = nextInt(), ys = nextInt(); n = nextInt(); int[][] pts = new int[n][2]; for (int i = 0; i < n; i++) { pts[i][0] = nextInt(); pts[i][1] = nextInt(); } D = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { D[i][i] = 2 * (sqr(pts[i][0] - xs) + sqr(pts[i][1] - ys)); } else { D[i][j] = sqr(pts[i][0] - xs) + sqr(pts[i][1] - ys) + sqr(pts[i][0] - pts[j][0]) + sqr(pts[i][1] - pts[j][1]) + sqr(pts[j][0] - xs) + sqr(pts[j][1] - ys); } } } nn = 1 << n; dp = new int[nn]; prev = new int[nn]; Arrays.fill(dp, -1); Arrays.fill(prev, -1); dp[0] = 0; Dp(nn - 1); pw.println(dp[nn - 1]); pw.print(0); for (int p = nn - 1; p != -1 && prev[p] != -1; p = prev[p]) { int vv = p ^ prev[p]; for (int j = 0; j < n; j++) { int jj = 1 << j; if ((vv & jj) == 0) continue; pw.print(' '); pw.print(j + 1); } pw.print(" 0"); } pw.println(); } private int Dp(int i) { if (dp[i] != -1) return dp[i]; int ans = 107374182, p = -1; int j1 = 1, pos1 = 0; for (; pos1 < n && j1 < nn; j1 *= 2, pos1++) { if ((i & j1) == 0) continue; int a = D[pos1][pos1] + Dp(i ^ j1); if (a < ans) { ans = a; p = i ^ j1; } int j2 = j1 * 2, pos2 = pos1 + 1; for (; pos2 < n && j2 < nn; j2 *= 2, pos2++) { if ((i & j2) == 0) continue; a = D[pos1][pos2] + Dp(i ^ (j1 | j2)); if (a < ans) { ans = a; p = i ^ (j1 | j2); } } break; } dp[i] = ans; prev[i] = p; return ans; } private int sqr(int i) { return i * i; } // //////////////////////////////////////////////////// // Utility functions private void initstreams() throws Throwable { //System.setIn(new FileInputStream("1")); in = new BufferedReader(new InputStreamReader(System.in, "ISO-8859-1")); pw = new PrintWriter(System.out); } BufferedReader in; PrintWriter pw; StringTokenizer st; String nextString() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextString()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextString()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextString()); } @Override public void run() { try { initstreams(); solve(); } catch (Throwable e) { sError = e; } finally { if (pw != null) pw.close(); } } private static Throwable sError; public static void main(String[] args) throws Throwable { Thread t = new Thread(new Main()); t.start(); t.join(); if (sError != null) throw sError; } }
np
8_C. Looking for Order
CODEFORCES
import java.util.*; import java.io.*; public class codeforces { public static void main(String[] args) throws Exception { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int[]a=sc.nextIntArray(n); LinkedList<Integer>ll=new LinkedList<Integer>(); for(int i=0;i<n;i++) { if(a[i]==1) { ll.addLast(a[i]); }else if(ll.isEmpty()) { ll.addLast(a[i]); }else { while(!(ll.getLast()==a[i]-1)) { ll.removeLast(); } ll.removeLast(); ll.addLast(a[i]); } int ii=0; for(int j:ll) { pw.print(j); if(ii!=ll.size()-1){ pw.print('.'); } ii++; } pw.println(); } } pw.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return this.z - other.z; } return this.y - other.y; } else { return this.x - other.x; } } } static long mod = 1000000007; static Random rn = new Random(); static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main16E { private FastScanner in; private PrintWriter out; public void solve() throws IOException { int n = in.nextInt(); double[][] a = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = in.nextDouble(); } } int k = 1 << n; double[] p = new double[k]; int[][] b = new int[n + 1][]; for (int i = 0; i <= n; i++) { b[i] = new int[comb(i, n)]; } int[] bl = new int[n + 1]; for(int i = 0; i < k; i++) { int c = c2(i); b[c][bl[c]] = i; bl[c]++; } p[k - 1] = 1; for (int i = n; i >= 2; i--) { for (int j = 0; j < b[i].length; j++) { int t = b[i][j]; double pm = 1; pm /= (i * (i - 1) / 2); for (int x = 0; x < n; x++) { for (int y = x + 1; y < n; y++) { if ((t & (1 << x)) > 0 && (t & (1 << y)) > 0) { p[t & ~(1 << x)] += p[t] * pm * a[y][x]; p[t & ~(1 << y)] += p[t] * pm * a[x][y]; } } } } } for (int i = 0; i < n; i++) { out.print(p[1 << i] + " "); } } int comb(int n, int m) { int res = 1; for (int i = 1; i <= n; i++) { res = res * (m - i + 1); res /= i; } return res; } int c2(int k) { int res = 0; while (k > 0) { if (k % 2 == 1) { res ++; } k /= 2; } return res; } public void run() { try { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] arg) { new Main16E().run(); } }
np
16_E. Fish
CODEFORCES
/* * Hopefully this is AC :D */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.LinkedList; import java.util.StringTokenizer; import java.util.Arrays; public class TwoSets { static ArrayList<Integer> g[]; static boolean visited[]; static int ans[],p[],orig[]; static int n,a,b; @SuppressWarnings("unchecked") public static void main(String args[] ) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter w = new PrintWriter(System.out); StringTokenizer st1 = new StringTokenizer(br.readLine()); n = ip(st1.nextToken()); a = ip(st1.nextToken()); b = ip(st1.nextToken()); g = new ArrayList[n]; visited = new boolean[n]; ans = new int[n]; p = new int[n]; orig = new int[n]; StringTokenizer st2 = new StringTokenizer(br.readLine()); for(int i=0;i<n;i++){ p[i] = ip(st2.nextToken()); orig[i] = p[i]; g[i] = new ArrayList<Integer>(); } Arrays.sort(p); boolean impossible = false; for(int i=0;i<n;i++){ int i1 = Arrays.binarySearch(p, a-p[i]); int i2 = Arrays.binarySearch(p, b-p[i]); if(i1 < 0 || i1 >= n) i1 = -1; if(i2 < 0 || i2 >= n) i2 = -1; if(i1 == -1 && i2 != -1) //if only (b-x) present then both must belong to set 1 g[i].add(i2); else if(i1 != -1 && i2 == -1) //if only (a-x) present then both must belong to set 0 g[i].add(i1); else if(i1 != -1 && i2 != -1){ //both present hence all 3 should be in same set,doesn't matter which g[i].add(i1); g[i].add(i2); } else{ //if none present then not possible to be in any set impossible = true; break; } } if(impossible){//if any element without both a-x and b-x found System.out.println("NO"); return; } //Edge between a and b means they must be present in same set //ans[i] =0 or ans[i] =1 means it must be compulsory be present in that set //ans[i] = -1 means no restrictions on it's set number LinkedList<Integer> q = new LinkedList();//Queue for(int i=0;i<n;i++){ if(visited[i] == false){ ArrayList<Integer> curq = new ArrayList<Integer>(); //contains indices of all nodes in this connected component curq.add(i); q.add(i); visited[i] = true; while(!q.isEmpty()){ int curr = q.remove(); int s = g[curr].size(); for(int j=0;j<s;j++){ if(!visited[g[curr].get(j)]){ visited[g[curr].get(j)] = true; curq.add(g[curr].get(j)); q.add(g[curr].get(j)); } } } boolean found = true; int s = curq.size(); int temp[] = new int[s]; for(int j=0;j<s;j++) temp[j] = p[curq.get(j)]; Arrays.sort(temp); int anss = -1; for(int j=0;j<s;j++){ int i3 = Arrays.binarySearch(temp, a - temp[j]); if(i3 < 0 || i3 >= n){ found = false; break; } } if(!found){ found = true; for(int j=0;j<s;j++){ int i3 = Arrays.binarySearch(temp, b - temp[j]); if(i3 < 0 || i3 >= n){ found = false; break; } } if(found) anss = 1; else{ impossible = true; break; } } else anss = 0; for(int j=0;j<s;j++) ans[curq.get(j)] = anss; } } if(!impossible){ w.println("YES"); for(int i=0;i<n;i++){ int i1 = Arrays.binarySearch(p, orig[i]); if(ans[i1] == -1) ans[i1] = 1; w.print(ans[i1] + " "); } w.println(); } else w.println("NO"); w.close(); } public static int ip(String s){ return Integer.parseInt(s); } }
linear
468_B. Two Sets
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class ProblemA { public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); String[] data = s.readLine().split(" "); int n = Integer.valueOf(data[0]); int a = Integer.valueOf(data[1]); int b = Integer.valueOf(data[2]); long[] h = new long[n]; String[] line = s.readLine().split(" "); for (int i = 0 ; i < n ; i++) { h[i] = Integer.valueOf(line[i]); } Arrays.sort(h); System.out.println(h[b] - h[b-1]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; import static java.util.Arrays.fill; import static java.util.Arrays.copyOfRange; import static java.util.Arrays.binarySearch; import static java.lang.Math.min; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.max; import java.util.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; public class Main { public static void main(String[] args) throws IOException { int n = in.nextInt(); int[] a = in.nextIntArray(n); sort(a); int ans = 0; boolean[] done = new boolean[n]; for(int i = 0; i < n; i ++) { if(done[i]) continue; ans ++; for(int j = i + 1; j < n; j ++) if(a[j] % a[i] == 0) done[j] = true; } out.write(ans + "\n"); out.flush(); } public static FastReader in = new FastReader(); public static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); public static void gcj(int cn, Object ans) throws IOException { System.out.print("Case #" + cn + ": " + ans + "\n"); } public static ArrayList <Integer>[] ALArrayI(int size) { ArrayList <Integer>[] l = new ArrayList[size]; for(int i = 0; i < size; i ++) l[i] = new ArrayList <> (); return l; } public static ArrayList <Long>[] ALArrayL(int size) { ArrayList <Long>[] l = new ArrayList[size]; for(int i = 0; i < size; i ++) l[i] = new ArrayList <> (); return l; } public static Integer[] integerList(int fi, int fo) { Integer[] l = new Integer[fo - fi]; for(int i = 0; i < fo - fi; i ++) l[i] = fi + i; return l; } } class Graph { TreeSet <Integer>[] g; public Graph(int n) { g = new TreeSet[n]; for(int i = 0; i < n; i ++) g[i] = new TreeSet <> (); } public void addEdge(int u, int v) { g[u].add(v); } public TreeSet <Integer> getAdj(int u) { return g[u]; } public int nodes() { return g.length; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i ++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) { Integer[] a = new Integer[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 String[] nextStringArray(int n) { String[] a = new String[n]; for(int i = 0; i < n; i ++) a[i] = next(); return a; } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
/* * PDPM IIITDM Jabalpur * Asutosh Rana */ import java.util.*; import java.io.*; import java.math.*; public class Main { long MOD = 1000000007; InputReader in;BufferedReader br;PrintWriter out; public static void main (String[] args) throws java.lang.Exception { Main solver = new Main(); solver.in = new InputReader(System.in); solver.br = new BufferedReader(new InputStreamReader(System.in)); solver.out = new PrintWriter(System.out); solver.solve(); solver.out.flush(); solver.out.close(); } public void solve(){ int tc = 1;//in.readInt(); for(int cas=1;cas<=tc;cas++){ int N = in.readInt(); int[] A = new int[N]; in.readInt(A); HashMap<Integer, Integer> H = new HashMap<>(); long sum = A[0], count = 1; BigInteger B = BigInteger.ZERO; H.put(A[0], 1); for(int i=1;i<N;i++){ // res = res + (count*A[i] - sum); B = B.add(BigInteger.valueOf(count*A[i]-sum)); if(!H.containsKey(A[i])) H.put(A[i], 0); H.put(A[i], H.get(A[i])+1); if(H.containsKey(A[i]-1)){ int k = H.get(A[i]-1); // res = res + (k*(A[i]-1) - k*A[i]); B = B.add(BigInteger.valueOf((k*(A[i]-1) - k*A[i]))); } if(H.containsKey(A[i]+1)){ int k = H.get(A[i]+1); B = B.add(BigInteger.valueOf((k*(A[i]+1) - k*A[i]))); // res = res + (k*(A[i]+1) - k*A[i]); } // out.println(res); sum+=A[i];count++; } // out.println("-1"); out.println(B); } } } 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 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 void readInt(int[] A){ for(int i=0;i<A.length;i++) A[i] = readInt(); } public long readLong() { 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 void readLong(long[] A){ for(int i=0;i<A.length;i++) A[i] = readLong(); } public double readDouble() { 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, readInt()); 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, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public char[] readCharA(){ return readString().toCharArray(); } 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); } }
nlogn
903_D. Almost Difference
CODEFORCES
import java.util.*; import java.io.*; public class D { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(int arr[],int l1,int r1,int l2,int r2) { int tmp[]=new int[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(long arr[],int l1,int r1,int l2,int r2) { long tmp[]=new long[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } static int n,m,k,uu[][],rr[][],dd[][],ll[][],dp[][][]; public static void main(String args[]) throws IOException { Scan input=new Scan(); StringBuilder ans=new StringBuilder(""); n=input.scanInt(); m=input.scanInt(); k=input.scanInt(); dp=new int[n][m][k]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { for(int kk=0;kk<k;kk++) { dp[i][j][kk]=-1; } } } uu=new int[n][m]; rr=new int[n][m]; dd=new int[n][m]; ll=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m-1;j++) { int tmp=input.scanInt(); rr[i][j]=tmp; ll[i][j+1]=tmp; } } for(int i=0;i<n-1;i++) { for(int j=0;j<m;j++) { int tmp=input.scanInt(); dd[i][j]=tmp; uu[i+1][j]=tmp; } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(k%2!=0) { ans.append(-1+" "); continue; } ans.append((2*solve(i,j,k/2))+" "); } ans.append("\n"); } System.out.println(ans); } public static int solve(int x,int y,int rem) { if(rem==0) { return 0; } if(dp[x][y][rem]!=-1) { return dp[x][y][rem]; } int ans=Integer.MAX_VALUE/10; if(uu[x][y]!=0) { ans=Math.min(ans,uu[x][y]+solve(x-1,y,rem-1)); } if(rr[x][y]!=0) { ans=Math.min(ans,rr[x][y]+solve(x,y+1,rem-1)); } if(dd[x][y]!=0) { ans=Math.min(ans,dd[x][y]+solve(x+1,y,rem-1)); } if(ll[x][y]!=0) { ans=Math.min(ans,ll[x][y]+solve(x,y-1,rem-1)); } dp[x][y][rem]=ans; return ans; } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; /** * Created by Brandt Henslee on 2/24/2015. */ public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] parsedString; int objectNum = 0; int xStart=0; int yStart=0; parsedString = in.readLine().split(" "); xStart = Integer.parseInt(parsedString[0]); yStart = Integer.parseInt(parsedString[1]); objectNum = Integer.parseInt(in.readLine()); int[] xLocs = new int[objectNum+1]; int[] yLocs = new int[objectNum+1]; int[] bitMasks = new int[1<<objectNum]; Arrays.fill(bitMasks, -1); int[] previous = new int[1<<objectNum]; xLocs[objectNum]=xStart; yLocs[objectNum]=yStart; for(int i=0; i<objectNum; i++){ parsedString = in.readLine().split(" "); xLocs[i] = Integer.parseInt(parsedString[0]); yLocs[i] = Integer.parseInt(parsedString[1]); } //go through all pairs and find time requirement for each pair of objects //the entry at point [i][j] is equal to the time it takes to get from point i to point j int[][] times = new int[objectNum+1][objectNum+1]; for(int i=0;i<=objectNum;i++){ for(int j=0; j<=objectNum;j++){ times[i][j] = times[j][i] = (xLocs[i]-xLocs[j])*(xLocs[i]-xLocs[j])+(yLocs[i]-yLocs[j])*(yLocs[i]-yLocs[j]); } } //each value in bitmasks represents the minimum time necessary to get //the unmasked bits //so bitmasks[5] (5=101) is the fastest time in which you can get //items 1 and 3 bitMasks[0] = 0; //collecting zero objects takes 0 time //1<<n makes the n+1 position in the bit string = 1 //1<<2 = 100 for (int i=0; i<(1<<objectNum); i++){ if(bitMasks[i]==-1) { }else{ for(int j=0; j<objectNum; j++){ if(((1<<j)&i) == 0){ //if our current j object hasn't been picked up yet int curState = (1<<j) | i; //ith state after picking up j object int curTime = bitMasks[i] + 2*times[objectNum][j]; //time required to get object j from bag at state i if(bitMasks[curState] == -1 || curTime < bitMasks[curState]){ bitMasks[curState] = curTime; //put fastest time in for gettingto our current state previous[curState] = i; } for(int k=0; k<objectNum; k++){ if(((1<<k) & curState) == 0){ //if the kth position in our current state hasn't been picked up int kState = ((1<<k) | curState); //curstate after picking pu kth object //kTime is time it takes to go from bag, to j, to k and back int kTime = bitMasks[i] + times[objectNum][j] + times[j][k] + times[k][objectNum]; if(bitMasks[kState] == -1 || kTime < bitMasks[kState]){ bitMasks[kState] = kTime; //put shortest tiem in for getting to kState previous[kState] = i; } } } break; } } } } int finalState = (1<<objectNum)-1; System.out.println(bitMasks[finalState]); Deque<Integer> outputQ = new ArrayDeque<Integer>(); outputQ.add(0); int curState = finalState; while(curState>0){ //1100 ^ 1101 = 0001 //difference is the objects picked up in this state but not in previous state int difference = curState ^ previous[curState]; int firstItem = -1; int secondItem = -1; for(int i=0; i<objectNum; i++){ if(((1<<i)&difference)>0){ //if the ith object was picked up in this state secondItem=firstItem; //keep track of how many items are picked up firstItem=i; } } if(secondItem!=-1){ //put in two items followed by a return to 0 outputQ.add(firstItem+1); outputQ.add(secondItem+1); outputQ.add(0); } else{ outputQ.add(firstItem + 1); outputQ.add(0); } curState = previous[curState]; } System.out.print(outputQ.removeLast()); while(!outputQ.isEmpty()){ System.out.print(" "); System.out.print(outputQ.removeLast()); } } }
np
8_C. Looking for Order
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class P287B{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; long n, k; void run(){ n=sc.nextLong(); k=sc.nextLong(); solve(); } void solve(){ long left=-1, right=k+1; for(; right-left>1;){ long m=(left+right)/2; long lb=k*(k+1)/2-(k-m)*(k-m+1)/2-(m-1); if(lb>=n){ right=m; }else{ left=m; } } // debug(left, right); println(""+(right>k?-1:right)); } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(deepToString(os)); } public static void main(String[] args){ Locale.setDefault(Locale.US); new P287B().run(); } }
logn
287_B. Pipeline
CODEFORCES
import java.io.*; import java.util.*; public class trafficerules { public static void main(String[] args) throws Exception { if ("Satayev".equals(System.getProperty("user.name"))) { long start = System.nanoTime(); new trafficerules().solve(new FileInputStream("input")); System.err.printf("Time elapsed: %d ms.\n", (System.nanoTime()-start)/1000000); } else new trafficerules().solve(System.in); } void solve(InputStream is) throws Exception { Scanner in = new Scanner(is); double a = in.nextDouble(), maxv = in.nextDouble(), s = in.nextDouble(), d = in.nextDouble(), w = in.nextDouble(); if (maxv < w) w = maxv; double t = 0; // v = at // s = att/2 double t1 = w / a; double s1 = a*t1*t1/2; double v1 = w; if ( s1 < d ) { v1 = w; if (v1 >= maxv) t1 += (d-s1)/v1; else { double tt = (maxv - v1)/a; double ss = v1*tt+a*tt*tt/2; ss *= 2; if (s1 + ss < d) t1 += tt*2 + (d-s1-ss)/maxv; else { ss = (d-s1)/2; // ss = v1*t + a*t*t/2; double A = a/2; double B = v1; double C = -ss; double D = B*B - 4 * A * C; tt = (-B + Math.sqrt(D))/2/A; t1 += tt*2; } } s1 = d; } if (s1 > d) { s1 = d; t1 = Math.sqrt(2*s1/a); v1 = a * t1; } t += t1; double t2 = (maxv - v1) / a; double s2 = v1*t2 + a*t2*t2/2; double v2 = maxv; if (s1 + s2 < s) { v2 = maxv; t2 += (s-s1-s2)/v2; } if (s1 + s2 > s) { s -= s1; // v = v1 + a*t // s = v1*t + a*t*t/2 double A = a/2; double B = v1; double C = -s; double D = B*B - 4*A*C; t2 = (-B + Math.sqrt(D))/2/A; } t += t2; System.out.println(t); } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CodeD { static class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } public String next() { while(!st.hasMoreTokens()) { String l = nextLine(); if(l == null) return null; st = new StringTokenizer(l); } 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 int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public void sortIntArray(int[] array) { Integer[] vals = new Integer[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortLongArray(long[] array) { Long[] vals = new Long[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortDoubleArray(double[] array) { Double[] vals = new Double[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } } static final Scanner sc; static final int n; static final int[][] distancias; static final int[] distancia; static final int[] dp; static final int[] dpNext; static final int X; static final int Y; static { sc = new Scanner(); X = sc.nextInt(); Y = sc.nextInt(); n = sc.nextInt(); distancias = new int[n][n]; distancia = new int[n]; dp = new int[1 << n]; Arrays.fill(dp, -1); dpNext = new int[1 << n]; } static int dp(int mascara) { if(dp[mascara] != -1) return dp[mascara]; int highest = -1; for(int i = 0, tmp = mascara; tmp != 0; i++, tmp >>= 1) { if((tmp & 1) == 1) { highest = i; break; } } if(highest == -1) return 0; int nextMsc = mascara ^ (1 << highest); int costHighest = distancia[highest]; int best = (costHighest << 1) + dp(nextMsc); int bestNext = nextMsc; for(int i = 0, tmp = nextMsc, iC = 1; tmp != 0; i++, tmp >>= 1, iC <<= 1) { if((tmp & 1) == 1) { int msc = nextMsc ^ iC; int possibleA = costHighest + distancias[highest][i] + distancia[i] + dp(msc); if(possibleA < best) { best = possibleA; bestNext = msc; } } } dpNext[mascara] = bestNext; return dp[mascara] = best; } public static void main(String[] args) { int[][] objetos = new int[n][2]; for(int i = 0; i < n; i++) { objetos[i][0] = sc.nextInt(); objetos[i][1] = sc.nextInt(); distancia[i] = (X - objetos[i][0]) * (X - objetos[i][0]) + (Y - objetos[i][1]) * (Y - objetos[i][1]); } for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) distancias[i][j] = (objetos[i][0] - objetos[j][0]) * (objetos[i][0] - objetos[j][0]) + (objetos[i][1] - objetos[j][1]) * (objetos[i][1] - objetos[j][1]); int ans = dp((1 << n) - 1); System.out.println(ans); int current = (1 << n) - 1; while(current != 0) { int next = dpNext[current]; int differents = next ^ current; System.out.print("0 "); for(int i = 0; i < n; i++) if((differents & (1 << i)) != 0) System.out.print((i + 1) + " "); current = next; } System.out.println("0"); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author George Marcus */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); if(N >= 0) out.println(N); else { N = Math.abs(N); int v1 = - (N / 10); int v2 = - (N / 100 * 10 + (N % 10)); out.println(Math.max(v1, v2)); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { return Integer.parseInt(nextString()); } public String nextString() { 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; } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.util.Scanner; public class composite { public static void main(String[] args) { Scanner s=new Scanner(System.in); int a=s.nextInt(); if(a%2==0) { a=a-4; System.out.println(4+" "+a); } else { a=a-9; System.out.println(9+" "+a); } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.io.*; import java.util.*; public class A { public static void main(String[] args){ FastScanner sc = new FastScanner(); long a = sc.nextLong(); long b = sc.nextLong(); long result = 0L; while(a != 0 && b != 0) { if(a > b) { result += a/b; a = a % b; } else { result += b/a; b = b % a; } long gcd = gcd(a, b); a /= gcd; b /= gcd; } System.out.println(result); } private static long gcd(long a, long b) { while(a != 0 && b != 0) { if(a < b) { long tmp = a; a = b; b = tmp; } a%=b; } return a + b; } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
constant
343_A. Rational Resistance
CODEFORCES
import java.io.*; import java.util.*; public class Solution { static MyScanner sc; private static PrintWriter out; static long M2 = 1_000_000_000L + 7; public static void main(String[] s) throws Exception { StringBuilder stringBuilder = new StringBuilder(); if (stringBuilder.length() == 0) { sc = new MyScanner(System.in); } else { sc = new MyScanner(new BufferedReader(new StringReader(stringBuilder.toString()))); } out = new PrintWriter(new OutputStreamWriter(System.out)); initData(); solve(); out.flush(); } private static void initData() { } private static void solve() throws IOException { int n = sc.nextInt(); int q = sc.nextInt(); int[] vv = sc.na(n); double[] ans = new double[n]; for (int i = 0; i < n; i++) { ans[i] = q; for (int s = 0; s < i; s++) { if (Math.abs(vv[i] - vv[s]) > q * 2) continue; double diff = 4 * q * q - Math.abs(vv[i] - vv[s]) * Math.abs(vv[i] - vv[s]); diff = Math.sqrt(diff); ans[i] = Math.max(ans[i], diff + ans[s]); } out.print(ans[i] + " "); } } private static void solveT() throws IOException { int t = sc.nextInt(); while (t-- > 0) { solve(); } } private static long gcd(long l, long l1) { if (l > l1) return gcd(l1, l); if (l == 0) return l1; return gcd(l1 % l, l); } private static long pow(long a, long b, long m) { if (b == 0) return 1; if (b == 1) return a; long pp = pow(a, b / 2, m); pp *= pp; pp %= m; return (pp * (b % 2 == 0 ? 1 : a)) % m; } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner(BufferedReader br) { this.br = br; } public MyScanner(InputStream in) { this(new BufferedReader(new InputStreamReader(in))); } void findToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } } String next() { findToken(); return st.nextToken(); } Integer[] nab(int n) { Integer[] k = new Integer[n]; for (int i = 0; i < n; i++) { k[i] = sc.fi(); } return k; } int[] na(int n) { int[] k = new int[n]; for (int i = 0; i < n; i++) { k[i] = sc.fi(); } return k; } long[] nl(int n) { long[] k = new long[n]; for (int i = 0; i < n; i++) { k[i] = sc.nextLong(); } return k; } int nextInt() { return Integer.parseInt(next()); } int fi() { String t = next(); int cur = 0; boolean n = t.charAt(0) == '-'; for (int a = n ? 1 : 0; a < t.length(); a++) { cur = cur * 10 + t.charAt(a) - '0'; } return n ? -cur : cur; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package pipeline; import java.util.Scanner; /** * * @author admin */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner scan=new Scanner(System.in); long n=scan.nextLong(),k=scan.nextLong(); if(n>((k-2)*(k-1))/2+k){ System.out.println("-1"); } else if(n==1){ System.out.println("0"); } else if(n<=k&&n>1){ System.out.println("1"); } else{ n-=k; long start=k-2; long x; long left=1,right=k-2; // System.out.println(left+" "+right); while(left<=right){ x=(left+right)/2; // System.out.println(x); if(n>cumSum(x, start)){ left=x+1; // System.out.println("if"); } else if(n<cumSum(x-1, start)){ right=x-1; // System.out.println("else if"); } else{ System.out.println(1+x); break; } } } } public static long cumSum(long x,long start){ return (x*(2*start+1-x))/2; } }
logn
287_B. Pipeline
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; //****Use Integer Wrapper Class for Arrays.sort()**** public class AG1 { public static void main(String[] Args){ FastReader scan=new FastReader(); int n=scan.nextInt(); int[] arr=new int[n]; for (int i = 0; i <n ; i++) { arr[i]=scan.nextInt(); } Arrays.sort(arr); boolean[] done=new boolean[n]; int ans=0; for(int i=0;i<n;i++){ if(!done[i]){ done[i]=true; ans++; for(int j=i+1;j<n;j++){ if(arr[j]%arr[i]==0){ done[j]=true; } } } } System.out.println(ans); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } 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; } } }
quadratic
1209_A. Paint the Numbers
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 TA { public void solve(long n) { long a = 0, b = 0; if (n % 2 == 0) { if (n % 4 == 0) { a = n / 2; b = n/ 2; } else { a = n / 2 - 1; b = n / 2 + 1; } } else { a = 4; b = n - a; while (b > 0 && (b % 3 != 0)) { a += 2; b = n - a; } } System.out.println(a + " " + b); } public static void main(String[] args) { FastScanner in = new FastScanner(); new TA().solve(in.nextLong()); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Teams { BufferedReader in; PrintWriter out; StringTokenizer st; Random rnd; class Pair implements Comparable<Pair> { int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if(a != p.a) { return -(a - p.a); } return (b - p.b); } } void solve() throws IOException { int n = nextInt(), k = nextInt(); Pair[] ps = new Pair[n]; for(int i = 0; i < n; i++) ps[i] = new Pair(nextInt(), nextInt()); Arrays.sort(ps); int curPlace = 1, res = 0; int[] places = new int[n]; for(int i = 0; i < n; i++) { if(i - 1 >= 0 && ps[i].compareTo(ps[i - 1]) != 0) ++curPlace; places[i] = curPlace; } for(int i = 0; i < n; i++) { if(places[i] == places[k - 1]) ++res; } out.println(res); } public static void main(String[] args) { new Teams().run(); } public void run() { try { final String className = this.getClass().getName().toLowerCase(); try { in = new BufferedReader(new FileReader(className + ".in")); out = new PrintWriter(new FileWriter(className + ".out")); } catch (FileNotFoundException e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } rnd = new Random(); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(42); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) return null; st = new StringTokenizer(line); } 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()); } }
nlogn
166_A. Rank List
CODEFORCES
import java.io.PrintWriter; import java.util.Scanner; public class D { public void run(Scanner in, PrintWriter out) { int n = in.nextInt(); int[][] graph = new int[n][n]; int m = in.nextInt(); for (int i = 0; i < m; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; graph[x][y] = 1; graph[y][x] = 1; } long[][] dyn = new long[1 << n][n]; for (int i = 0; i < n; i++) { dyn[1 << i][i] = 1; } long answer = 0; for (int mask = 1; mask < 1 << n; mask++) { int start = Integer.numberOfTrailingZeros(mask); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) == 0) continue; for (int j = start + 1; j < n; j++) { if (graph[i][j] > 0 && (mask & (1 << j)) == 0) { dyn[mask + (1 << j)][j] += dyn[mask][i]; } } if (graph[i][start] > 0) { answer += dyn[mask][i]; } } } out.println((answer - m)/ 2); } public static void main(String[] args) { try (Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out) ) { new D().run(in, out); } catch (Exception e) { e.printStackTrace(); } } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println(n + n / 2); } }
constant
84_A. Toy Army
CODEFORCES
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); for (int i = 0, t = sc.nextInt(); i < t; i++) { int n = sc.nextInt(); LinkedList<Set<Integer>> stack = new LinkedList<>(); for (int j = 0; j < n; j++) { printStack(stack); int val = sc.nextInt(); if (val == 1) { Set<Integer> branch = new HashSet<>(); branch.add(val); stack.push(branch); continue; } Set<Integer> branch = stack.peek(); assert branch != null; while (branch.contains(val) || branch.stream().max(Integer::compareTo).get() + 1 != val) { stack.pop(); branch = stack.peek(); } branch.add(val); } printStack(stack); } } public static void printStack(LinkedList<Set<Integer>> stack) { if (stack.size() == 0) { return; } StringBuilder sb = new StringBuilder(); for (int i = stack.size() - 1; i >= 0; i--) { sb.append(stack.get(i).stream().max(Integer::compareTo).get()).append("."); } System.out.println(sb.substring(0, sb.length() - 1)); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintWriter; import java.util.Arrays; import java.io.OutputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { double special(int[] loyalties, int[] levels, int playerlevelsum) { int poss = 1 << loyalties.length; double res = 0; for(int pos = 0; pos < poss; pos++) { double occurs = 1; int happy = 0; int badlevelssum = 0; for(int i = 0; i < loyalties.length; i++) { if(((pos >> i) & 1) == 1) { //happy senator happy++; occurs *= (double) loyalties[i] / 100; } else { //unhappy senator badlevelssum += levels[i]; occurs *= (double) (100 - loyalties[i]) / 100; } } double winprob = (happy <= levels.length / 2) ? (double) playerlevelsum / (playerlevelsum + badlevelssum) : 1; // System.err.println(pos + " " + (happy <= levels.length / 2) + " " + playerlevelsum + " " + (playerlevelsum + badlevelssum) + " " + occurs + " " + winprob + " " + occurs * winprob); res += occurs * winprob; } return res; } public void solve(int testNumber, InputReader in, OutputWriter out) { int senators = in.readInt(); // n, [1, 8] int sweets = in.readInt(); // k, [1, 8] int playerlevelsum = in.readInt(); // A, [1, 9999] int[] levels = new int[senators]; // [1, 9999] int[] loyalties = new int[senators]; // [0, 100] divisible by 10 IOUtils.readIntArrays(in, levels, loyalties); ArrayList<ArrayList<Integer>> possibilities = new ArrayList<>(Arrays.asList(new ArrayList<>())); for(int senator = 0; senator < senators; senator++) { ArrayList<ArrayList<Integer>> newpossibilities = new ArrayList<>(); for(ArrayList<Integer> al : possibilities) { int sumsofar = 0; for(int val : al) sumsofar += val; int minadd = senator == senators - 1 ? sweets - sumsofar : 0; for(int moar = minadd; moar <= sweets - sumsofar; moar++) { ArrayList<Integer> copy = new ArrayList<>(al); copy.add(moar); newpossibilities.add(copy); } } possibilities = newpossibilities; } double res = 0; // out.printLine(possibilities.size()); for(ArrayList<Integer> al : possibilities) { int[] newloyalties = new int[senators]; for(int i = 0; i < senators; i++) newloyalties[i] = Math.min(100, loyalties[i] + 10 * al.get(i)); // out.printLine(al); // out.printLine(newloyalties); // double works = dp(0, 0, newloyalties); double special = special(newloyalties, levels, playerlevelsum); double tot = special; res = Math.max(res, tot); } out.printLine(res); } } 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 int readInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if(c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while(!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if(filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void 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(); } } static class IOUtils { public static void readIntArrays(InputReader in, int[]... arrays) { for(int i = 0; i < arrays[0].length; i++) { for(int j = 0; j < arrays.length; j++) arrays[j][i] = in.readInt(); } } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.*; import java.awt.geom.Point2D; import java.text.*; import java.math.*; import java.util.*; public class Main implements Runnable { final String filename = ""; public void solve() throws Exception { int n = iread(), k = iread(), A = iread(); int[] b = new int[n], l = new int[n]; for (int i = 0; i < n; i++) { l[i] = iread(); b[i] = iread(); } int[] c = new int[n]; double ans = 0.0; for (int mask = 0; mask < 1 << (k + n - 1); mask++) { int t = 0; for (int i = 0; i < n + k - 1; i++) { if ((mask & (1 << i)) != 0) t++; } if (t != k) continue; int x = mask; for (int i = 0; i < n; i++) { c[i] = b[i]; while (x % 2 == 1) { c[i] += 10; x /= 2; } if (c[i] > 100) c[i] = 100; x /= 2; } double res = 0.0; for (int mask2 = 0; mask2 < 1 << n; mask2++) { int m = 0; double p = 1.0; t = 0; for (int i = 0; i < n; i++) { if ((mask2 & (1 << i)) == 0) { t += l[i]; p *= (100.0 - c[i]) / 100.0; } else { p *= c[i] / 100.0; m++; } } if (m * 2 > n) res += p; else res += p * A * 1.0 / (A + t); } ans = Math.max(ans, res); } DecimalFormat df = new DecimalFormat("0.0000000"); out.write(df.format(ans) + "\n"); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); // in = new BufferedReader(new FileReader(filename+".in")); // out = new BufferedWriter(new FileWriter(filename+".out")); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public int iread() throws Exception { return Integer.parseInt(readword()); } public double dread() throws Exception { return Double.parseDouble(readword()); } public long lread() throws Exception { return Long.parseLong(readword()); } BufferedReader in; BufferedWriter out; public String readword() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) { try { Locale.setDefault(Locale.US); } catch (Exception e) { } // new Thread(new Main()).start(); new Thread(null, new Main(), "1", 1 << 25).start(); } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Locale; import java.io.OutputStream; import java.io.PrintWriter; import java.util.AbstractList; import java.io.Writer; import java.util.Collection; import java.util.List; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Jacob Jiang */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); double[][] probability = in.next2DDoubleArray(n, n); double[] dp = new double[1 << n]; dp[dp.length - 1] = 1; for (int mask = (1 << n) - 1; mask >= 0; mask--) { int count = Integer.bitCount(mask); if (count <= 1) continue; double multi = 1. / calc(count); for (int i = 0; i < n; i++) { if (NumberUtils.checkBit(mask, i)) { for (int j = i + 1; j < n; j++) { if (NumberUtils.checkBit(mask, j)) { // i eat j dp[mask - (1 << j)] += multi * probability[i][j] * dp[mask]; // j eat i dp[mask - (1 << i)] += multi * probability[j][i] * dp[mask]; } } } } } double[] answer = new double[n]; for (int i = 0; i < n; i++) { answer[i] = dp[1 << i]; } out.printLine(ArrayUtils.asList(answer).toArray()); } private static int calc(int x) { return x * (x - 1) / 2; } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 double[] nextDoubleArray(int count) { double[] result = new double[count]; for (int i = 0; i < count; i++) { result[i] = nextDouble(); } return result; } public double[][] next2DDoubleArray(int n, int m) { double[][] result = new double[n][]; for (int i = 0; i < n; i++) { result[i] = nextDoubleArray(m); } return result; } } class OutputWriter { PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object obj) { writer.print(obj); } public void println() { writer.println(); } public void print(char c) { writer.print(c); } public void close() { writer.close(); } public void printItems(Object... items) { for (int i = 0; i < items.length; i++) { if (i != 0) { print(' '); } print(items[i]); } } public void printLine(Object... items) { printItems(items); println(); } } class NumberUtils { public static boolean checkBit(int mask, int bit) { return (mask & (1 << bit)) != 0; } } class ArrayUtils { private ArrayUtils() { } public static List<Double> asList(double[] array) { return new DoubleList(array); } private static class DoubleList extends AbstractList<Double> { double[] array; private DoubleList(double[] array) { this.array = array; } public Double set(int index, Double element) { double result = array[index]; array[index] = element; return result; } public Double get(int index) { return array[index]; } public int size() { return array.length; } } }
np
16_E. Fish
CODEFORCES
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Arrays; public class CF1238E { public static void main(String[] args) throws Exception { boolean local = System.getSecurityManager() == null; boolean async = false; Charset charset = Charset.forName("ascii"); FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset); Task task = new Task(io, new Debug(local)); if (async) { Thread t = new Thread(null, task, "dalt", 1 << 27); t.setPriority(Thread.MAX_PRIORITY); t.start(); t.join(); } else { task.run(); } if (local) { io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M"); } io.flush(); } public static class Task implements Runnable { final FastIO io; final Debug debug; int inf = (int) 1e8; long lInf = (long) 1e18; double dInf = 1e50; public Task(FastIO io, Debug debug) { this.io = io; this.debug = debug; } @Override public void run() { solve(); } int[][] fee; int m; long[] dp; int mask; int[][] maskFee; public void solve() { int n = io.readInt(); m = io.readInt(); char[] s = new char[n]; io.readString(s, 0); for (int i = 0; i < n; i++) { s[i] -= 'a'; } fee = new int[m][m]; for (int i = 1; i < n; i++) { fee[s[i]][s[i - 1]]++; fee[s[i - 1]][s[i]]++; } mask = (1 << m) - 1; maskFee = new int[m][mask + 1]; SubsetGenerator sg = new SubsetGenerator(); for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { sg.meanings[j] = fee[i][j]; } for (int j = 0; j <= mask; j++) { maskFee[i][j] = sg.next(); } } dp = new long[mask + 1]; Arrays.fill(dp, -1); dp[0] = 0; io.cache.append(dp(mask)); } BitOperator bo = new BitOperator(); public long dp(int s) { if (dp[s] == -1) { long extra = 0; int remainSet = mask - s; for (int j = 0; j < m; j++) { if (bo.bitAt(s, j) == 0) { continue; } extra += maskFee[j][remainSet]; } dp[s] = lInf; for (int j = 0; j < m; j++) { if (bo.bitAt(s, j) == 0) { continue; } int ss = bo.setBit(s, j, false); dp[s] = Math.min(dp[s], extra + dp(ss)); } } return dp[s]; } } /** * Bit operations */ public static class BitOperator { public int bitAt(int x, int i) { return (x >> i) & 1; } public int bitAt(long x, int i) { return (int) ((x >> i) & 1); } public int setBit(int x, int i, boolean v) { if (v) { x |= 1 << i; } else { x &= ~(1 << i); } return x; } public long setBit(long x, int i, boolean v) { if (v) { x |= 1L << i; } else { x &= ~(1L << i); } return x; } public long swapBit(long x, int i, int j) { int bi = bitAt(x, i); int bj = bitAt(x, j); x = setBit(x, i, bj == 1); x = setBit(x, j, bi == 1); return x; } public int swapBit(int x, int i, int j) { int bi = bitAt(x, i); int bj = bitAt(x, j); x = setBit(x, i, bj == 1); x = setBit(x, j, bi == 1); return x; } /** * Determine whether x is subset of y */ public boolean subset(long x, long y) { return intersect(x, y) == x; } /** * Merge two set */ public long merge(long x, long y) { return x | y; } public long intersect(long x, long y) { return x & y; } public long differ(long x, long y) { return x - intersect(x, y); } } public static class SubsetGenerator { private int[] meanings = new int[33]; private int[] bits = new int[33]; private int remain; private int next; public void setSet(int set) { int bitCount = 0; while (set != 0) { meanings[bitCount] = set & -set; bits[bitCount] = 0; set -= meanings[bitCount]; bitCount++; } remain = 1 << bitCount; next = 0; } public boolean hasNext() { return remain > 0; } private void consume() { remain = remain - 1; int i; for (i = 0; bits[i] == 1; i++) { bits[i] = 0; next -= meanings[i]; } bits[i] = 1; next += meanings[i]; } public int next() { int returned = next; consume(); return returned; } } public static class FastIO { public final StringBuilder cache = new StringBuilder(1 << 13); private final InputStream is; private final OutputStream os; private final Charset charset; private StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastIO(InputStream is, OutputStream os, Charset charset) { this.is = is; this.os = os; this.charset = charset; } public FastIO(InputStream is, OutputStream os) { this(is, os, Charset.forName("ascii")); } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public long readLong() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } long val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public double readDouble() { boolean sign = true; skipBlank(); if (next == '+' || next == '-') { sign = next == '+'; next = read(); } long val = 0; while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } if (next != '.') { return sign ? val : -val; } next = read(); long radix = 1; long point = 0; while (next >= '0' && next <= '9') { point = point * 10 + next - '0'; radix = radix * 10; next = read(); } double result = val + (double) point / radix; return sign ? result : -result; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } public int readLine(char[] data, int offset) { int originalOffset = offset; while (next != -1 && next != '\n') { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(byte[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (byte) next; next = read(); } return offset - originalOffset; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } public void flush() throws IOException { os.write(cache.toString().getBytes(charset)); os.flush(); cache.setLength(0); } public boolean hasMore() { skipBlank(); return next != -1; } } public static class Debug { private boolean allowDebug; public Debug(boolean allowDebug) { this.allowDebug = allowDebug; } public void assertTrue(boolean flag) { if (!allowDebug) { return; } if (!flag) { fail(); } } public void fail() { throw new RuntimeException(); } public void assertFalse(boolean flag) { if (!allowDebug) { return; } if (flag) { fail(); } } private void outputName(String name) { System.out.print(name + " = "); } public void debug(String name, int x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, long x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, double x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, int[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, long[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, double[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, Object x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, Object... x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.deepToString(x)); } } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.io.*; import java.util.*; public class Problem1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if (n < 0) { int first = n / 10; int second = (n / 100)*10 + (n % 10); if (first > second) System.out.println(first); else System.out.println(second); } else { System.out.println(n); } } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.util.Scanner; public class codef8 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int beacon[] = new int[1000001]; int pos[] = new int[num]; for (int i = 0; i < num; i++) { int position = sc.nextInt(); beacon[position] = sc.nextInt(); pos[i] = position; } int dp[] = new int[1000001]; int max = 0; if (beacon[0] != 0) dp[0] = 1; for (int i = 1; i <= 1000000; i++) { if (beacon[i] == 0) { dp[i] = dp[i-1]; } else { int j = i - beacon[i] - 1; if (j < 0) { dp[i] = 1; } else { dp[i] = dp[j] + 1; } } max = Math.max(max, dp[i]); } System.out.println(num-max); } }
linear
608_C. Chain Reaction
CODEFORCES
import java.util.Scanner; import java.util.HashSet; import java.io.PrintWriter; import java.io.File; public class FireAgain { public static void main(String[] args){ File in = new File("input.txt"); File out = new File("output.txt"); Scanner sc; PrintWriter pw; try{ sc = new Scanner(in); pw = new PrintWriter(out); }catch(Exception e){ sc = new Scanner(System.in); pw = null; } int max_x = sc.nextInt(); int max_y = sc.nextInt(); int start_num = sc.nextInt(); HashSet<int[]> start = new HashSet<int[]>(); for(int i=0; i<start_num; i++){ int[] cell = new int[2]; cell[0] = sc.nextInt(); cell[1] = sc.nextInt(); start.add(cell); } int[] result = new int[]{1,1}; int resultLen = 0; for(int i=1; i<=max_x; i++){ for(int j=1; j<=max_y; j++){ int[] sh = new int[]{1,1}; int shLen = Integer.MAX_VALUE; for(int[] fired: start){ int len = Math.abs(i - fired[0]) + Math.abs(j - fired[1]); if(len < shLen){ sh[0] = i; sh[1] = j; shLen = len; } } if(shLen > resultLen){ result[0] = sh[0]; result[1] = sh[1]; resultLen = shLen; } } } pw.print(result[0] + " " + result[1]); pw.close(); return ; } }
cubic
35_C. Fire Again
CODEFORCES
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package substring; import java.util.*; /** * * @author lav */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner scr = new Scanner(System.in); // System.out.println("entet strig"); String str = scr.nextLine(); int len =0; // System.out.println(str.substring(0, str.length())); for(int i=0;i<(str.length()-1);i++) { for(int j=i+1;j<str.length();j++) { String sub = str.substring(i, j); //int a=i+sub.indexOf(sub.charAt(0)); int ind = str.indexOf(sub, i+1); if(ind!=-1 && sub.length()>len ) { len = sub.length(); } } } System.out.println(len); // TODO code application logic here } }
cubic
23_A. You're Given a String...
CODEFORCES
/** * Date: 14 Sep, 2019 * Link: * * @author Prasad-Chaudhari * @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/ * @git: https://github.com/Prasad-Chaudhari */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Hashtable; import java.util.LinkedList; import java.util.Map; public class newProgram9 { public static void main(String[] args) throws IOException { // TODO code application logic here FastIO in = new FastIO(); int t = in.ni(); // int t = 1; while (t-- > 0) { int n = in.ni(); int m = in.ni(); int a[][] = new int[n][m]; int b[][] = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.ni(); b[j][i] = a[i][j]; } } for (int i = 0; i < m; i++) { Arrays.sort(b[i]); } Data d[] = new Data[m]; for (int i = 0; i < m; i++) { d[i] = new Data(-b[i][n - 1], i); } Arrays.sort(d); int col = Math.min(n, m); int c[][] = new int[n][col]; for (int i = 0; i < col; i++) { for (int j = 0; j < n; j++) { c[j][i] = a[j][d[i].b]; } } // for (int i = 0; i < n; i++) { // for (int j = 0; j < col; j++) { // System.out.print(c[i][j] + " "); // } // System.out.println(); // } System.out.println(ans(c, n, col, 0)); } in.bw.flush(); } private static int ans(int c[][], int n, int m, int col) { if (col == m) { int sum = 0; for (int i = 0; i < n; i++) { int max = 0; for (int j = 0; j < m; j++) { // System.out.print(c[i][j] + " "); max = Math.max(c[i][j], max); } sum += max; // System.out.println(); } // System.out.println(sum); return sum; } else { int max = ans(c, n, m, col + 1); int curr[] = new int[n]; for (int i = 0; i < n; i++) { curr[i] = c[i][col]; } for (int i = 1; i < n; i++) { for (int j = 0; j < n; j++) { c[j][col] = curr[(i + j) % n]; } max = Math.max(max, ans(c, n, m, col + 1)); } return max; } } static class FastIO { private final BufferedReader br; private final BufferedWriter bw; private String s[]; private int index; private final StringBuilder sb; public FastIO() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8")); s = br.readLine().split(" "); sb = new StringBuilder(); index = 0; } public int ni() throws IOException { return Integer.parseInt(nextToken()); } public double nd() throws IOException { return Double.parseDouble(nextToken()); } public long nl() throws IOException { return Long.parseLong(nextToken()); } public String next() throws IOException { return nextToken(); } public String nli() throws IOException { try { return br.readLine(); } catch (IOException ex) { } return null; } public int[] gia(int n) throws IOException { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public int[] gia(int n, int start, int end) throws IOException { validate(n, start, end); int a[] = new int[n]; for (int i = start; i < end; i++) { a[i] = ni(); } return a; } public double[] gda(int n) throws IOException { double a[] = new double[n]; for (int i = 0; i < n; i++) { a[i] = nd(); } return a; } public double[] gda(int n, int start, int end) throws IOException { validate(n, start, end); double a[] = new double[n]; for (int i = start; i < end; i++) { a[i] = nd(); } return a; } public long[] gla(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nl(); } return a; } public long[] gla(int n, int start, int end) throws IOException { validate(n, start, end); long a[] = new long[n]; for (int i = start; i < end; i++) { a[i] = nl(); } return a; } public int[][][] gwtree(int n) throws IOException { int m = n - 1; int adja[][] = new int[n + 1][]; int weight[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; int cost[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = i + 1; to[i] = ni(); cost[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; weight[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][count[from[i]] - 1] = to[i]; adja[to[i]][count[to[i]] - 1] = from[i]; weight[from[i]][count[from[i]] - 1] = cost[i]; weight[to[i]][count[to[i]] - 1] = cost[i]; count[from[i]]--; count[to[i]]--; } return new int[][][] { adja, weight }; } public int[][][] gwg(int n, int m) throws IOException { int adja[][] = new int[n + 1][]; int weight[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; int cost[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = ni(); to[i] = ni(); cost[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; weight[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][count[from[i]] - 1] = to[i]; adja[to[i]][count[to[i]] - 1] = from[i]; weight[from[i]][count[from[i]] - 1] = cost[i]; weight[to[i]][count[to[i]] - 1] = cost[i]; count[from[i]]--; count[to[i]]--; } return new int[][][] { adja, weight }; } public int[][] gtree(int n) throws IOException { int adja[][] = new int[n + 1][]; int from[] = new int[n - 1]; int to[] = new int[n - 1]; int count[] = new int[n + 1]; for (int i = 0; i < n - 1; i++) { from[i] = i + 1; to[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; } for (int i = 0; i < n - 1; i++) { adja[from[i]][--count[from[i]]] = to[i]; adja[to[i]][--count[to[i]]] = from[i]; } return adja; } public int[][] gg(int n, int m) throws IOException { int adja[][] = new int[n + 1][]; int from[] = new int[m]; int to[] = new int[m]; int count[] = new int[n + 1]; for (int i = 0; i < m; i++) { from[i] = ni(); to[i] = ni(); count[from[i]]++; count[to[i]]++; } for (int i = 0; i <= n; i++) { adja[i] = new int[count[i]]; } for (int i = 0; i < m; i++) { adja[from[i]][--count[from[i]]] = to[i]; adja[to[i]][--count[to[i]]] = from[i]; } return adja; } public void print(String s) throws IOException { bw.write(s); } public void println(String s) throws IOException { bw.write(s); bw.newLine(); } public void print(int s) throws IOException { bw.write(s + ""); } public void println(int s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(long s) throws IOException { bw.write(s + ""); } public void println(long s) throws IOException { bw.write(s + ""); bw.newLine(); } public void print(double s) throws IOException { bw.write(s + ""); } public void println(double s) throws IOException { bw.write(s + ""); bw.newLine(); } private String nextToken() throws IndexOutOfBoundsException, IOException { if (index == s.length) { s = br.readLine().split(" "); index = 0; } return s[index++]; } private void validate(int n, int start, int end) { if (start < 0 || end >= n) { throw new IllegalArgumentException(); } } } static class Data implements Comparable<Data> { int a, b; public Data(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Data o) { if (a == o.a) { return Integer.compare(b, o.b); } return Integer.compare(a, o.a); } public static void sort(int a[]) { Data d[] = new Data[a.length]; for (int i = 0; i < a.length; i++) { d[i] = new Data(a[i], 0); } Arrays.sort(d); for (int i = 0; i < a.length; i++) { a[i] = d[i].a; } } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
/** * @author derrick20 */ import java.io.*; import java.util.*; public class SameSumBlocks { public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); int[] pre = new int[N + 1]; var ansMap = new HashMap<Integer, ArrayDeque<Pair>>(); for (int j = 1; j <= N; j++) { pre[j] = pre[j - 1] + sc.nextInt(); for (int i = j; i >= 1; i--) { int sum = pre[j] - pre[i - 1]; /** we can actually perform the greedy scheduling as we read in the information! Because we are sweeping with an increasing right pointer, the moment a sum is found with this right endpoint, we can greedily place it into the schedule for a given sum "bucket", (if it's disjoint. Otherwise, we would be replacing one OR MORE previous intervals, which would only decrease or keep the same size, while reducing our future accessibility for adding intervals!) */ if (!ansMap.containsKey(sum) || ansMap.get(sum).getLast().r < i) { var dq = ansMap.computeIfAbsent(sum, val -> new ArrayDeque<>()); dq.add(new Pair(i, j, sum)); } } } var ans = new ArrayDeque<Pair>(); for (var group : ansMap.values()) { if (group.size() > ans.size()) { ans = group; } } out.println(ans.size()); for (Pair p : ans) { out.println(p); } out.close(); } static class Pair { int l, r, sum; public Pair(int ll, int rr, int ss) { l = ll; r = rr; sum = ss; } public String toString() { return l + " " + r; } } static class FastScanner { private int BS = 1<<16; private char NC = (char)0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt=1; boolean neg = false; if(c==NC)c=getChar(); for(;(c<'0' || c>'9'); c = getChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=getChar()) { res = (res<<3)+(res<<1)+c-'0'; cnt*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/cnt; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c>32) { res.append(c); c=getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c!='\n') { res.append(c); c=getChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=getChar(); if(c==NC)return false; else if(c>32)return true; } } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.util.*; import java.io.*; public class R574B { public static void main(String[] args) { JS scan = new JS(); long n = scan.nextInt(); long put = 1; long k = scan.nextInt(); long have = 0; long moves = 0; while(have < k) { have += put; put++; moves++; } long ans = 0; moves += have-k; ans += have-k; long lo = 0; long hi = n-moves; long bs = 0; while(lo <= hi) { //could she have eaten mid candies? long mid = (lo+hi)/2; long left = (n-moves)-mid+put-1; long rr = tri(left)-tri(put); if(rr <= mid) { bs = mid; hi = mid-1; } else { lo = mid+1; } } System.out.println(ans+bs); } static long tri(long n) { return n*(n-1)/2; } static class JS{ public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public JS() { in = new BufferedInputStream(System.in, BS); } public JS(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.util.*; public class Main{ public static void main(String[]args){ Scanner input=new Scanner(System.in); int x=input.nextInt(); if(x%4==0||x%7==0||x%47==0||x%74==0||x%744==0||x%474==0||x%447==0||x%477==0||x%474==0) System.out.println("YES"); else System.out.println("NO"); } }
constant
122_A. Lucky Division
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class ProblemB { public static int _gnum; public static int _cnum; public static int _needs; public static int _level; public static double _maxans = 0; public static double votedfs(int[][] grl, int g, int votes) { if (votes >= _needs) { return 1.0d; } if (g >= _gnum) { return 0.0d; } double agrees = (double)grl[g][1] / 100; return agrees * votedfs(grl, g+1, votes+1) + (1.0d - agrees) * votedfs(grl, g+1, votes); } public static double battledfs(int[][] grl, int g, int votes, int levels) { if (votes >= _needs) { return 0.0d; } if (g >= _gnum) { return (double)_level / (_level + levels); } double agrees = (double)grl[g][1] / 100; return agrees * battledfs(grl, g+1, votes+1, levels) + (1.0d - agrees) * battledfs(grl, g+1, votes, levels + grl[g][0]); } public static void candydfs(int[][] grl, int g, int n) { if (g >= _gnum) { double na = votedfs(grl, 0, 0) + battledfs(grl, 0, 0, 0); _maxans = Math.max(_maxans, na); return; } int rem = grl[g][1]; candydfs(grl, g+1, n); for (int i = 1 ; i <= n ; i++) { if (grl[g][1] < 100) { grl[g][1] += 10; candydfs(grl, g+1, n-i); } } grl[g][1] = rem; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); String[] d = line.split(" "); int gnum = Integer.valueOf(d[0]); int cnum = Integer.valueOf(d[1]); int level = Integer.valueOf(d[2]); _gnum = gnum; _cnum = cnum; _needs = (gnum + 1) / 2; if (gnum % 2 == 0) { _needs += 1; } _level = level; int[][] grl = new int[gnum][2]; for (int g = 0 ; g < gnum ; g++) { line = br.readLine(); String[] gg = line.split(" "); grl[g][0] = Integer.valueOf(gg[0]); grl[g][1] = Integer.valueOf(gg[1]); } for (int a = 0 ; a < gnum ; a++) { for (int b = 0 ; b < gnum - 1 ; b++) { if (grl[b][1] < grl[b+1][1]) { int tmp = grl[b][0]; grl[b][0] = grl[b+1][0]; grl[b+1][0] = tmp; tmp = grl[b][1]; grl[b][1] = grl[b+1][1]; grl[b+1][1] = tmp; } } } int ag = 0; int xnum = cnum; for (int g = 0 ; g < gnum ; g++) { int needs = (100 - grl[g][1]) / 10; int roy = 0; if (needs <= xnum) { xnum -= needs; roy = 100; } else { roy = grl[g][1] + xnum * 10; xnum = 0; } if (roy >= 100) { ag++; } } if (ag >= _needs) { System.out.println(1.0); return; } candydfs(grl, 0, _cnum); System.out.println(_maxans); br.close(); } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.StringTokenizer; public class problemA { public static long GCD(long number1, long number2) { //base case if(number2 == 0){ return number1; } return GCD(number2, number1%number2); } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); long b = Long.parseLong(st.nextToken()); long c = Long.parseLong(st.nextToken()); if(c-b<2 ||((c-b==2)&& GCD(c,b)==1) ){ System.out.println("-1"); }else{ if(b%2==0 ){ System.out.println(b+" "+(b+1)+" "+(b+2)); }else System.out.println((b+1)+" "+(b+2)+" "+(b+3)); } } }
constant
483_A. Counterexample
CODEFORCES
import java.util.*; public class AgainTwentyfive { public static void main(String[] args) { System.out.println("25"); } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.io.*; import java.util.*; public class A { BufferedReader in; StringTokenizer st; PrintWriter out; String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } void solve() throws Exception { int n = nextInt(); if(n%2==0) out.println("4 "+(n-4)); else out.println("9 "+(n-9)); } void run() { try { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { new A().run(); } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); String s=br.readLine(); String ss[]=s.split(" "); int arr[]=new int[n]; for(int i=0;i<n;i++) arr[i]=Integer.parseInt(ss[i]); Arrays.sort(arr); int coun=0,coun2=0; for(int i=arr[0],k=0;k<n;) { for(int j=k;j<n;j++) { if(arr[j]%i==0) { arr[j]=-1; coun2++; } } Arrays.sort(arr); k=coun2; coun++; if(coun2<n) i=arr[coun2]; else break; } System.out.println(coun); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
//package round196; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class A { InputStream is; PrintWriter out; String INPUT = ""; public static long pow(long a, long n, long mod) { // a %= mod; long ret = 1; int x = 63-Long.numberOfLeadingZeros(n); for(;x >= 0;x--){ ret = ret * ret % mod; if(n<<63-x<0)ret = ret * a % mod; } return ret; } void solve() { int n = ni(), m = ni(), K = ni(); if(m <= n/K*(K-1)+n%K){ out.println(m); }else{ int mod = 1000000009; int f = m - (n/K*(K-1)+n%K); out.println(((pow(2, f+1, mod) + mod - 2) * K + (m - f*K)) % mod); } } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
logn
338_A. Quiz
CODEFORCES
import java.io.*; import java.util.*; import java.util.function.Function; public class Main { static int N; static int[] U, V; static int[] A; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); N = sc.nextInt(); U = new int[N-1]; V = new int[N-1]; for (int i = 0; i < N - 1; i++) { U[i] = sc.nextInt()-1; V[i] = sc.nextInt()-1; } A = sc.nextIntArray(N, -1); System.out.println(solve() ? "Yes" : "No"); } static boolean solve() { if( A[0] != 0 ) return false; int[][] G = adjB(N, U, V); Map<Integer, Integer> parents = new HashMap<>(); for (Node node : orderFromRoot(N, G, 0)) { parents.put(node.a, node.parent); } ArrayDeque<Integer> q = new ArrayDeque<>(); for (int next : G[0]) { q.add(0); } int idx = 1; while(!q.isEmpty()) { int p = q.poll(); int a = A[idx++]; if( parents.get(a) != p ) { return false; } for (int next : G[a]) { if( next == p ) continue; q.add(a); } } return true; } static int[][] adjB(int n, int[] from, int[] to) { int[][] adj = new int[n][]; int[] cnt = new int[n]; for (int f : from) { cnt[f]++; } for (int t : to) { cnt[t]++; } for (int i = 0; i < n; i++) { adj[i] = new int[cnt[i]]; } for (int i = 0; i < from.length; i++) { adj[from[i]][--cnt[from[i]]] = to[i]; adj[to[i]][--cnt[to[i]]] = from[i]; } return adj; } static Node[] orderFromRoot(int N, int[][] G, int root) { ArrayDeque<Node> q = new ArrayDeque<>(); Node[] ret = new Node[N]; int idx = 0; q.add(new Node(-1, root)); while(!q.isEmpty()) { Node n = q.poll(); ret[idx++] = n; for (int next : G[n.a]) { if( next == n.parent ) continue; q.add(new Node(n.a, next)); } } return ret; } static class Node { int parent, a; public Node(int parent, int a) { this.parent = parent; this.a = a; } } @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()); } }
nlogn
1037_D. Valid BFS?
CODEFORCES
import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), sum = 0; Integer[] A = new Integer[n]; for (int i = 0 ; i < n ; i++) { A[i] = sc.nextInt(); sum += A[i]; } Arrays.sort(A, Collections.reverseOrder()); int c = 0, ans = 0; while (ans <= sum) { ans += A[c]; sum -= A[c]; c++; } System.out.println(c); } }
nlogn
160_A. Twins
CODEFORCES