src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.util.Scanner; public class Main { final static long Mod = 1000000009; static long n, m, k, t, l, u, ans; static Scanner cin = new Scanner(System.in); static long multi_mod(long base, long cur) { long res = 1; while(cur > 0) { if(cur % 2 == 1) res = (res * base) % Mod; cur >>= 1; base = (base * base) % Mod; } return res; } public static void main(String[] args) { n = cin.nextLong(); m = cin.nextLong(); k = cin.nextLong(); l = (k - 1)*(n / k) + n % k; if(m <= l) { System.out.println(m); } else { t = n / k; u = m - l; ans = (0 + (t - u) * (k - 1) + n % k) % Mod; ans = (ans + ((k)*((multi_mod(2, u + 1) - 2 + Mod) % Mod)) % Mod) % Mod; System.out.println(ans); } } }
logn
338_A. Quiz
CODEFORCES
import java.io.*; import java.util.*; public class C { static long mod=(long)(1e9+7); public static long powMod(long e,long b) { /*e=e%mod;*/ long res=1; while(e>0) { if(e%2==1) res=res*b%mod; e/=2; b=b*b%mod; } return res; } public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter pw=new PrintWriter(System.out); long x=sc.nextLong(),k=sc.nextLong(); if(x==0) { System.out.println(0); return; } if(k==0) { pw.println((2*x)%mod); pw.close();return; } long ans=2*x-1; ans=ans%mod; long b=powMod(k,2); ans=((ans*b)+1)%mod; pw.println(ans); pw.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(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(); } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main { public static int gcd(int a , int b) { if (b == 0) return 0; else { return a / b + gcd (b , a % b); } } public static void main(String[] args) { Scanner sc = new Scanner (System.in); int testCase = sc.nextInt(); while (testCase-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); if (n < m) { int temp = n; n = m; m = temp; } int ans = gcd (n , m); System.out.println(ans); } } }
constant
267_A. Subtractions
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Solve4 { public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int x= sc.nextInt(); int y= sc.nextInt(); int z= sc.nextInt(); int t1= sc.nextInt(); int t2= sc.nextInt(); int t3= sc.nextInt(); if(Math.abs(x-y)*t1 < (Math.abs(x-z)+Math.abs(x-y))*t2+3*t3 ) System.out.println("NO"); else System.out.println("YES"); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException ex) { } return s; } } }
constant
1054_A. Elevator or Stairs?
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author beginner1010 */ 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); TaskG1 solver = new TaskG1(); solver.solve(1, in, out); out.close(); } static class TaskG1 { final int mod = (int) 1e9 + 7; int[][][] dp; int rec(int mask, int time, int T, int genre, int[] ts, int[] gs) { if (time > T) return 0; if (time == T) return 1; if (mask == (1 << ts.length) - 1) return 0; int res = dp[genre][time][mask]; if (res != -1) return res; res = 0; for (int i = 0; i < ts.length; i++) { if ((mask & (1 << i)) == 0 && (mask == 0 || gs[i] != genre)) { res += rec(mask | (1 << i), time + ts[i], T, gs[i], ts, gs); if (res >= mod) res -= mod; } } return dp[genre][time][mask] = res; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] ts = new int[n]; int[] gs = new int[n]; int T = in.nextInt(); for (int i = 0; i < n; i++) { ts[i] = in.nextInt(); gs[i] = in.nextInt() - 1; } dp = new int[3][T][1 << n]; for (int[][] aux : dp) { for (int[] aux2 : aux) Arrays.fill(aux2, -1); } int ans = rec(0, 0, T, 0, ts, gs); out.println(ans); } } static class InputReader { private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private 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 (isWhitespace(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 (!isWhitespace(c)); return res * sgn; } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Scanner; public class A1 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); long size = scan.nextLong(); int numberOfSpecial = scan.nextInt(); long pageSize = scan.nextLong(); long[] specialItemsArray = new long[numberOfSpecial]; for (int i = 0; i < numberOfSpecial; i++) { specialItemsArray[i] = scan.nextLong(); } int totalRemoved = 0; int step = 0; long currentPageIndex = BigDecimal.valueOf(specialItemsArray[0]).divide(BigDecimal.valueOf(pageSize),2, RoundingMode.UP).setScale(0, RoundingMode.CEILING).longValue(); int specialItemArrayIndex = 1; while (specialItemArrayIndex < numberOfSpecial) { long pageIndex = BigDecimal.valueOf(specialItemsArray[specialItemArrayIndex] - totalRemoved).divide(BigDecimal.valueOf(pageSize),2,RoundingMode.UP).setScale(0, RoundingMode.CEILING).longValue(); if (currentPageIndex != pageIndex) { step++; totalRemoved = specialItemArrayIndex; currentPageIndex = BigDecimal.valueOf(specialItemsArray[specialItemArrayIndex] - totalRemoved).divide(BigDecimal.valueOf(pageSize),2,RoundingMode.UP).setScale(0, RoundingMode.CEILING).longValue(); } specialItemArrayIndex++; } System.out.println(step + 1); } }
linear
1190_A. Tokitsukaze and Discard Items
CODEFORCES
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class B { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(bf.readLine()); StringTokenizer st = new StringTokenizer(bf.readLine()); Integer[] a = new Integer[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); Arrays.sort(a); int[] b = new int[n]; for(int i=0; i<n; i++) b[i] = a[i].intValue(); boolean diff = false; boolean diff2 = false; Set<Integer> vals = new HashSet<Integer>(); vals.add(b[0]); int valval = 0; for(int i=1; i<n; i++) { vals.add(b[i]); if(b[i] == b[i-1]) { if(!diff) { diff = true; valval = b[i]; } else diff2 = true; } } long sum = 0; for(int i : b) sum += i; sum -= 1L*n*(n-1)/2; if(diff && !diff2) { if(!vals.contains((valval-1)) && (valval > 0)) { if(sum%2 == 0) out.println("cslnb"); else out.println("sjfnb"); } else out.println("cslnb"); } else if(diff2) out.println("cslnb"); else if(sum%2 == 0) out.println("cslnb"); else out.println("sjfnb"); // int n = Integer.parseInt(st.nextToken()); out.close(); System.exit(0); } }
linear
1190_B. Tokitsukaze, CSL and Stone Game
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nipuna Samarasekara */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { ///////////////////////////////////////////////////////////// public void solve(int testNumber, FastScanner in, FastPrinter out) { int n=in.nextInt(); if (n%2==0){ if (n%4==0) out.println(n/2+" "+n/2); else out.println(6+" "+(n-6)); } else{ out.println(9+" "+(n-9)); } } } class FastScanner extends BufferedReader { public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); // if (isEOF && ret < 0) { // throw new InputMismatchException(); // } // isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CoveredPointsCount { //UPSOLVE public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); long[] myArray = new long[2 * n]; for (int i = 0; i < n; i++) { StringTokenizer st1 = new StringTokenizer(br.readLine()); myArray[2 * i] = Long.parseLong(st1.nextToken()) * 2; myArray[2 * i + 1] = Long.parseLong(st1.nextToken()) * 2 + 1; } Arrays.sort(myArray); long[] ans = new long[n + 1]; int cnt = 0; for (int i = 0; i < 2 * n - 1; i++) { if (myArray[i] % 2 == 0) cnt++; else cnt--; ans[cnt] += (myArray[i + 1] + 1) / 2 - (myArray[i] + 1) / 2; } StringBuilder answer = new StringBuilder(); for (int i = 1; i < n + 1; i++) { answer.append(ans[i]); answer.append(" "); } System.out.println(answer); } }
nlogn
1000_C. Covered Points Count
CODEFORCES
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class e { public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } static ArrayList<String>list1=new ArrayList<String>(); static void combine(String instr, StringBuffer outstr, int index,int k) { if(outstr.length()==k) { list1.add(outstr.toString());return; } if(outstr.toString().length()==0) outstr.append(instr.charAt(index)); for (int i = 0; i < instr.length(); i++) { outstr.append(instr.charAt(i)); combine(instr, outstr, i + 1,k); outstr.deleteCharAt(outstr.length() - 1); } index++; } static ArrayList<ArrayList<Integer>>l=new ArrayList<>(); static void comb(int n,int k,int ind,ArrayList<Integer>list) { if(k==0) { l.add(new ArrayList<>(list)); return; } for(int i=ind;i<=n;i++) { list.add(i); comb(n,k-1,ind+1,list); list.remove(list.size()-1); } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static void main(String[] args) { // TODO Auto-generated method stub FastReader in=new FastReader(); HashMap<Integer,Integer>map=new HashMap<Integer,Integer>(); int n=in.nextInt(); int r=in.nextInt(); double theta=(double)360/(double)n; double b=1-((double)2/(double)(1-Math.cos((double)2*Math.PI/(double)n))); double x=Math.sqrt(1-b)-1; double ans=(double)r/(double)x; System.out.println(ans); } }
constant
1100_C. NN and the Optical Illusion
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.StringJoiner; import java.util.StringTokenizer; import java.util.function.Function; public class Main { static String S; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); S = sc.next(); System.out.println(solve()); } static int solve() { int ans = -1; int time = 1; int n = S.length(); for (int i = 1; i < n*2; i++) { if( S.charAt((i-1)%n) != S.charAt(i%n) ) { time++; } else { ans = Math.max(time, ans); time = 1; } } ans = Math.max(time, ans); if( ans == n*2 ) { return n; } else { return ans; } } @SuppressWarnings("unused") static class FastScanner { private BufferedReader reader; private StringTokenizer tokenizer; FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } long nextLong() { return Long.parseLong(next()); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArray(int n, int delta) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt() + delta; return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } } static <A> void writeLines(A[] as, Function<A, String> f) { PrintWriter pw = new PrintWriter(System.out); for (A a : as) { pw.println(f.apply(a)); } pw.flush(); } static void writeLines(int[] as) { PrintWriter pw = new PrintWriter(System.out); for (int a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { PrintWriter pw = new PrintWriter(System.out); for (long a : as) pw.println(a); pw.flush(); } static int max(int... as) { int max = Integer.MIN_VALUE; for (int a : as) max = Math.max(a, max); return max; } static int min(int... as) { int min = Integer.MAX_VALUE; for (int a : as) min = Math.min(a, min); return min; } static void debug(Object... args) { StringJoiner j = new StringJoiner(" "); for (Object arg : args) { if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j.toString()); } }
linear
1025_C. Plasticine zebra
CODEFORCES
import java.io.*; import java.util.*; /* * Raudel Ravelo Suarez * Problem: */ public class C { Scanner sc; BufferedReader in; PrintStream out; StringTokenizer tok; public C() throws NumberFormatException, IOException { //sc = new Scanner(System.in); //sc = new Scanner(new FileReader("in.txt")); in = new BufferedReader(new InputStreamReader(System.in)); //in = new BufferedReader(new FileReader("in.txt")); out = System.out; run(); } void run() throws NumberFormatException, IOException { //Add your code here int[] array; int n = nextInt(); array = new int[n]; int max = 0; int pos = 0; for(int i = 0; i <n; i++) { int l = nextInt(); if(l > max) { pos = i; max = l; } array[i] = l; } if(max == 1)array[pos] = 2; else array [pos] = 1; Arrays.sort(array); out.print(array[0]); for(int i = 1; i < n; i++) out.print(" " + array[i]); out.println(); } public static void main(String[] args) throws NumberFormatException, IOException { new C(); } String nextToken() throws IOException { if(tok ==null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
nlogn
135_A. Replacement
CODEFORCES
import java.util.Scanner; public class D { public static void main(String [] args){ Scanner in = new Scanner(System.in); long a = in.nextLong(); long b = in.nextLong(); String sa = Long.toBinaryString(a); String sb = Long.toBinaryString(b); long ans = 0; if(sb.length()-sa.length()>0){ for(int i = 0 ; i < sb.length() ; i++){ ans += 1l<<i; } System.out.println(ans); } else{ int num = -1 ; for(int i = 62 ; i >= 0 ; i--){ if((b & 1l << i) != 0 && ((~a) & (1l << i)) != 0){ num = i; break; } } ans = 0; if(num!=-1) for(int i = 0 ; i <= num ; i ++){ ans += 1l<<i; } System.out.println(ans); } } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.NoSuchElementException; public class Main { static PrintWriter out; static InputReader ir; static void solve() { int n = ir.nextInt(); int[] a = ir.nextIntArray(n); Arrays.sort(a); boolean[] used = new boolean[n]; int ct = 0; for (int i = 0; i < n; i++) { if (used[i]) continue; for (int j = i + 1; j < n; j++) { if (a[j] % a[i] == 0) used[j] = true; } ct++; } out.println(ct); } public static void main(String[] args) { ir = new InputReader(System.in); out = new PrintWriter(System.out); solve(); out.flush(); } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } static void tr(Object... o) { out.println(Arrays.deepToString(o)); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class C { static final int M = 1000000007; public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); long x = Long.parseLong(st.nextToken()); if(x == 0){ System.out.println(0); System.exit(0); } final long k = Long.parseLong(st.nextToken()); x = x%M; long ans = (exp(2, k+1)*x - (exp(2, k) - 1))%M; if(ans < 0) ans += M; System.out.println(ans); /* for(long i = 1234567890; i < 1234567999; i++){ ans = (exp(2, i+1)*x - (exp(2, i) - 1))%M; if(ans < 0) ans += M; System.out.println(ans); } /* System.out.println((k-1)/2); System.out.println(x); System.out.println(exp(2, k)); System.out.println(exp(2, k+1)); */ } public static long exp(long a, long n){ if(n == 0) return 1; if(n == 1) return a%M; if(n%2 == 0) return exp((a*a)%M, n/2); else return (a*exp((a*a)%M, (n-1)/2))%M; } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.*; import java.io.*; import java.math.BigInteger; public class C { static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; public static void main(String[] args) { in = new InputReader(System.in); out = new PrintWriter(System.out); long x = in.nextLong(); long k = in.nextLong(); if(x == 0){ out.println(0); } else{ long mul = pow(2, k + 1, mod); x %= mod; mul = (mul * x) % mod; long sub = pow(2, k, mod); sub = (sub - 1 + mod) % mod; mul = (mul - sub + mod) % mod; out.println(mul); } out.close(); } static class Pair implements Comparable<Pair> { int x,y; int i; Pair (int x,int y) { this.x = x; this.y = y; } Pair (int x,int y, int i) { this.x = x; this.y = y; this.i = i; } public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y==y; } return false; } @Override public String toString() { return x + " "+ y + " "+i; } /*public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); }*/ } static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } static long gcd(long x,long y) { if(y==0) return x; else return gcd(y,x%y); } static int gcd(int x,int y) { if(y==0) return x; else return gcd(y,x%y); } static long pow(long n,long p,long m) { long result = 1; if(p==0){ return 1; } while(p!=0) { if(p%2==1) result *= n; if(result >= m) result %= m; p >>=1; n*=n; if(n >= m) n%=m; } return result; } static long pow(long n,long p) { long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(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; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] colors = new int[n]; for (int i = 0; i < n; i++) { colors[i] = scanner.nextInt(); } Arrays.sort(colors); int amountOfColors = 0; for (int i = 0; i < n; i++) { if (colors[i] != 0){ amountOfColors++; int color = colors[i]; for (int j = i; j < n; j++) { if (colors[j] % color == 0){ colors[j] = 0; } } } } System.out.println(amountOfColors); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; public class Main { private static void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); List<List<Integer>> g = new ArrayList<>(n + 1); for (int i = 0; i < n + 1; i++) { g.add(new LinkedList<>()); } int degree1 = 0, degree2 = 0, root = 0; for (int i = 0; i < n - 1; i++) { int a = in.nextInt(); int b = in.nextInt(); g.get(a).add(b); g.get(b).add(a); if (g.get(a).size() > degree1) { if (a == root) { degree1 = g.get(a).size(); } else { degree2 = degree1; degree1 = g.get(a).size(); root = a; } } else if (g.get(a).size() > degree2) { degree2 = g.get(a).size(); } if (g.get(b).size() > degree1) { if (b == root) { degree1 = g.get(b).size(); } else { degree2 = degree1; degree1 = g.get(b).size(); root = b; } } else if (g.get(b).size() > degree2) { degree2 = g.get(b).size(); } } if (degree2 > 2) { out.print("No"); } else { out.println("Yes"); List<Integer> leaves = new LinkedList<>(); for (int i = 1; i <= n; i++) { if (i != root) { if (g.get(i).size() == 1) { leaves.add(i); } } } out.println(leaves.size()); for (int i : leaves) { out.println(root + " " + i); } } } private static void shuffleArray(int[] array) { int index; Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { index = random.nextInt(i + 1); if (index != i) { array[index] ^= array[i]; array[i] ^= array[index]; array[index] ^= array[i]; } } } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); solve(in, out); in.close(); out.close(); } private static class InputReader { private BufferedReader br; private StringTokenizer st; InputReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); st = null; } String nextLine() { String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } String next() { while (st == null || !st.hasMoreTokens()) { String line = nextLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } byte nextByte() { return Byte.parseByte(next()); } short nextShort() { return Short.parseShort(next()); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } private static class OutputWriter { BufferedWriter bw; OutputWriter(OutputStream os) { bw = new BufferedWriter(new OutputStreamWriter(os)); } void print(int i) { print(Integer.toString(i)); } void println(int i) { println(Integer.toString(i)); } void print(long l) { print(Long.toString(l)); } void println(long l) { println(Long.toString(l)); } void print(double d) { print(Double.toString(d)); } void println(double d) { println(Double.toString(d)); } void print(boolean b) { print(Boolean.toString(b)); } void println(boolean b) { println(Boolean.toString(b)); } void print(char c) { try { bw.write(c); } catch (IOException e) { e.printStackTrace(); } } void println(char c) { println(Character.toString(c)); } void print(String s) { try { bw.write(s); } catch (IOException e) { e.printStackTrace(); } } void println(String s) { print(s); print('\n'); } void close() { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
linear
981_C. Useful Decomposition
CODEFORCES
/** * DA-IICT * Author : Savaliya Sagar */ import java.io.*; import java.math.*; import java.util.*; public class C817 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { long n = nl(); long s = nl(); long l = 1; long r = n; long ans = 0; while(l<=r){ long mid = (l+r)/2; long sum = 0; long temp = mid; while(temp!=0){ sum += temp%10; temp/=10; } if(mid-sum<s){ ans = mid; l = mid+1; }else r = mid - 1; } out.println(n-ans); } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { new C817().run(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != // ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.util.*;import java.io.*;import java.math.*; public class Main { public static void process()throws IOException { int n=ni(); int[]A=new int[n]; int point = -1; for(int _i=0;_i<n;_i++){ int x =ni(); if(x==1){ point++; A[point]=1; } else{ while(x!=A[point]+1){ A[point]=0; point--; } } A[point]=x; for(int i=0;i<point;i++) p(A[i]+"."); pn(A[point]); } } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} int t=1; t=ni(); while(t-- > 0) {process();} out.flush();out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class SequenceTransformation { void solve() { int p = 1, n = in.nextInt(); while (n > 0) { if (n == 1) { out.print(p + " "); break; } if (n == 2) { out.print(p + " "); out.print(2 * p + " "); break; } if (n == 3) { out.print(p + " "); out.print(p + " "); out.print(3 * p + " "); break; } for (int i = 0; i < (n + 1) / 2; i++) { out.print(p + " "); } p *= 2; n /= 2; } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new SequenceTransformation().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
linear
1059_C. Sequence Transformation
CODEFORCES
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); // System.err.println(f(1)); // System.err.println(f(4)); int tc = sc.nextInt(); out: while(tc-->0){ long n = sc.nextInt(); long k = sc.nextLong(); if(n >= 32){ pw.println("YES " + (n-1)); continue; } long steps = 0; for (int i = 1;; i++) { long cnt = ((1l<<(i+1))-1); steps += ((1l<<(i))-1); if(steps > k) break; if(steps > f(n)) break; // long rem = k-((1<<i)-1); long rem = k-steps; // System.err.println("steps:" + steps + " cnt:" + cnt + " f:" + f(n-i)); // System.err.println("rem: " + (f(n) - steps - cnt*f(n-i))); if(rem <= f(n) - steps - cnt*f(n-i)){ pw.println("YES " + (n-i)); continue out; } } pw.println("NO"); } pw.flush(); pw.close(); } static long f(long n){ if(n == 0) return 0; long ans = 0; for (int i = 0; i < n; i++) { ans += 1l<<(2*i); } return ans; } static int[][] matMul(int[][] A, int[][] B, int p, int q, int r) //C(p x r) = A(p x q) x (q x r) -- O(p x q x r) { int[][] C = new int[p][r]; for(int i = 0; i < p; ++i) for(int j = 0; j < r; ++j) for(int k = 0; k < q; ++k) C[i][j] += A[i][k] * B[k][j]; return C; } /* * 4. Square Matrix Exponentiation */ static int[][] matPow(int[][] base, int p) { int n = base.length; int[][] ans = new int[n][n]; for(int i = 0; i < n; i++) ans[i][i] = 1; while(p != 0) { if((p & 1) == 1) ans = matMul(ans, base, n, n, n); base = matMul(base, base, n, n, n); p >>= 1; } return ans; } static int[][] packU(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) p[f]++; for (int t : to) p[t]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } static int pow(int n, int p){ int ans = 1; for (int i = 0; i < p; i++) { ans *= n; } return ans; } static int[][] packD(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) if(f != -1) p[f]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) if(from[i] != -1) {g[from[i]][--p[from[i]]] = to[i];} return g; } static void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int)(Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s)));} 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();} } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.*; import java.util.*; import java.util.LinkedList; import java.math.*; import java.lang.*; import java.util.PriorityQueue; import static java.lang.Math.*; @SuppressWarnings("unchecked") public class Solution implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long min(long a,long b) { if(a>b) { return b; } return a; } public static int min(int a,int b) { if(a>b) { return b; } return a; } public static long max(long a,long b) { if(a>b) { return a; } return b; } public static int max(int a,int b) { if(a>b) { return a; } return b; } static class pair { long x; long y; pair(long x,long y) { this.x = x; this.y = y; } public String toString() { return x+" "+y; } } public static int gcd(int a,int b) { if(a==0) return b; if(b==0) return a; while((a%=b)!=0&&(b%=a)!=0); return a^b; } static int num = (int)1e6; public static int random(int min,int max) { return min+(int)((max-min)*Math.random()); } float min(float a,float b) { if(a>b) { return b; } return a; } float dist(float x1,float y1,float x2,float y2) { return (float)Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); } float mod(float x) { if(x>0) { return x; } return -x; } public static long pow(long n,int pow) { long res = 1; while(pow!=0) { if((pow&1)==1) { res *= n; } n *= n; pow = pow>>1; } return res; } public static int bsearch(int n,long k) { int l = 1; int r = n; while(r>l) { int mid = (l+r+1)>>1; if(pow(2,mid+1)-mid-2<=k) { l = mid; } else { r = mid-1; } } if(pow(2,l+1)-l-2==0&&pow(2,l+1)-l-2==k) { return 0; } else if(pow(2,l+1)-l-2<=k) { return l; } return 0; } public static boolean valid(int n,long k,int steps) { long total_max = (pow(4,n)-1)/3; long cant_be = ((pow(4,n-steps)-1)/3)*(pow(2,steps+1)-1); long available = total_max-cant_be; if(available>=k) { return true; } return false; } public static void main(String args[]) throws Exception { new Thread(null, new Solution(),"Main",1<<26).start(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t1 = sc.nextInt(); while(t1-->0) { int n = sc.nextInt(); long k = sc.nextLong(); if(n>31) { out.println("YES "+(n-1)); continue; } int steps = bsearch(n,k); if(steps==0) { if(k==0) out.println("YES "+n); else out.println("NO"); } if(valid(n,k,steps)) { out.println("YES "+(n-steps)); } else { out.println("NO"); } } out.close(); } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.util.LinkedList; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.util.Collection; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Queue; import java.io.IOException; import java.io.FileOutputStream; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream("input.txt"); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream("output.txt"); } catch (IOException e) { throw new RuntimeException(e); } InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); Queue<Point> points = new LinkedList<Point>(); int[][] burnTime = new int[n][m]; boolean[][] visited = new boolean[n][m]; for (int i = 0; i < k; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; visited[x][y] = true; burnTime[x][y] = 0; points.add(new Point(x, y)); } int[] dx = new int[]{-1, 0, 0, 1}; int[] dy = new int[]{0, -1, 1, 0}; while (points.size() != 0) { Point cur = points.poll(); int x = cur.x; int y = cur.y; for (int i = 0; i < dx.length; i++) { int nextX = x + dx[i]; int nextY = y + dy[i]; if (nextX >= 0 && nextX < n && nextY >= 0 && nextY < m && (burnTime[x][y] + 1 < burnTime[nextX][nextY] || !visited[nextX][nextY])) { points.add(new Point(nextX, nextY)); visited[nextX][nextY] = true; burnTime[nextX][nextY] = burnTime[x][y] + 1; } } } int x, y; x = y = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (burnTime[i][j] > burnTime[x][y]) { x = i; y = j; } } } out.printf("%d %d", x + 1, y + 1); } } class Point { int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main (String[] args) throws IOException { BufferedReader reader = new BufferedReader (new InputStreamReader (System.in)); String[] splitted = reader.readLine().split(" "); int n = Integer.parseInt(splitted[0]); int m = Integer.parseInt(splitted[1]); int k = Integer.parseInt(splitted[2]); PriorityQueue<Integer> queue = new PriorityQueue<Integer> (1000, Collections.reverseOrder()); splitted = reader.readLine().split(" "); for (int ii = 0; ii < splitted.length; ii++) { queue.add(Integer.parseInt(splitted[ii])); } int counter = 0; int spot = k; while (spot < m && !queue.isEmpty()) { spot = spot + queue.poll() - 1; counter++; } if (spot < m) { System.out.println("-1"); } else { System.out.println(counter); } } }
nlogn
257_A. Sockets
CODEFORCES
import java.io.*; import java.util.*; import java.util.prefs.NodeChangeEvent; import java.math.*; public class Main implements Runnable { private BufferedReader in; private PrintWriter out; private StringTokenizer st; private Random rnd; private void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; int max = 0; for(int i = 0; i < n; i++) { a[i] = nextInt(); if(a[i] > a[max]) max = i; } int value = 1; if(a[max] == 1) value = 2; a[max] = value; Arrays.sort(a); for(int i = 0; i < n; i++) { out.print(a[i]); out.print(' '); } } public static void main(String[] args) { new Main().run(); } public void run() { try { try { in = new BufferedReader(new FileReader("INPUT.TXT")); out = new PrintWriter(new FileWriter("OUTPUT.TXT")); } catch(FileNotFoundException e) { in = new BufferedReader(new InputStreamReader((System.in))); out = new PrintWriter(System.out); } st = null; rnd = new Random(); solve(); out.close(); } catch(IOException e) { e.printStackTrace(); } } private String nextToken() throws IOException, NullPointerException { while(st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } 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()); } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.*; import java.util.*; public class Solution { private BufferedReader in; private PrintWriter out; private StringTokenizer st; void solve() throws IOException { String s = next(); HashSet<String> set = new HashSet<String>(); int ans = 0; for (int i = 0; i < s.length(); ++i) { for (int j = i + 1; j <= s.length(); ++j) { String t = s.substring(i, j); if (set.contains(t)) { ans = Math.max(ans, t.length()); } set.add(t); } } out.println(ans); } Solution() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); solve(); in.close(); out.close(); } private void eat(String str) { st = new StringTokenizer(str); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { new Solution(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.awt.Polygon; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.*; import java.util.Collection; public class Solution { /** * @param args * @throws IOException */ static StringTokenizer st; static BufferedReader reader; public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); int xs = NextInt(); int ys = NextInt(); int n = NextInt(); int x[] = new int[n]; int y[] = new int[n]; int single[] = new int[n]; int pair[][] = new int[n][n]; for (int i = 0; i < n; ++i) { x[i] = NextInt(); y[i] = NextInt(); } for (int i = 0; i < n; ++i) single[i] = 2 * dist(xs, ys, x[i], y[i]); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) pair[i][j] = dist(xs, ys, x[i], y[i]) + dist(x[i], y[i], x[j], y[j]) + dist(x[j], y[j], xs, ys); int dp[] = new int[1 << n]; int prev[] = new int[1 << n]; for (int mask = 0; mask < (1 << n); ++mask) { int p = -1; for (int i = 0; i < n; ++i) if (((mask >> i) & 1) != 0) { p = i; break; } if (p == -1) continue; dp[mask] = dp[mask ^ (1 << p)] + single[p]; prev[mask] = p; for (int j = p + 1; j < n; ++j) { if (((mask >> j) & 1) != 0) { int res = pair[p][j] + dp[mask ^ (1 << p) ^ (1 << j)]; if (res < dp[mask]) { dp[mask] = res; prev[mask] = p + 100 * j; } } } } int cur = (1 << n) - 1; System.out.printf("%d\n0 ", dp[cur]); while(cur != 0) { if (prev[cur] < 100) { System.out.printf("%d %d ", prev[cur] + 1, 0); cur ^= (1 << prev[cur]); } else { int i = prev[cur] / 100; int j = prev[cur] % 100; System.out.printf("%d %d %d ", i + 1, j + 1, 0); cur = cur ^ (1 << i) ^ (1 << j); } } } static int dist(int x0, int y0, int x1, int y1) { return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1); } static int NextInt() throws NumberFormatException, IOException { return Integer.parseInt(NextToken()); } static String NextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { st = new StringTokenizer(reader.readLine()); } return st.nextToken(); } }
np
8_C. Looking for Order
CODEFORCES
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class TaskA { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); new TaskA().solve(in, out); in.close(); out.close(); } private void solve(Scanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int answer = 0; int counter = k; int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = in.nextInt(); Arrays.sort(a); int[] b = Arrays.copyOf(a, a.length); for (int i = 0; i < n; ++i) a[i] = b[n - i - 1]; for (int i = 0; i < n; ++i) { if (counter < m) { counter += a[i] - 1; ++answer; } else break; } if (counter < m) out.println("-1"); else out.println(answer); } }
nlogn
257_A. Sockets
CODEFORCES
import java.util.*; import java.io.*; public class MotherOfDragons { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out, false); int n = scanner.nextInt(); double k = scanner.nextInt(); long[] graph = new long[n]; for(int i = 0; i < n; i++) { for(int j =0; j < n; j++) { int val = scanner.nextInt(); if (val == 1 || i == j) graph[i] |= 1L << j; } } //meet in the middle approach int szLeft = n/2; int szRight = n - szLeft; //max size of clique int[] dp = new int[1 << szLeft]; int maxMask = 1 << szLeft; //iterate over every left mask for(int mask = 1; mask <maxMask; mask++) { int curMask = mask; //go over every bit in the mask for(int j = 0; j < szLeft; j++) { if (((1 << j) & mask) > 0) { //update the union of reachability curMask &= graph[j + szRight] >> szRight; //can also attempt to pull from prev mask for max size //will not be optimal if end update happens, but otherwise is useful for dp dp[mask] = Math.max(dp[mask], dp[mask ^ (1 << j)]); } } //if the union of connectedness is the starting mask then we have a clique if (mask == curMask) { dp[mask] = Math.max(dp[mask],Integer.bitCount(mask)); } } int ans = 0; int rmaxMask = 1 << szRight; for(int mask = 0; mask < rmaxMask; mask++) { //mask to track if the current creates its own clique int curMask = mask; //mask to track the connection between the halves int oMask = maxMask -1; for(int j = 0; j < szRight; j++) { if (((1 << j) & mask) > 0) { //need to mask out the left side bits curMask &= (graph[j] & (rmaxMask-1)); //update corresp avail in the left side oMask &= graph[j] >> szRight; } } //not a clique portion if (curMask != mask) continue; //update answer ans = Math.max(ans, Integer.bitCount(mask) + dp[oMask]); } k/=ans; out.println(k * k * (ans * (ans-1))/2); out.flush(); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
np
839_E. Mother of Dragons
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class JavaApplication2 { public static void main(String[] args) throws IOException { BufferedReader sc= new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(sc.readLine().split(" ")[0]); ArrayList<String> tshr = new ArrayList<>(n); for (int i = 0; i < n; i++) { tshr.add(sc.readLine()); } for (int i = 0; i < n; i++) { tshr.remove(sc.readLine()); } System.out.println(tshr.size()); } }
linear
1000_A. Codehorses T-shirts
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.io.*; import java.util.*; public class B2 { String s = null; String[] ss = null; int[][] sn = null; int n = 0; double ans = 1; int A = 0; public void run() throws Exception{ BufferedReader br = null; File file = new File("input.txt"); if(file.exists()){ br = new BufferedReader(new FileReader("input.txt")); } else{ br = new BufferedReader(new InputStreamReader(System.in)); } s = br.readLine(); ss = s.split(" "); n = Integer.parseInt(ss[0]); int k = Integer.parseInt(ss[1]); A = Integer.parseInt(ss[2]); sn = new int[n][2]; for(int i = 0; i < n; i++){ s = br.readLine(); ss = s.split(" "); sn[i][0] = Integer.parseInt(ss[0]); sn[i][1] = Integer.parseInt(ss[1]); } int num = 0; for(int i = 0; i < n; i++){ num += (100 - sn[i][1]) / 10; } if(k >= num){ System.out.println("1.0"); return; } check(0, k, sn); ans = 1 - ans; System.out.println(ans); } void check(int i, int k, int[][] sn){ if(i == n && k == 0){ check2(sn); return; } else if(i == n && k > 0){ return; } else if(k == 0){ check(i+1, k, sn); } else{ for(int j = 0; j <= k; j++){ if(sn[i][1] + j * 10 <= 100){ int[][] nsn = copy(sn); nsn[i][1] += j * 10; check(i+1, k - j, nsn); } } } } void check2(int[][] sn){ List<Integer> target = new ArrayList<Integer>(); int h = 0; for(int i = 0; i < sn.length; i++){ if(sn[i][1] != 100){ target.add(i); } else{ h++; } } if(h > n / 2){ System.out.println("1.0"); System.exit(0); } int makemax = n - h; int makemin = (n+1)/2; double ma = 0; for(int i = makemax; i >= makemin; i--){ Combination c = new Combination(makemax, i); Iterator<int[]> ite = c.iterator(); while(ite.hasNext()){ int[] ret = ite.next(); Set<Integer> make = new HashSet<Integer>(); for(int j = 0; j < ret.length; j++){ if(ret[j] > 0){ make.add(target.get(j)); } } double makeK = 1; int B = 0; for(int j = 0; j < n; j++){ int perc = 0; if(make.contains(j)){ perc = 100 - sn[j][1]; B += sn[j][0]; } else{ perc = sn[j][1]; } makeK *= ((double)perc / 100); } ma += makeK * (1 - (double)A/(A+B)); } } ans = Math.min(ans, ma); } int[][] copy(int[][] sn){ int[][] csn = new int[sn.length][2]; for(int i = 0; i < sn.length; i++){ csn[i][0] = sn[i][0]; csn[i][1] = sn[i][1]; } return csn; } /** * @param args */ public static void main(String[] args) throws Exception{ B2 t = new B2(); t.run(); } public class Combination implements Iterable<int[]> { private final int max; private final int select; public Combination(int max, int select) { if (max < 1 || 62 < max) { throw new IllegalArgumentException(); } this.max = max; this.select = select; } public Iterator<int[]> iterator() { return new CombinationIterator(max, select); } private class CombinationIterator implements Iterator<int[]> { private long value; private final long max; private final int size; private int[] ret = null; public CombinationIterator(int max, int select) { this.value = (1L << select) - 1L; this.size = max; this.max = 1L << max; this.ret = new int[size]; } public boolean hasNext() { return value < max; } public int[] next() { long stock = value; value = next(value); for(int i = 0; i < size; i++){ long tmp = stock >> i; tmp = tmp & 1; ret[i] = (int)tmp; } return ret; } public void remove() { throw new UnsupportedOperationException(); } private long next(long source) { long param1 = smallestBitOf(source); long param2 = param1 + source; long param3 = smallestBitOf(param2); long param5 = (param3 / param1) >>> 1; return param5 - 1 + param2; } private long smallestBitOf(long source) { long result = 1L; while (source % 2 == 0) { source >>>= 1; result <<= 1; } return result; } } } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author phantom11 */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int N = in.nextInt(); int r = in.nextInt(); int i, j; BigDecimal initial = new BigDecimal(10); initial = initial.pow(100); int x[] = new int[N]; BigDecimal y[] = new BigDecimal[N]; Arrays.fill(y, initial); for (i = 0; i < N; i++) { x[i] = in.nextInt(); } for (i = 0; i < N; i++) { BigDecimal y2 = new BigDecimal(r); for (j = 0; j < i; j++) { if (Math.abs(x[i] - x[j]) <= 2 * r) { double xDiff = x[i] - x[j]; xDiff *= xDiff; xDiff = 4 * r * r - xDiff; xDiff = Math.sqrt(xDiff); BigDecimal yNew = new BigDecimal(xDiff); yNew = yNew.add(y[j]); if (yNew.compareTo(y2) > 0) { y2 = yNew; } } } y[i] = y2; } for (i = 0; i < N; i++) { out.print(y[i] + " "); } } } static class InputReader { BufferedReader in; StringTokenizer tokenizer = null; public InputReader(InputStream inputStream) { in = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } catch (IOException e) { return null; } } public int nextInt() { return Integer.parseInt(next()); } } 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 close() { writer.close(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class A { void solve(){ long k = readLong(); long x = 9; long y = 1; while(k > x * y){ k -= x * y; x *= 10; y++; } long w = k / y + (k % y == 0 ? 0 : 1); long e = (k % y - 1 % y + y) % y; long num = x/9 + w - 1; String s = Long.toString(num); out.print(s.charAt((int) e) - '0'); } public static void main(String[] args) { new A().run(); } void run(){ init(); solve(); out.close(); } BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init(){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } String readLine(){ try{ return in.readLine(); }catch(Exception ex){ throw new RuntimeException(ex); } } String readString(){ while(!tok.hasMoreTokens()){ String nextLine = readLine(); if(nextLine == null) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(); } int readInt(){ return Integer.parseInt(readString()); } long readLong(){ return Long.parseLong(readString()); } double readDouble(){ return Double.parseDouble(readString()); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Egor Kulikov (egor@egork.net) */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { out.printLine(25); } } static class InputReader { private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } }
constant
630_A. Again Twenty Five!
CODEFORCES
//package round113; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), k = ni(); int[][] d = new int[n][2]; for(int i = 0;i < n;i++){ d[i][0] = ni(); d[i][1] = ni(); } Arrays.sort(d, new Comparator<int[]>() { public int compare(int[] a, int[] b) { if(a[0] - b[0] != 0)return -(a[0] - b[0]); return a[1] - b[1]; } }); int b; for(b = k-1;b >= 0 && d[k-1][0] == d[b][0] && d[k-1][1] == d[b][1];b--); b++; int a; for(a = k-1;a < n && d[k-1][0] == d[a][0] && d[k-1][1] == d[a][1];a++); a--; out.println(a-b+1); } 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(); } public int ni() { try { int num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public long nl() { try { long num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public String ns() { try{ int b = 0; StringBuilder sb = new StringBuilder(); while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' ')); if(b == -1)return ""; sb.append((char)b); while(true){ b = is.read(); if(b == -1)return sb.toString(); if(b == '\r' || b == '\n' || b == ' ')return sb.toString(); sb.append((char)b); } } catch (IOException e) { } return ""; } public char[] ns(int n) { char[] buf = new char[n]; try{ int b = 0, p = 0; while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n')); if(b == -1)return null; buf[p++] = (char)b; while(p < n){ b = is.read(); if(b == -1 || b == ' ' || b == '\r' || b == '\n')break; buf[p++] = (char)b; } return Arrays.copyOf(buf, p); } catch (IOException e) { } return null; } double nd() { return Double.parseDouble(ns()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
nlogn
166_A. Rank List
CODEFORCES
import java.util.Scanner; public class CF275Ad2 { public static void main(String[] args) throws Exception { Scanner scan = new Scanner(System.in); long l = scan.nextLong(); long r = scan.nextLong(); long diff = r-l; boolean exists = false; if(diff >= 3){ if(l%2 == 1){ l++; } exists = true; } else if(diff == 2 && l%2 == 0){ exists = true; } else if(diff == 2 && gcd(l, r) > 1){ exists = true; } if(!exists){ System.out.println("-1"); } else { System.out.println(l + " " + (l+1) + " " + (l+2)); } } private static long gcd(long a, long b){ if(b == 0){ return 1; } return gcd(b, a % b); } }
constant
483_A. Counterexample
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; public class Main { static long MOD=1000000007; public static long pow(long x,long k){ long base=x%MOD; long res=1; while(k>0){ if((k&1)==1){ res=(res*base)%MOD; } base=(base*base)%MOD; k>>=1; } return res; } public static void main (String[] args) throws java.lang.Exception { Scanner scan=new Scanner(System.in); long x=scan.nextLong(); long k=scan.nextLong(); long MOD=1000000007; if(x==0){System.out.println(0);return;} x %= MOD; long a=pow(2L,k+1); long b=pow(2L,k); long res=(a*x)%MOD-b+1; if(res<0){res+=MOD;} System.out.println(res%MOD); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(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, ScanReader in, PrintWriter out) { int n = in.scanInt(); int r = in.scanInt(), temp; double max1; double high[] = new double[1002]; for (int i = 0; i < n; i++) { temp = in.scanInt(); max1 = high[temp] + ((high[temp] == 0) ? r : +(2 * r)); for (int j = temp - 1; j > temp - (2 * r) && j > 0; j--) { if (high[j] == 0) continue; max1 = Math.max(max1, high[j] + Math.sqrt((4 * r * r) - ((temp - j) * (temp - j)))); } for (int j = temp + 1; j <= 1000 && j < temp + (2 * r); j++) { if (high[j] == 0) continue; max1 = Math.max(max1, high[j] + Math.sqrt((4d * r * r) - (((j - temp) * (j - temp))))); } if (temp - (2 * r) > 0) max1 = Math.max(high[temp - (2 * r)], max1); if (temp + (2 * r) <= 1000) max1 = Math.max(high[temp + (2 * r)], max1); high[temp] = max1; out.print(max1 + " "); } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class EhabAndAnotherAnotherXorProblem implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); public void solve() { int initial = ask(0, 0); int a = 0, b = 0; if (initial == 0) { for (int i = 0; i < 30; i++) { int response = ask(1 << i, 0); if (response == -1) { a |= (1 << i); } } b = a; } else { for (int i = 29; i >= 0; i--) { int response = ask(a | (1 << i), b | (1 << i)); if (response != initial) { if (response == 1) { b |= (1 << i); } else { a |= (1 << i); } initial = ask(a, b); } else { response = ask(a | (1 << i), b); if (response == -1) { a |= (1 << i); b |= (1 << i); } } } } answer(a, b); } private int ask(int c, int d) { out.printf("? %d %d\n", c, d); out.flush(); return in.ni(); } private void answer(int a, int b) { out.printf("! %d %d\n", a, b); out.flush(); } @Override public void close() throws IOException { in.close(); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (EhabAndAnotherAnotherXorProblem instance = new EhabAndAnotherAnotherXorProblem()) { instance.solve(); } } }
logn
1088_D. Ehab and another another xor problem
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class CF1195B { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); private static StringTokenizer st; public static void main(String[] args) throws Exception { st = new StringTokenizer(reader.readLine()); long n = Long.parseLong(st.nextToken()); long k = Long.parseLong(st.nextToken()); long put = (-3 + (long)Math.sqrt((long)9 + 8 * k + 8 * n)) / 2; long eat = n - put; writer.write(Long.toString(eat)); writer.newLine(); writer.flush(); } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CoveredPointsCount { //UPSOLVE public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); long[] myArray = new long[2 * n]; for (int i = 0; i < n; i++) { StringTokenizer st1 = new StringTokenizer(br.readLine()); myArray[2 * i] = Long.parseLong(st1.nextToken()) * 2; myArray[2 * i + 1] = Long.parseLong(st1.nextToken()) * 2 + 1; } Arrays.sort(myArray); long[] ans = new long[n + 1]; int cnt = 0; for (int i = 0; i < 2 * n - 1; i++) { if (myArray[i] % 2 == 0) cnt++; else cnt--; ans[cnt] += (myArray[i + 1] + 1) / 2 - (myArray[i] + 1) / 2; } StringBuilder answer = new StringBuilder(); for (int i = 1; i < n + 1; i++) { answer.append(ans[i]); answer.append(" "); } System.out.println(answer); } }
nlogn
1000_C. Covered Points Count
CODEFORCES
import java.io.*; import java.lang.reflect.*; public class D { final int MOD = (int)1e9 + 7; final double eps = 1e-12; final int INF = (int)1e9; public D () { long L = sc.nextLong(); long R = sc.nextLong(); for (int i = 60; i >= 0; --i) { long b = (1L << i); long A = (L & b), B = (R & b); if (A != B) exit(2*b-1); } exit(0); } //////////////////////////////////////////////////////////////////////////////////// /* Dear hacker, don't bother reading below this line, unless you want to help me debug my I/O routines :-) */ static MyScanner sc = new MyScanner(); static class MyScanner { public String next() { newLine(); return line[index++]; } 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() { line = null; return readLine(); } public String [] nextStrings() { line = null; return readLine().split(" "); } public char [] nextChars() { return next().toCharArray(); } public Integer [] nextInts() { String [] L = nextStrings(); Integer [] res = new Integer [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } public Long [] nextLongs() { String [] L = nextStrings(); Long [] res = new Long [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Long.parseLong(L[i]); return res; } public Double [] nextDoubles() { String [] L = nextStrings(); Double [] res = new Double [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Double.parseDouble(L[i]); return res; } public String [] next (int N) { String [] res = new String [N]; for (int i = 0; i < N; ++i) res[i] = sc.next(); return res; } public Integer [] nextInt (int N) { Integer [] res = new Integer [N]; for (int i = 0; i < N; ++i) res[i] = sc.nextInt(); return res; } public Long [] nextLong (int N) { Long [] res = new Long [N]; for (int i = 0; i < N; ++i) res[i] = sc.nextLong(); return res; } public Double [] nextDouble (int N) { Double [] res = new Double [N]; for (int i = 0; i < N; ++i) res[i] = sc.nextDouble(); return res; } public String [][] nextStrings (int N) { String [][] res = new String [N][]; for (int i = 0; i < N; ++i) res[i] = sc.nextStrings(); return res; } public Integer [][] nextInts (int N) { Integer [][] res = new Integer [N][]; for (int i = 0; i < N; ++i) res[i] = sc.nextInts(); return res; } public Long [][] nextLongs (int N) { Long [][] res = new Long [N][]; for (int i = 0; i < N; ++i) res[i] = sc.nextLongs(); return res; } public Double [][] nextDoubles (int N) { Double [][] res = new Double [N][]; for (int i = 0; i < N; ++i) res[i] = sc.nextDoubles(); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error(e); } } private final BufferedReader r; MyScanner () { this(new BufferedReader(new InputStreamReader(System.in))); } MyScanner(BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = readLine().split(" "); index = 0; } } } static void print(Object o, Object... a) { printDelim(" ", o, a); } static void cprint(Object o, Object... a) { printDelim("", o, a); } static void printDelim (String delim, Object o, Object... a) { pw.println(build(delim, o, a)); } static void exit (Object o, Object... a) { print(o, a); exit(); } static void exit () { pw.close(); System.out.flush(); System.err.println("------------------"); System.err.println("Time: " + ((millis() - t) / 1000.0)); System.exit(0); } void NO() { throw new Error("NO!"); } //////////////////////////////////////////////////////////////////////////////////// static String build(String delim, Object o, Object... a) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : a) append(b, p, delim); return b.toString().trim(); } static void append(StringBuilder b, Object o, String delim) { if (o.getClass().isArray()) { int L = Array.getLength(o); for (int i = 0; i < L; ++i) append(b, Array.get(o, i), delim); } else if (o instanceof Iterable<?>) { for (Object p : (Iterable<?>)o) append(b, p, delim); } else b.append(delim).append(o); } //////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new D(); exit(); } static void start() { t = millis(); } static PrintWriter pw = new PrintWriter(System.out); static long t; static long millis() { return System.currentTimeMillis(); } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class e { public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } static ArrayList<String>list1=new ArrayList<String>(); static void combine(String instr, StringBuffer outstr, int index,int k) { if(outstr.length()==k) { list1.add(outstr.toString());return; } if(outstr.toString().length()==0) outstr.append(instr.charAt(index)); for (int i = 0; i < instr.length(); i++) { outstr.append(instr.charAt(i)); combine(instr, outstr, i + 1,k); outstr.deleteCharAt(outstr.length() - 1); } index++; } static ArrayList<ArrayList<Integer>>l=new ArrayList<>(); static void comb(int n,int k,int ind,ArrayList<Integer>list) { if(k==0) { l.add(new ArrayList<>(list)); return; } for(int i=ind;i<=n;i++) { list.add(i); comb(n,k-1,ind+1,list); list.remove(list.size()-1); } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static void main(String[] args) { // TODO Auto-generated method stub FastReader in=new FastReader(); HashMap<Integer,Integer>map=new HashMap<Integer,Integer>(); int n=in.nextInt(); int r=in.nextInt(); double theta=(double)360/(double)n; double b=1-((double)2/(double)(1-Math.cos((double)2*Math.PI/(double)n))); double x=Math.sqrt(1-b)-1; double ans=(double)r/(double)x; System.out.println(ans); } }
constant
1100_C. NN and the Optical Illusion
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author ankur */ 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(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long k = in.nextLong(); HashMap<Long, Integer> hm = new HashMap<>(); long ar[] = in.nextLongArray(n); for (int i = 0; i < n; i++) { long dist = ar[i] + k; long min = k; for (int j = 0; j < n; j++) { min = Math.min(min, Math.abs(ar[j] - dist)); } if (min == k) { hm.put(dist, 1); } dist = ar[i] - k; min = k; for (int j = 0; j < n; j++) { min = Math.min(min, Math.abs(ar[j] - dist)); } if (min == k) { hm.put(dist, 1); } } out.print(hm.size()); } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar; private int snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { //*-*------clare------ //remeber while comparing 2 non primitive data type not to use == //remember Arrays.sort for primitive data has worst time case complexity of 0(n^2) bcoz it uses quick sort //again silly mistakes ,yr kb tk krta rhega ye mistakes //try to write simple codes ,break it into simple things //knowledge>rating /* public class Main implements Runnable{ public static void main(String[] args) { new Thread(null,new Main(),"Main",1<<26).start(); } public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC();//chenge the name of task solver.solve(1, in, out); out.close(); } */ if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import javafx.util.Pair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; public class ElongatedMatrix { private static int n; /** * if the rows are arranged in some permutation [p_1, p_2,...i,j,...p_n], * 1!=i!=j!=n, minCost[i][j] is the min k for any permutation with i&j adjacent **/ private static int[][] minCost; /** * minCostEndpoints[i][j] is the min k for any permutation such that * the rows are arranged in some permutation [i, p_2, ... p_{n-1}, j], **/ private static int[][] minCostEndpoints; /** * Max k of a path over a subset of all rows ending at a certain vertex * The first 16 bits of the key represent the subset. Node n is in the subset iff (x & (2 << n))!=0 * key/(1<<16) is the end vertex number */ private static HashMap<Integer, Integer> costs = new HashMap<>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int[] params = Arrays.stream(br.readLine().split(" ")) .mapToInt(x -> Integer.parseInt(x)).toArray(); n = params[0]; int m = params[1]; int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) { matrix[i] = Arrays.stream(br.readLine().split(" ")) .mapToInt(x -> Integer.parseInt(x)).toArray(); } minCost = new int[n][n]; minCostEndpoints = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i > j) { minCost[i][j] = Integer.MAX_VALUE; for (int k = 0; k < m; k++) { int diff = Math.abs(matrix[i][k] - matrix[j][k]); if (diff < minCost[i][j]) { minCost[i][j] = diff; } } minCost[j][i] = minCost[i][j]; } minCostEndpoints[i][j] = Integer.MAX_VALUE; for (int k = 0; k < m - 1; k++) { int diff = Math.abs(matrix[i][k + 1] - matrix[j][k]); if (diff < minCostEndpoints[i][j]) { minCostEndpoints[i][j] = diff; } } } } int maxCost = n == 1 ? minCostEndpoints[0][0] : 0; for (int i = 0; i < n; i++) { costs.clear(); for (int j = 0; j < n; j++) { if (i != j) { int bitmask = (1 << i) | (1 << j); int state = bitmask + (j << 16); costs.put(state, minCost[i][j]); } } for (int j = 0; j < n; j++) { if (i != j) { if (minCostEndpoints[i][j] <= maxCost) { continue; } else { int pathCost = Math.min(minCostEndpoints[i][j], findMaxCost(i, j, (1 << n) - 1)); maxCost = Math.max(maxCost, pathCost); } } } } System.out.println(maxCost); br.close(); } //find the minimum cost starting at st, ending at end, and using only the rows in set private static int findMaxCost(int st, int end, int set) { int state = set + (end << 16); if (costs.containsKey(state)) { return costs.get(state); } int maxCost = 0; for (int i = 0; i < n; i++) { if (i != st && i != end && (set & (1 << i)) != 0) { int setWithoutEnd = set - (1 << end); int pathCost = Math.min(findMaxCost(st, i, setWithoutEnd), minCost[i][end]); maxCost = Math.max(pathCost, maxCost); } } costs.put(state, maxCost); return maxCost; } }
np
1102_F. Elongated Matrix
CODEFORCES
import java.util.*; import java.io.*; public class Main { static final int MAXN = 24; int[] x = new int[MAXN]; int[] y = new int[MAXN]; int[][] dist = new int[MAXN][MAXN]; int[] single = new int[MAXN]; int sqr(int x) { return x * x; } void run(int nT) { int xs = cin.nextInt(); int ys = cin.nextInt(); int n = cin.nextInt(); for (int i = 0; i < n; ++i) { x[i] = cin.nextInt(); y[i] = cin.nextInt(); } for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { dist[i][j] = sqr(x[i] - xs) + sqr(y[i] - ys) + sqr(x[i] - x[j]) + sqr(y[i] - y[j]) + sqr(x[j] - xs) + sqr(y[j] - ys); } } for (int i = 0; i < n; ++i) { single[i] = (sqr(x[i] - xs) + sqr(y[i] - ys)) * 2; } int[] dp = new int[1 << n]; int[] pre = new int[1 << n]; int tot = 1 << n; for (int s = 1; s < tot; ++s) { int i; for (i = 0; i < n; ++i) { if ((s & (1 << i)) != 0) break; } dp[s] = dp[s^(1<<i)] + single[i]; pre[s] = i + 1; for (int j = i + 1; j < n; ++j) { if ((s & (1 << j)) != 0) { int cur = dp[s^(1 << i) ^(1<<j)] + dist[i][j]; if (cur < dp[s]) { dp[s] = cur; pre[s] = (i + 1) * 100 + (j + 1); } } } } out.println(dp[tot - 1]); int now = tot - 1; out.print("0"); while (now > 0) { int what = pre[now]; int px = what % 100 - 1; int py = what / 100 - 1; if (px >= 0) { out.print(" "); out.print(px + 1); now ^= 1 << px; } if (py >= 0) { out.print(" "); out.print(py + 1); now ^= 1 << py; } out.print(" "); out.print("0"); } out.println(""); } public static void main(String[] argv) { Main solved = new Main(); int T = 1; // T = solved.cin.nextInt(); for (int nT = 1; nT <= T; ++nT) { solved.run(nT); } solved.out.close(); } InputReader cin = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); } class InputReader { BufferedReader reader; 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()); } }
np
8_C. Looking for Order
CODEFORCES
//package timus; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.StreamTokenizer; import java.io.Writer; import java.math.BigInteger; import java.util.Arrays; public class Abra { public static void main(String[] args) throws IOException { new Abra().run(); } StreamTokenizer in; PrintWriter out; boolean oj; void init() throws IOException { oj = System.getProperty("ONLINE_JUDGE") != null; Reader reader = oj ? new InputStreamReader(System.in) : new FileReader( "input.txt"); Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt"); in = new StreamTokenizer(new BufferedReader(reader)); out = new PrintWriter(writer); } void run() throws IOException { long beginTime = System.currentTimeMillis(); init(); solve(); out.flush(); } void printMem() { if (!oj) { System.out.println("Memory used = " + (Runtime.getRuntime().totalMemory() - Runtime .getRuntime().freeMemory())); } } int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } String nextString() throws IOException { in.nextToken(); return in.sval; } double nextDouble() throws IOException { in.nextToken(); return in.nval; } long deg(long x, long y) { long a = x; for (long i = 2; i <= y; i++) { a *= x; } return a; } long fact(long x) { long a = 1; for (long i = 2; i <= x; i++) { a *= i; } return a; } long digitSum(String x) { long a = 0; for (int i = 0; i < x.length(); i++) { a += x.codePointAt(i) - 48; } return a; } long digitSum(long x) { long a = 0; while (x > 0) { a += x % 10; x /= 10; } return a; } long digitMul(long x) { long a = 1; while (x > 0) { a *= x % 10; x /= 10; } return a; } int digitCubesSum(int x) { int a = 0; while (x > 0) { a += (x % 10) * (x % 10) * (x % 10); x /= 10; } return a; } double pif(double ax, double ay, double bx, double by) { return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by)); } double getPosPart(double x) { if (x <= 0) return 0; else return x; } double max(double x, double y) { if (x > y) return x; else return y; } long gcd(long a, long b) { if (a < b) { long c = b; b = a; a = c; } while (a % b != 0) { a = a % b; if (a < b) { long c = b; b = a; a = c; } } return b; } int gcd(int a, int b) { if (a < b) { int c = b; b = a; a = c; } while (a % b != 0) { a = a % b; if (a < b) { int c = b; b = a; a = c; } } return b; } long lcm(long a, long b) throws IOException { return a * b / gcd(a, b); } int lcm(int a, int b) throws IOException { return a * b / gcd(a, b); } int countOccurences(String x, String y) { int a = 0, i = 0; while (true) { i = y.indexOf(x); if (i == -1) break; a++; y = y.substring(i + 1); } return a; } int[] primes; int findPrimes(int x) { boolean[] forErato = new boolean[x]; primes = new int[x]; int l = 0, j = 0; for (int i = 2; i < x; i++) { if (forErato[i]) continue; l++; primes[l] = i; j = i * 2; while (j < x) { forErato[j] = true; j += i; } } return l; } int rev(int x) { int a = 0; while (x > 0) { a = a * 10 + x % 10; x /= 10; } return a; } class myDate { int d, m, y; public myDate(int da, int ma, int ya) { d = da; m = ma; y = ya; } int[] ml = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; void inc() { if ((d == 31) && (m == 12)) { y++; d = 1; m = 1; } else { if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) { ml[1] = 29; } if (d == ml[m - 1]) { m++; d = 1; } else d++; } } } int partition(int n, int l, int m) {// n - sum, l - length, m - every part // <= m if (n < l) return 0; if (n < l + 2) return 1; if (l == 1) return 1; int c = 0; for (int i = Math.min(n - l + 1, m); i >= (n + l - 1) / l; i--) { c += partition(n - i, l - 1, i); } return c; } String s; int l; void solve() throws IOException { s = nextString(); l = s.length(); int max = 0; for (int i = 0; i < l - 1; i++) { for (int j = i + 1; j < l; j++) { if (countOccurences(s.substring(i, j), s) > 1) if (j - i > max) max = j - i; } } out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES
//package contese_476; import java.util.*; public class q1 { int m=(int)1e9+7; public class Node { int a; int b; public void Node(int a,int b) { this.a=a; this.b=b; } } public int mul(int a ,int b) { a=a%m; b=b%m; return((a*b)%m); } public int pow(int a,int b) { int x=1; while(b>0) { if(b%2!=0) x=mul(x,a); a=mul(a,a); b=b/2; } return x; } public static long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); HashMap<Integer,Integer> h=new HashMap(); //HashMap<Integer,Integer> h1=new HashMap(); int[] a=new int[n]; int x=sc.nextInt(); for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(h.get(a[i])==null) { h.put(a[i], 1); //h1.put(a[i],i); } else { System.out.print(0); System.exit(0); } } for(int i=0;i<n;i++) { int num=a[i]&x; if(num==a[i]) continue; if(h.get(num)==null) continue; else { System.out.print(1); System.exit(0); } } for(int i=0;i<n;i++) { int num=a[i]&x; if(num==a[i]) continue; if(h.get(num)==null) h.put(num, 1); else { System.out.print(2); System.exit(0); } } System.out.print(-1); } }
linear
1013_B. And
CODEFORCES
import java.util.Scanner; public class A235 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); long n = sc.nextInt(); if (n == 1) { System.out.println(1); return; } else if (n == 2) { System.out.println(2); return; } else if (n == 3) { System.out.println(6); return; } if (n % 2 == 0) { if(n % 3 == 0) System.out.println((n - 1) * (n - 2) * (n - 3)); else System.out.println((n - 1) * n * (n - 3)); } else { System.out.println(n * (n - 1) * (n - 2)); } } }
constant
235_A. LCM Challenge
CODEFORCES
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Gaurav */import java.io.*; public class a23 { public static void main(String arg[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine();int max=0; for(int i=0;i<s.length();i++) { for(int j=i+1;j<=s.length();j++) { String g=s.substring(i,j); //System.out.println(g); if(max<g.length()) for(int k=i+1;k<=s.length()-g.length();k++) { //System.out.println(s.substring(k,k+g.length())); if(g.compareTo(s.substring(k,k+g.length()))==0) { max=g.length(); break; } } } } System.out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; public class ProblemE { static final int INF = 1000000; public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.valueOf(s.readLine()); double[][] prob = new double[n][n]; double[] dp = new double[1<<n]; for (int i = 0 ; i < n ; i++) { String[] line = s.readLine().split(" "); for (int j = 0 ; j < n ; j++) { prob[i][j] = Double.valueOf(line[j]); } } dp[(1<<n)-1] = 1.0d; for (int p = (1<<n)-1 ; p >= 1 ; p--) { if (dp[p] > 0.0d) { int left = Integer.bitCount(p); if (left == 1) { continue; } double baseProb = 1.0d / (left * (left - 1) / 2); for (int i = 0 ; i < n ; i++) { if ((p & (1<<i)) == 0) { continue; } for (int j = i+1 ; j < n ; j++) { if ((p & (1<<j)) == 0) { continue; } dp[p-(1<<i)] += dp[p] * baseProb * prob[j][i]; dp[p-(1<<j)] += dp[p] * baseProb * prob[i][j]; } } } } StringBuffer b = new StringBuffer(); for (int i = 0 ; i < n ; i++) { b.append(" ").append(dp[1<<i]); } out.println(b.substring(1)); out.flush(); } public static void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } }
np
16_E. Fish
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int INF = 1000 * 1000 * 1000; public void solve(int testNumber, InputReader in, OutputWriter out) { int x0 = in.readInt(); int y0 = in.readInt(); int n = in.readInt(); int[] xs = new int[n + 1], ys = new int[n + 1]; xs[0] = x0; ys[0] = y0; for (int i = 1; i <= n; i++) { xs[i] = in.readInt(); ys[i] = in.readInt(); } int[] one = new int[n]; for (int i = 0; i < n; i++) one[i] = dist(0, i + 1, xs, ys) * 2; int[][] two = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { two[i][j] = dist(0, i + 1, xs, ys) + dist(0, j + 1, xs, ys) + dist(i + 1, j + 1, xs, ys); } } int[] dp = new int[(1 << n)]; Arrays.fill(dp, INF); dp[0] = 0; int[] prev = new int[(1 << n)]; for (int mask = 0; mask < (1 << n); mask++) { for (int i = 0; i < n; i++) { if (((mask >> i) & 1) != 0) continue; ; int nmask = mask | (1 << i); int cost = one[i] + dp[mask]; if (cost < dp[nmask]) { dp[nmask] = cost; prev[nmask] = i; } for (int j = i + 1; j < n; j++) { if (((mask >> j) & 1) != 0) continue; int nnmask = nmask | (1 << j); cost = two[i][j] + dp[mask]; if (cost < dp[nnmask]) { dp[nnmask] = cost; prev[nnmask] = n + i * n + j; } } break; } } int mask = (1 << n) - 1; out.printLine(dp[mask]); ArrayList<Integer> res = new ArrayList<>(); res.add(0); while (mask > 0) { if (prev[mask] < n) { res.add(prev[mask] + 1); mask &= ~(1 << prev[mask]); } else { int ii = (prev[mask] - n) / n; int jj = (prev[mask] - n) % n; int i = Math.max(ii, jj); int j = Math.min(ii, jj); res.add(i + 1); res.add(j + 1); mask &= ~(1 << i); mask &= ~(1 << j); } res.add(0); } Collections.reverse(res); for (int val : res) out.print(val + " "); out.printLine(); } int dist(int i, int j, int[] xs, int[] ys) { return (xs[i] - xs[j]) * (xs[i] - xs[j]) + (ys[i] - ys[j]) * (ys[i] - ys[j]); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int 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() { writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class IQTest { public static void main(String args[]) throws Exception { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String line; line = stdin.readLine(); int n = Integer.parseInt(line); line = stdin.readLine(); List even = new ArrayList(); List odd = new ArrayList(); String[] kk = line.split(" "); for(int i=0;i<n;i++) { if(Integer.parseInt(kk[i])%2==0) even.add(i); else odd.add(i); } if(even.size()==1) System.out.println((Integer)even.get(0)+1); else System.out.println((Integer)odd.get(0)+1); } }
linear
25_A. IQ test
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class P { public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(), x = sc.nextInt(), y = sc.nextInt(); long C = sc.nextLong(); int lo = 0, hi = (int) (1e6); int answer = -1; while (lo <= hi) { int L = lo + (hi - lo) / 2; long area = 0; for (int steps = 0; steps <= L; ++steps) { // L + 1 steps to right if (y + steps > N) break; long up = Math.min(x, 1 + L - steps), down = Math.min(N - x, L - steps); area += up + down; } for (int steps = 1; steps <= L; ++steps) { // L steps to left if (y - steps < 1) break; long up = Math.min(x, 1 + L - steps), down = Math.min(N - x, L - steps); area += up + down; } if (area >= C) { answer = L; hi = L - 1; } else lo = L + 1; } out.println(answer); out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } String nextLine() throws IOException { return br.readLine(); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; public class Main{ static long MOD = 1_000_000_007L; //static long MOD = 998_244_353L; //static long MOD = 1_000_000_033L; static long inv2 = (MOD + 1) / 2; static int[][] dir = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; static long lMax = 0x3f3f3f3f3f3f3f3fL; static int iMax = 0x3f3f3f3f; static HashMap <Long, Long> memo = new HashMap(); static MyScanner sc = new MyScanner(); //static ArrayList <Integer> primes; static int nn = 300000; static long[] pow2; static long [] fac; static long [] pow; static long [] inv; static long [] facInv; static int[] base; static int[] numOfDiffDiv; static int[] numOfDiv; static ArrayList <Integer> primes; //static int[] primes; static int ptr = 0; static boolean[] isPrime; //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); // Start writing your solution here. ------------------------------------- /*fac = new long[nn + 1]; fac[1] = 1; for(int i = 2; i <= nn; i++) fac[i] = fac[i - 1] * i % MOD;*/ /*pow2 = new long[nn + 1]; pow2[0] = 1L; for(int i = 1; i <= nn; i++) pow2[i] = pow2[i - 1] * 2L;*/ /*inv = new long[nn + 1]; inv[1] = 1; for (int i = 2; i <= nn; ++i) inv[i] = (MOD - MOD / i) * inv[(int)(MOD % i)] % MOD;*/ /*facInv = new long[nn + 1]; facInv[0] = facInv[1] = 1; for (int i = 2; i <= nn; ++i) facInv[i] = facInv[i - 1] * inv[i] % MOD;*/ /*numOfDiffDiv = new int[nn + 1]; for(int i = 2; i <= nn; i++) if(numOfDiffDiv[i] == 0) for(int j = i; j <= nn; j += i) numOfDiv[j] ++;*/ /*numOfDiv = new int[nn + 1]; numOfDiv[1] = 1; for(int i = 2; i <= nn; i++) { for(int j = 2; j * j <= i; j++) { if(i % j == 0) { numOfDiv[i] = numOfDiv[i / j] + 1; break; } } }*/ //primes = sieveOfEratosthenes(100001); /* int t = 1; //t = sc.ni(); while(t-- > 0) { //boolean res = solve(); //out.println(res ? "YES" : "NO"); long res = solve(); out.println(res); }*/ int t = 1, tt = 0; //t = sc.ni(); for(int i = 1; i <40000; i++) squares.add(i * i); while(tt++ < t) { boolean res = solve(); //out.println("Case #" + tt + ": " + res); //out.println(res ? "YES" : "NO"); } out.close(); } static HashSet <Integer> squares = new HashSet(); static boolean solve() { /*String s = sc.nextLine(); char[] c = s.toCharArray(); int n = c.length;*/ //int n = sc.ni(); //long[] a = new long[n]; //for(int i = 0; i < n; i++) a[i] = sc.nl(); long res = 0; int n = sc.ni(); long m = sc.nl(); long[][][] dp = new long[2][n + 3][n + 3]; long[][][] dp2 = new long[2][n + 3][n + 3]; dp[0][2][1] = dp[1][2][2] = dp2[0][1][1] = 1L; for(int i = 3; i <= n; i++) { long[][] bef = dp[0]; long[][] aft = dp[1]; long[][] nbef = new long[n + 3][n + 3]; long[][] naft = new long[n + 3][n + 3]; for(int len = 1; len <= i; len++) { for(int ind = 1; ind <= len; ind++) { nbef[len + 1][1] += bef[len][ind]; nbef[len + 1][ind + 1] -= bef[len][ind]; naft[len + 1][ind + 1] += bef[len][ind]; //naft[len + 1][len + 2] -= bef[len][ind]; naft[len + 1][ind + 1] += aft[len][ind]; //naft[len + 1][len + 2] -= aft[len][ind]; nbef[len + 1][1] += dp2[0][len][ind] + dp2[1][len][ind]; //nbef[len + 1][len + 2] -= dp2[0][len][ind] + dp2[1][len][ind]; } } for(int len = 1; len <= i; len++) { for(int ind = 1; ind <= len; ind ++) { nbef[len][ind] = (nbef[len][ind] + nbef[len][ind - 1] + 10000000L * m) % m; naft[len][ind] = (naft[len][ind] + naft[len][ind - 1] + 10000000L * m) % m; } } dp2 = dp; dp = new long[][][]{nbef, naft}; } for(long[] row: dp[0]) for(long i : row) res += i; for(long[] row: dp[1]) for(long i : row) res += i; out.println(res % m); return false; } // edges to adjacency list by uwi public static int[][] packU(int n, int[] from, int[] to) { return packU(n, from, to, from.length); } public static int[][] packU(int n, int[] from, int[] to, int sup) { int[][] g = new int[n][]; int[] p = new int[n]; for (int i = 0; i < sup; i++) p[from[i]]++; for (int i = 0; i < sup; i++) p[to[i]]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < sup; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } // tree diameter by uwi public static int[] diameter(int[][] g) { int n = g.length; int f0 = -1, f1 = -1, d01 = -1; int[] q = new int[n]; boolean[] ved = new boolean[n]; { int qp = 0; q[qp++] = 0; ved[0] = true; for(int i = 0;i < qp;i++){ int cur = q[i]; for(int e : g[cur]){ if(!ved[e]){ ved[e] = true; q[qp++] = e; continue; } } } f0 = q[n-1]; } { int[] d = new int[n]; int qp = 0; Arrays.fill(ved, false); q[qp++] = f0; ved[f0] = true; for(int i = 0;i < qp;i++){ int cur = q[i]; for(int e : g[cur]){ if(!ved[e]){ ved[e] = true; q[qp++] = e; d[e] = d[cur] + 1; continue; } } } f1 = q[n-1]; d01 = d[f1]; } return new int[]{d01, f0, f1}; } public static long c(int n, int k) { return (fac[n] * facInv[k] % MOD) * facInv[n - k] % MOD; } // SegmentTree range min/max query by uwi public static class SegmentTreeRMQ { public int M, H, N; public int[] st; public SegmentTreeRMQ(int n) { N = n; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; st = new int[M]; Arrays.fill(st, 0, M, Integer.MAX_VALUE); } public SegmentTreeRMQ(int[] a) { N = a.length; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; st = new int[M]; for(int i = 0;i < N;i++){ st[H+i] = a[i]; } Arrays.fill(st, H+N, M, Integer.MAX_VALUE); for(int i = H-1;i >= 1;i--)propagate(i); } public void update(int pos, int x) { st[H+pos] = x; for(int i = (H+pos)>>>1;i >= 1;i >>>= 1)propagate(i); } private void propagate(int i) { st[i] = Math.min(st[2*i], st[2*i+1]); } public int minx(int l, int r){ int min = Integer.MAX_VALUE; if(l >= r)return min; while(l != 0){ int f = l&-l; if(l+f > r)break; int v = st[(H+l)/f]; if(v < min)min = v; l += f; } while(l < r){ int f = r&-r; int v = st[(H+r)/f-1]; if(v < min)min = v; r -= f; } return min; } public int min(int l, int r){ return l >= r ? 0 : min(l, r, 0, H, 1);} private int min(int l, int r, int cl, int cr, int cur) { if(l <= cl && cr <= r){ return st[cur]; }else{ int mid = cl+cr>>>1; int ret = Integer.MAX_VALUE; if(cl < r && l < mid){ ret = Math.min(ret, min(l, r, cl, mid, 2*cur)); } if(mid < r && l < cr){ ret = Math.min(ret, min(l, r, mid, cr, 2*cur+1)); } return ret; } } } public static char[] rev(char[] a){char[] b = new char[a.length];for(int i = 0;i < a.length;i++)b[a.length-1-i] = a[i];return b;} public static double dist(double a, double b){ return Math.sqrt(a * a + b * b); } public static long inv(long a){ return quickPOW(a, MOD - 2); } public class Interval { int start; int end; public Interval(int start, int end) { this.start = start; this.end = end; } } public static ArrayList<Integer> sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { if (prime[p]) { for (int i = p * 2; i <= n; i += p) { prime[i] = false; } } } ArrayList<Integer> primeNumbers = new ArrayList<>(); for (int i = 2; i <= n; i++) { if (prime[i]) { primeNumbers.add(i); } } return primeNumbers; } public static int lowerBound(int[] a, int v){ return lowerBound(a, 0, a.length, v); } public static int lowerBound(int[] a, int l, int r, int v) { if(l > r || l < 0 || r > a.length)throw new IllegalArgumentException(); int low = l-1, high = r; while(high-low > 1){ int h = high+low>>>1; if(a[h] >= v){ high = h; }else{ low = h; } } return high; } public static int rlowerBound(int[] a, int v){ return lowerBound(a, 0, a.length, v); } public static int rlowerBound(int[] a, int l, int r, int v) { if(l > r || l < 0 || r > a.length)throw new IllegalArgumentException(); int low = l-1, high = r; while(high-low > 1){ int h = high+low>>>1; if(a[h] <= v){ high = h; }else{ low = h; } } return high; } public static long C(int n, int m) { if(m == 0 || m == n) return 1l; if(m > n || m < 0) return 0l; long res = fac[n] * quickPOW((fac[m] * fac[n - m]) % MOD, MOD - 2) % MOD; return res; } public static long quickPOW(long n, long m) { long ans = 1l; while(m > 0) { if(m % 2 == 1) ans = (ans * n) % MOD; n = (n * n) % MOD; m >>= 1; } return ans; } public static long quickPOW(long n, long m, long mod) { long ans = 1l; while(m > 0) { if(m % 2 == 1) ans = (ans * n) % mod; n = (n * n) % mod; m >>= 1; } return ans; } public static int gcd(int a, int b) { if(a % b == 0) return b; return gcd(b, a % b); } public static long gcd(long a, long b) { if(a % b == 0) return b; return gcd(b, a % b); } static class Randomized { public static void shuffle(int[] data) { shuffle(data, 0, data.length - 1); } public static void shuffle(int[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); int tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static void shuffle(long[] data) { shuffle(data, 0, data.length - 1); } public static void shuffle(long[] data, int from, int to) { to--; for (int i = from; i <= to; i++) { int s = nextInt(i, to); long tmp = data[i]; data[i] = data[s]; data[s] = tmp; } } public static int nextInt(int l, int r) { return RandomWrapper.INSTANCE.nextInt(l, r); } } static class RandomWrapper { private Random random; public static final RandomWrapper INSTANCE = new RandomWrapper(new Random()); public RandomWrapper() { this(new Random()); } public RandomWrapper(Random random) { this.random = random; } public int nextInt(int l, int r) { return random.nextInt(r - l + 1) + l; } } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
cubic
1515_E. Phoenix and Computers
CODEFORCES
//stan hu tao //join nct ridin by first year culture reps import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class x1497E { static final int MAX = 10000000; public static void main(String hi[]) throws Exception { int[] prime = new int[MAX+1]; for(int d=2; d <= MAX; d++) if(prime[d] == 0) for(int v=d; v <= MAX; v+=d) if(prime[v] == 0) prime[v] = d; FastScanner infile = new FastScanner(); int T = infile.nextInt(); StringBuilder sb = new StringBuilder(); int[] freq = new int[MAX+1]; int[] ts = new int[MAX+1]; int time = 0; while(T-->0) { int N = infile.nextInt(); int K = infile.nextInt(); int[] arr = infile.nextInts(N); for(int i=0; i < N; i++) { int key = 1; while(arr[i] > 1) { int p = prime[arr[i]]; int cnt = 0; while(arr[i]%p == 0) { arr[i] /= p; cnt ^= 1; } if(cnt == 1) key *= p; } arr[i] = key; } int[][] right = new int[N][K+1]; for(int k=0; k <= K; k++) { int dex = 0; int cnt = 0; for(int i=0; i < N; i++) { while(dex < N && cnt <= k) { if(ts[arr[dex]] == time && freq[arr[dex]] >= 1 && cnt+1 > k) break; if(ts[arr[dex]] == time && freq[arr[dex]] >= 1) cnt++; if(ts[arr[dex]] < time) { ts[arr[dex]] = time; freq[arr[dex]] = 0; } freq[arr[dex]]++; dex++; } right[i][k] = dex; if(freq[arr[i]] >= 2) cnt--; freq[arr[i]]--; } time++; } int[][] dp = new int[N+1][K+1]; for(int i=1; i <= N; i++) Arrays.fill(dp[i], N); for(int i=0; i < N; i++) for(int a=0; a <= K; a++) { dp[i+1][a] = min(dp[i+1][a], dp[i][a]+1); for(int b=0; b <= K-a; b++) dp[right[i][b]][a+b] = min(dp[right[i][b]][a+b], dp[i][a]+1); } int res = dp[N][0]; for(int k=1; k <= K; k++) res = min(res, dp[N][k]); sb.append(res+"\n"); } System.out.print(sb); } } class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } }
cubic
1497E2
CODEFORCES
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.util.Arrays; import java.io.PrintWriter; 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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int[] fs = IOUtils.readIntArray(in, n); Arrays.sort(fs); int ptr = fs.length - 1; int res = 0; while (ptr >= 0 && k < m) { k += fs[ptr--] - 1; res++; } if (k < m) out.println(-1); else out.println(res); } } class IOUtils { public static int[] readIntArray(Scanner in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.nextInt(); return array; } }
nlogn
257_A. Sockets
CODEFORCES
//package round455; 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 C { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int mod = 1000000007; long[] dp = new long[5005]; dp[0] = 1; for(int i = 0;i < n;i++){ char c = nc(); if(c == 's'){ if(i < n-1){ for(int j = 5003;j >= 0;j--){ dp[j] += dp[j+1]; if(dp[j] >= mod)dp[j] -= mod; } } }else{ for(int j = 5003;j >= 0;j--){ dp[j+1] = dp[j]; } dp[0] = 0; } } long ans = 0; for(int i = 0;i < 5005;i++)ans += dp[i]; out.println(ans % 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 C().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.util.*; import java.io.*; public class E { void solve(BufferedReader in) throws Exception { int[] xx = toInts(in.readLine()); int n = xx[0]; double k = xx[1]; int[][] board = new int[n][n]; for(int i = 0; i<n; i++) board[i] = toInts(in.readLine()); int fst = n/2; int snd = n - fst; int[] maxc = new int[1<<fst]; int max = 1; for(int i = 0; i<(1<<fst); i++) { for(int j = 0; j<fst; j++) { if((i&1<<j) != 0) maxc[i] = Math.max(maxc[i], maxc[i^(1<<j)]); } boolean ok = true; for(int a = 0; a<fst; a++) if((i&1<<a) != 0) { for(int b = a+1; b<fst; b++) if((i&1<<b) != 0) { if(board[a][b] == 0) ok = false; } } if(ok) { maxc[i] = Integer.bitCount(i); max = Math.max(max, maxc[i]); } } for(int i = 0; i<(1<<snd); i++) { boolean ok = true; for(int a = 0; a<snd; a++) if((i&1<<a) != 0) { for(int b = a+1; b<snd; b++) if((i&1<<b) != 0) { if(board[a+fst][b+fst] == 0) ok = false; } } if(!ok) continue; int mask = 0; for(int a = 0; a<fst; a++) { ok = true; for(int b = 0; b<snd; b++) { if((i&1<<b) != 0) { if(board[a][b+fst] == 0) ok = false; } } if(ok) mask |= (1<<a); } max = Math.max(Integer.bitCount(i) + maxc[mask], max); } System.out.println(k*k*(max-1.0)/(2*max)); } int toInt(String s) {return Integer.parseInt(s);} int[] toInts(String s) { String[] a = s.split(" "); int[] o = new int[a.length]; for(int i = 0; i<a.length; i++) o[i] = toInt(a[i]); return o; } void e(Object o) { System.err.println(o); } public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); (new E()).solve(in); } }
np
839_E. Mother of Dragons
CODEFORCES
// @author Sanzhar import java.io.*; import java.util.*; import java.awt.Point; public class Template { BufferedReader in; PrintWriter out; StringTokenizer st; String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (Exception e) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } public void run() throws Exception { //in = new BufferedReader(new FileReader("input.txt")); //out = new PrintWriter(new FileWriter("output.txt")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.flush(); out.close(); in.close(); } public void solve() throws Exception { long l = nextLong(); long r = nextLong(); long[] x = new long[100]; int kx = 0; while (r > 0) { x[kx++] = r % 2; r /= 2; } long[] y = new long[100]; int ky = 0; while (l > 0) { y[ky++] = l % 2; l /= 2; } long[] ans = new long[100]; boolean ok = false; for (int k = kx - 1; k >= 0; k--) { if (ok) { ans[k] = 1; continue; } if (x[k] > y[k]) { ans[k] = 1; ok = true; } } long a = 0; long p2 = 1; for (int i = 0; i < kx; i++) { a += p2 * ans[i]; p2 *= 2; } out.println(a); } public static void main(String[] args) throws Exception { new Template().run(); } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.io.*; import java.util.*; public class Codechef{ public static void main(String []args){ Scanner in = new Scanner(System.in); long n=in.nextLong(); long m=in.nextLong(); long k=in.nextLong(); long l=in.nextLong(); long j=((k+l)/m); if((k+l)%m!=0)j++; if((k+l>n) || j*m>n) { System.out.println(-1); }else { System.out.println(j); } } }
constant
1068_A. Birthday
CODEFORCES
import java.util.*; public class A { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { String s = sc.next(); for (int l = s.length(); l > 0; --l) { HashSet<String> set = new HashSet<String>(); for (int i = 0; i < s.length() - l + 1; ++i) if (set.contains(s.substring(i, i + l))) { System.out.println(l); return; } else { set.add(s.substring(i, i + l)); } } System.out.println(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; public class Main implements Runnable { private void solution() throws IOException { int n = in.nextInt(); int m = in.nextInt(); boolean[][] adj = new boolean[n][n]; long res = 0; for (int i = 0; i < m; ++i) { int x = in.nextInt(); int y = in.nextInt(); adj[x - 1][y - 1] = true; adj[y - 1][x - 1] = true; } for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (adj[i][j]) { --res; } } } final long[][] dp = new long[1 << n][n]; for (int i = 0; i < n; ++i) { for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { dp[mask][j] = 0; } } dp[0][0] = 1; for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { if (dp[mask][j] != 0) { for (int k = 0; k < n - i; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) { dp[mask | (1 << k)][k] += dp[mask][j]; } } } } if (((mask >> 0) & 1) != 0) { res += dp[mask][0]; } } } out.println(res / 2); } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private class Scanner { BufferedReader reader; StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""); } public boolean hasNext() throws IOException { while (!tokenizer.hasMoreTokens()) { String next = reader.readLine(); if (next == null) { return false; } tokenizer = new StringTokenizer(next); } return true; } public String next() throws IOException { hasNext(); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) throws IOException { new Thread(null, new Main(), "", 1 << 28).start(); } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Scanner in = new Scanner(new InputStreamReader(System.in)); }
np
11_D. A Simple Task
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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { long N = in.nextLong(); long K = in.nextLong(); if(N == 1) { out.println(0); return; } if(N <= K) { out.println(1); return; } long st = 1; long dr = K - 1; long m; long ans = -1; while(st <= dr) { m = (st + dr) / 2; if(get(m, K) <= N) { ans = m; st = m + 1; } else dr = m - 1; } N -= get(ans, K); if(ans == -1 || (ans == K - 1 && N > 0) ) { out.println(-1); return; } if(N > 0) ans++; out.println(ans); } private long get(long p, long K) { long sum = (K - p + 1 + K) * p / 2; long extra = p - 1; return sum - extra; } } 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 long nextLong() { return Long.parseLong(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; } }
logn
287_B. Pipeline
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class A { static StringTokenizer st; static BufferedReader in; public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int m = nextInt(); int k = nextInt(); int[]a = new int[n+1]; for (int i = 1; i <= n; i++) { a[i] = nextInt(); } if (k >= m) { System.out.println(0); return; } Arrays.sort(a, 1, n+1); int ans = 0; for (int i = n; i >= 1; i--) { ans++; k--; k += a[i]; if (k >= m) { System.out.println(ans); return; } } System.out.println(-1); pw.close(); } private static int nextInt() throws IOException{ return Integer.parseInt(next()); } private static long nextLong() throws IOException{ return Long.parseLong(next()); } private static double nextDouble() throws IOException{ return Double.parseDouble(next()); } private static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } }
nlogn
257_A. Sockets
CODEFORCES
import java.io.*; import java.util.*; public class LCMChallenge { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); long n = Long.parseLong(f.readLine()); if (n == 1 || n == 2) System.out.println(n); else if (n % 2 == 1) System.out.println(n*(n-1)*(n-2)); else { long prod = n*(n-1); long x = n-2; while (x > 0 && gcd(n,x) > 1 || gcd(n-1,x) > 1) x--; prod *= x; if ((n-1)*(n-2)*(n-3) > prod) prod = (n-1)*(n-2)*(n-3); System.out.println(prod); } } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a%b); } }
constant
235_A. LCM Challenge
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; import java.lang.*; public class Main { static Input in; static Output out; public static void main(String[] args) throws IOException { in = new Input(System.in); out = new Output(System.out); run(); out.close(); System.exit(0); } private static void run() throws IOException { int n = in.nextInt(), k = in.nextInt(); int[] A = new int[n]; for (int i = 0; i < n; i++) { A[i] = in.nextInt(); } Arrays.sort(A); int count = n; boolean[] hash = new boolean[n]; for (int i = n-1; i > 0; i--) { if(!hash[i]) { int a = A[i]; if(a % k == 0) { int p = a / k; int j = Arrays.binarySearch(A, p); if(j >= 0 && j < i) { hash[j] = true; count--; } } } } out.print(count); } } class Input { final int SIZE = 8192; private InputStream in; private byte[] buf = new byte[SIZE]; private int last, current, total; public Input(InputStream stream) throws IOException { in = stream; last = read(); } private int read() throws IOException { if (total == -1) return -1; if (current >= total) { current = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[current++]; } private void advance() throws IOException { while (true) { if (last == -1) return; if (!isValidChar(last)) last = read(); else break; } } private boolean isValidChar(int c) { return c > 32 && c < 127; } public boolean isEOF() throws IOException { advance(); return last == -1; } public String nextString() throws IOException { advance(); if (last == -1) throw new EOFException(); StringBuilder s = new StringBuilder(); while (true) { s.appendCodePoint(last); last = read(); if (!isValidChar(last)) break; } return s.toString(); } public String nextLine() throws IOException { if (last == -1) throw new EOFException(); StringBuilder s = new StringBuilder(); while (true) { s.appendCodePoint(last); last = read(); if (last == '\n' || last == -1) break; } return s.toString(); } public String nextLine(boolean ignoreIfEmpty) throws IOException { if (!ignoreIfEmpty) return nextLine(); String s = nextLine(); while (s.trim().length() == 0) s = nextLine(); return s; } public int nextInt() throws IOException { advance(); if (last == -1) throw new EOFException(); int n = 0, s = 1; if (last == '-') { s = -1; last = read(); if (last == -1) throw new EOFException(); } while (true) { n = n * 10 + last - '0'; last = read(); if (!isValidChar(last)) break; } return n * s; } public long nextLong() throws IOException { advance(); if (last == -1) throw new EOFException(); int s = 1; if (last == '-') { s = -1; last = read(); if (last == -1) throw new EOFException(); } long n = 0; while (true) { n = n * 10 + last - '0'; last = read(); if (!isValidChar(last)) break; } return n * s; } public BigInteger nextBigInt() throws IOException { return new BigInteger(nextString()); } public char nextChar() throws IOException { advance(); return (char) last; } public double nextDouble() throws IOException { advance(); if (last == -1) throw new EOFException(); int s = 1; if (last == '-') { s = -1; last = read(); if (last == -1) throw new EOFException(); } double n = 0; while (true) { n = n * 10 + last - '0'; last = read(); if (!isValidChar(last) || last == '.') break; } if (last == '.') { last = read(); if (last == -1) throw new EOFException(); double m = 1; while (true) { m = m / 10; n = n + (last - '0') * m; last = read(); if (!isValidChar(last)) break; } } return n * s; } public BigDecimal nextBigDecimal() throws IOException { return new BigDecimal(nextString()); } public void close() throws IOException { in.close(); in = null; } } class Output { final int SIZE = 8192; private Writer out; private char cb[] = new char[SIZE]; private int nChars = SIZE, nextChar = 0; private char lineSeparator = '\n'; public Output(OutputStream stream) { out = new OutputStreamWriter(stream); } void flushBuffer() throws IOException { if (nextChar == 0) return; out.write(cb, 0, nextChar); nextChar = 0; } void write(int c) throws IOException { if (nextChar >= nChars) flushBuffer(); cb[nextChar++] = (char) c; } void write(String s, int off, int len) throws IOException { int b = off, t = off + len; while (b < t) { int a = nChars - nextChar, a1 = t - b; int d = a < a1 ? a : a1; s.getChars(b, b + d, cb, nextChar); b += d; nextChar += d; if (nextChar >= nChars) flushBuffer(); } } void write(String s) throws IOException { write(s, 0, s.length()); } public void print(Object obj) throws IOException { write(String.valueOf(obj)); } public void println(Object obj) throws IOException { write(String.valueOf(obj)); write(lineSeparator); } public void printf(String format, Object... obj) throws IOException { write(String.format(format, obj)); } public void close() throws IOException { flushBuffer(); out.close(); out = null; } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
//package round15; import java.io.BufferedOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; import java.util.Arrays; import java.util.Scanner; public class A { private Scanner in; private PrintWriter out; public void solve() { int n = ni(); int t = ni(); Pair[] p = new Pair[n]; for(int i = 0;i < n;i++){ p[i] = new Pair(); p[i].x = ni(); p[i].a = ni(); } Arrays.sort(p); int ct = 2; for(int i = 0;i < n - 1;i++){ float d = p[i + 1].x - (float)p[i + 1].a / 2 - p[i].x - (float)p[i].a / 2; if(Math.abs(d - t) < EPS){ ct++; }else if(d > t){ ct += 2; } } out.println(ct); } double EPS = 0.0001; private static class Pair implements Comparable<Pair> { public int x; public int a; @Override public int compareTo(Pair o) { return x - o.x; } } public void run() throws Exception { // in = new Scanner(new StringReader("2 3 0 4 5 2")); in = new Scanner(System.in); System.setOut(new PrintStream(new BufferedOutputStream(System.out))); out = new PrintWriter(System.out); // int n = in.nextInt(); int n = 1; for(int i = 1;i <= n;i++){ long t = System.currentTimeMillis(); solve(); out.flush(); // System.err.printf("%04d/%04d %7d%n", i, n, System.currentTimeMillis() - t); } } public static void main(String[] args) throws Exception { new A().run(); } private int ni() { return Integer.parseInt(in.next()); } private static void tr(Object... o) { System.out.println(o.length == 1 ? o[0] : Arrays.toString(o)); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C8 { static int[] mem; static int[] bag; static int[][] items; static int[] close; static PrintWriter pw; static int n; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); pw = new PrintWriter(System.out); bag = new int[2]; bag[0] = sc.nextInt(); bag[1] = sc.nextInt(); n = sc.nextInt(); items = new int[n][2]; for(int i = 0;i<n;i++) { items[i][0] = sc.nextInt(); items[i][1] = sc.nextInt(); } //System.out.println((items[0][1]-bag[1])*(items[0][1]-bag[1])); mem = new int[1<<n]; Arrays.fill(mem, -1); pw.println(dp(0)); trace(0); pw.print(0); pw.flush(); } static int dp(int mask){ if(mask==(1<<n)-1) return 0; if(mem[mask]!=-1) return mem[mask]; int ans = (int)1e9; for(int i = 0;i<n;i++) if((1<<i&mask)==0) { ans = getDisBag(i)*2+dp(mask|1<<i); for(int j = i+1;j<n;j++) if((1<<j&mask)==0) ans = Math.min(ans, getDisBag(i)+getDis(i,j)+getDisBag(j)+dp(mask|1<<i|1<<j)); break; } return mem[mask] = ans; } static int getDis(int i, int j){ return (items[i][0]-items[j][0])*(items[i][0]-items[j][0])+(items[i][1]-items[j][1])*(items[i][1]-items[j][1]); } static int getDisBag(int i){ return (items[i][0]-bag[0])*(items[i][0]-bag[0])+(items[i][1]-bag[1])*(items[i][1]-bag[1]); } static int getClosest(int i, int mask){ int ret = -1; for(int j = 0;j<n;j++) if(i!=j&&(mask&1<<j)==0) if(ret==-1||getDis(i, j)<getDis(i, ret)) ret = j; return ret; } static void trace(int mask){ if(mask==(1<<n)-1) return; int ans = (int)1e9; for(int i = 0;i<n;i++) if((1<<i&mask)==0) { ans = getDisBag(i)*2+dp(mask|1<<i); if(mem[mask]==ans) { pw.print(0+" "+(i+1)+" "); trace(mask|1<<i); return; } for(int j = i+1;j<n;j++) if((1<<j&mask)==0) if(mem[mask] == getDisBag(i)+getDis(i,j)+getDisBag(j)+dp(mask|1<<i|1<<j)) { pw.print(0+" "+(i+1)+" "+(j+1)+" "); trace(mask|1<<i|1<<j); return; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int 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();} } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class A_122 { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(bf.readLine()); System.out.println((n%4==0||n%7==0||n%47==0||n%74==0||n%447==0||n%474==0||n%477==0||n%744==0||n%747==0||n%774==0)?"YES":"NO"); } }
constant
122_A. Lucky Division
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author ShekharN */ 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 { private final int MOD = (int) (1e9 + 7); public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); String[] arr = new String[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextString(); } int[] dp = new int[n]; Arrays.parallelSetAll(dp, i -> 0); dp[0] = 1; int cnt = 0; for (int i = 0; i < n; i++) { if (arr[i].equals("f")) { cnt++; continue; } calc(dp, n, cnt); cnt = 0; } int sum = 0; for (int i = 0; i < n; i++) { sum += dp[i]; sum %= MOD; } out.println(sum); } private void calc(int[] dp, int n, int cnt) { for (int i = n - 1; i >= 0; i--) { if (i != n - 1) dp[i] += dp[i + 1]; dp[i] %= MOD; } //int[] tmp = new int[n]; int prev = dp[0]; for (int i = 0, y = 0; i < MathUtil.gcdInt(n, cnt); i++) { //tmp[(i+cnt)%n] = dp[i]; y = i; prev = dp[i]; do { int nextId = (y + cnt) % n; int tmp = dp[nextId]; dp[nextId] = prev; prev = tmp; y = nextId; } while (y != i); } //Arrays.parallelSetAll(dp,i->tmp[i]); } } 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 f) { br = new BufferedReader(new InputStreamReader(f)); } public String nextString() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextString()); } } static class MathUtil { public static int gcdInt(int a, int b) { if (b == 0) return a; return gcdInt(b, a % b); } } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.util.*; import java.io.*; public class PythonIndentation { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(in.readLine()); int[][] dp = new int[N][N]; dp[0][0] = 1; for(int i = 1; i < N; ++i) { char lastCmd = in.readLine().charAt(0); int[] sum = new int[N]; sum[N - 1] = dp[i - 1][N - 1]; for(int j = N - 2; j >= 0; --j) sum[j] = (sum[j + 1] + dp[i - 1][j]) % 1000000007; for(int j = 0; j < N; ++j) { if(lastCmd == 'f' && j > 0) dp[i][j] = dp[i - 1][j - 1]; else if(lastCmd == 's') dp[i][j] = sum[j]; } } int ans = 0; for(int i = 0; i < N; ++i) ans = (ans + dp[N - 1][i]) % 1000000007; System.out.println(ans); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class q5 { static NoD[] arr; static int index,count,zc; static ArrayList<NoD> pos,neg; static long[][][][] dp; static long solve(int a,int b, int c,int d, long mod) { long[][][][] a2=dp; int p=-1; if(a==0 && b==0 && c==0) return 1; if(dp[a][b][c][d]!=-1) return dp[a][b][c][d]; long tr=0; if(a>0 && d!=1) { tr=+a*solve(a-1,b,c,1,mod); tr%=mod; } if(b >0 && d!=2) { tr+=b*solve(a,b-1,c,2,mod); tr%=mod; } if(c>0 && d!=3) { tr+=c*solve(a,b,c-1,3,mod); tr%=mod; } tr%=mod; return dp[a][b][c][d]=tr; } public static void main(String[] args) throws IOException { Reader.init(System.in); PrintWriter out=new PrintWriter(System.out); int n=Reader.nextInt(),t=Reader.nextInt(); long mod=(long)1e9+7,fact[]=new long[16]; dp=new long[16][16][16][4]; for(int i=0;i<16;i++) { for(int j=0;j<16;j++) { for(int k=0;k<16;k++) Arrays.fill(dp[i][j][k], -1); } } fact[0]=1; for(int i=1;i<=15;i++) { fact[i]=i*fact[i-1]; fact[i]%=mod; } NoD[] arr=new NoD[n]; for(int i=0;i<n;i++) { int a=Reader.nextInt(),b=Reader.nextInt(); arr[i]=new NoD(a,b); } long ans=0; for(int i=0;i<(1<<n);i++) { int time=0; int prev=-1; int t1=0,t2=0,t3=0; long[] c= {i}; BitSet b=BitSet.valueOf(c); for(int j=0;j<n;j++) { if(b.get(j)) { time+=arr[j].val; prev=arr[j].index; if(arr[j].index==1) t1++; else if(arr[j].index==2) t2++; else t3++; } } if(time==t) { long v=1; long v2=1; v*=solve(t1,t2,t3,0,mod); v%=mod; ans+=v; ans%=mod; } } out.println(ans); out.flush(); } } class NoD{ int val, index; NoD(int v,int i){ val=v;index=i; } } class Pair{ NoD a, b; Pair(NoD aa,NoD bb){ a=aa;b=bb; } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String nextLine() throws IOException{ return reader.readLine(); } static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.*; import static java.lang.Math.*; public class Main { static int hx, hy; static int[] X, Y; static int N; static int[] DP; static int pw(int a) { return a * a; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); hx = sc.nextInt(); hy = sc.nextInt(); N = sc.nextInt(); X = new int[N]; Y = new int[N]; for (int i = 0; i < N; ++i) { X[i] = sc.nextInt(); Y[i] = sc.nextInt(); } DP = new int[1 << N]; Arrays.fill(DP, -1); int ans = recur(0); ArrayList<Integer> aa = new ArrayList<Integer>(); int U = 0; aa.add(0); int test = 0; while (U != (1 << N) - 1) { int a = 0; for (int i = 0; i < N; ++i) { if (((1 << i) & U) == 0) { a = i; break; } } int ans2 = recur(U | (1 << a)) + 2 * (pw(X[a] - hx) + pw(Y[a] - hy)); int temp = 2 * (pw(X[a] - hx) + pw(Y[a] - hy)); int best = -1; for (int i = a + 1; i < N; ++i) { if (((1 << i) & U) == 0) { int ans3 = recur(U|(1<<a)|(1<<i)) + pw(X[a]-X[i])+pw(Y[a]-Y[i]) + pw(X[a]-hx)+pw(Y[a]-hy) + pw(X[i]-hx)+pw(Y[i]-hy); if (ans3 < ans2) { ans2 = ans3; ans2 = ans3; best = i; temp = pw(X[a]-X[i])+pw(Y[a]-Y[i]) + pw(X[a]-hx)+pw(Y[a]-hy) + pw(X[i]-hx)+pw(Y[i]-hy); } } } if (best == -1) { aa.add(a + 1); aa.add(0); U |= (1 << a); } else { aa.add(a + 1); aa.add(best + 1); aa.add(0); U |= (1 << a) | (1 << best); } } System.out.println(ans); for (int i = 0; i < aa.size(); ++i) { System.out.print(aa.get(i) + " "); } } private static int recur(int U) { if (DP[U] != -1) { return DP[U]; } if (U == (1 << N) - 1) { return 0; } int a = 0; for (int i = 0; i < N; ++i) { if (((1 << i) & U) == 0) { a = i; break; } } int ans = recur(U | (1 << a)) + 2 * (pw(X[a] - hx) + pw(Y[a] - hy)); for (int i = a + 1; i < N; ++i) { if (((1 << i) & U) == 0) { ans = min(ans, recur(U|(1<<a)|(1<<i)) + pw(X[a]-X[i])+pw(Y[a]-Y[i]) + pw(X[a]-hx)+pw(Y[a]-hy) + pw(X[i]-hx)+pw(Y[i]-hy)); } } DP[U] = ans; return ans; } }
np
8_C. Looking for Order
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); ASonyaAndHotels solver = new ASonyaAndHotels(); solver.solve(1, in, out); out.close(); } static class ASonyaAndHotels { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int d = in.scanInt(); int[] ar = new int[n]; int ans = 2; for (int i = 0; i < n; i++) ar[i] = in.scanInt(); for (int i = 0; i < n - 1; i++) { if (ar[i + 1] - ar[i] == 2 * d) ans++; else if (ar[i + 1] - ar[i] > 2 * d) ans += 2; } out.println(ans); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.io.*; public class ExplorerSpace { private static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static long[][][] dp; public static boolean valid(int i, int j, int n, int m) { return i>=0 && i<n &&j>=0 && j<m; } public static void solution(int n, int m, int k, int[][] h, int[][] v) { if(k%2==1) { for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) out.print(-1+" "); out.println(); } return; } dp = new long[n][m][k/2+1]; for(int t = 1; t<=k/2; t++) { for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) { dp[i][j][t] = Long.MAX_VALUE; } } } for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) { dp[i][j][0] = 0; } } for(int t = 1; t<=k/2; t++) { for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) { if(valid(i,j+1,n,m)) dp[i][j][t] = Math.min(dp[i][j][t], h[i][j] + dp[i][j+1][t-1]); if(valid(i,j-1,n,m)) dp[i][j][t] = Math.min(dp[i][j][t], h[i][j-1] + dp[i][j-1][t-1]); if(valid(i+1,j,n,m)) dp[i][j][t] = Math.min(dp[i][j][t], v[i][j] + dp[i+1][j][t-1]); if(valid(i-1,j,n,m)) dp[i][j][t] = Math.min(dp[i][j][t], v[i-1][j] + dp[i-1][j][t-1]); } } } for(int i = 0; i<n; i++) { for(int j = 0; j<m; j++) out.print((dp[i][j][k/2]*2)+" "); out.println(); } } private static PrintWriter out = new PrintWriter(System.out); public static void main (String[] args) { MyScanner s = new MyScanner(); int n = s.nextInt(); int m = s.nextInt(); int k = s.nextInt(); int[][] h = new int[n][m-1]; for(int i = 0; i<n; i++) { for(int j = 0; j<m-1; j++) { h[i][j] = s.nextInt(); } } int[][] v = new int[n-1][m]; for(int i = 0; i<n-1; i++) { for(int j = 0; j<m; j++) { v[i][j] = s.nextInt(); } } solution(n,m,k,h,v); out.flush(); out.close(); } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class CF22_1 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int num=sc.nextInt(); if(num!=1) { ArrayList<Integer>data=new ArrayList<Integer>(); for (int i=0;i<num;i++){ data.add(sc.nextInt()); } Collections.sort(data); int ind=1; while( data.get(ind-1)==data.get(ind) ) { ind++; if(ind ==data.size()) break; } if(data.size()>ind) System.out.println(data.get(ind)); else System.out.println("NO"); } else System.out.println("NO"); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class E implements Runnable { public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();} int n, m; char[] str; int[][] occs, cost; int[] dp; public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println(""); //where's my 420???? :( long tot = 0; for(int i = 0; i < 19999; i++) tot += i; System.err.println(tot); n = fs.nextInt(); m = fs.nextInt(); byte[] str = fs.next().getBytes(); int[] occs = new int[1<<m]; for(int i = 0; i < n-1; i++) { int l1 = str[i] - 'a'; int l2 = str[i+1] - 'a'; occs[(1<<l1) | (1<<l2)]++; occs[(1<<l2) | (1<<l1)]++; } //cost[mask][v] = numPairs with v for some all bits on in mask int all = (1<<m)-1; cost = new int[m][1<<m]; for(int i = 0; i < m; i++) { for(int mask = 1; mask < all; mask++) { if(((1<<i)&mask) > 0) continue; int lb = mask & (-mask); int trail = Integer.numberOfTrailingZeros(lb); int nmask = mask ^ lb; cost[i][mask] = cost[i][nmask]+occs[1<<i | 1<<trail]; } } dp = new int[1<<m]; for(int mask = dp.length-2; mask >= 0; mask--) { int addOn = 0; for(int nxt = 0; nxt < m; nxt++) { if(((1<<nxt)&mask) > 0) continue; addOn += cost[nxt][mask]; } int res = oo; for(int nxt = 0; nxt < m; nxt++) { if(((1<<nxt)&mask) > 0) continue; int ret = addOn+dp[mask | (1<<nxt)]; res = min(res, ret); } dp[mask] = res; } System.out.println(dp[0]>>1); out.close(); } int oo = (int)1e9; int min(int a, int b) { if(a < b) return a; return b; } class FastScanner { 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 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); } } 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; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
np
1238_E. Keyboard Purchase
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.HashMap; public class B { /** * @param args * @throws IOException */ static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; static HashMap<Character, Integer> val = new HashMap<Character, Integer>(); static HashMap<Integer, Character> ch = new HashMap<Integer, Character>(); static StringBuffer strcol = new StringBuffer(); static String s; static boolean isDigit(char a) { boolean found = false; for (int i = 0; i < digits.length; i++) { if (found = a == digits[i]) break; } return found; } static String ABtoRC(int pos) { do { ++pos; } while(!isDigit(s.charAt(pos))); int res = 0; for (int i = pos - 1, pow = 1; i >= 0; i--, pow *= 26) { res += val.get(s.charAt(i)) * pow; } return new String("R" + s.substring(pos, s.length()) + "C" + String.valueOf(res)); } static String RCtoAB(int cpos) { int col = Integer.valueOf(s.substring(cpos + 1, s.length())); int mod = 0; strcol.delete(0, strcol.length()); while (col >= 26) { int tmp = col / 26; mod = col - 26 * tmp; if (mod == 0) { mod += 26; tmp -= 1; } col = tmp; strcol.append(ch.get(mod)); } if(col != 0)strcol.append(ch.get(col)); strcol.reverse(); return strcol.toString() + s.substring(1, cpos); } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // BufferedReader input = new BufferedReader(new FileReader("input.txt")); // PrintWriter output = new PrintWriter(new FileWriter("output.txt")); BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter output = new PrintWriter(new OutputStreamWriter(System.out)); StreamTokenizer in = new StreamTokenizer(input); in.nextToken(); int n = (int)in.nval; for (int i = 0; i < 26; i++) { val.put((char)('A' + i), i + 1); } for (int i = 0; i < 26; i++) { ch.put(i + 1, (char)('A' + i)); } input.readLine(); for (int i = 0; i < n; i++) { s = input.readLine(); int cpos; if( ((cpos = s.indexOf('C')) > 1) && (isDigit(s.charAt(cpos - 1))) ) { output.println(RCtoAB(cpos)); } else { output.println(ABtoRC(cpos)); } } output.close(); input.close(); } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class A { static class Sort implements Comparable<Sort> { int x,a; public int compareTo(Sort o) { if (this.x==o.x) return this.a-o.a; return this.x-o.x; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int t = sc.nextInt(); Sort[]a = new Sort[n]; for (int i = 0; i < n; i++) { a[i] = new Sort(); a[i].x = sc.nextInt(); a[i].a = sc.nextInt(); } Arrays.sort(a); int ans = 2; for (int i = 1; i < n; i++) { double d = a[i].x-a[i].a / 2.0-a[i-1].x-a[i-1].a / 2.0; if (d==t) ans++; else if (d > t) ans += 2; } System.out.println(ans); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); long dest = sc.nextLong(); long max = (long)N * ((long)N + 1L) / 2L; if (dest < 2 * N - 1 || dest > max) { out.println("No"); out.close(); return; } int[] d = new int[N + 1]; int[] f = new int[N + 1]; int K = 1; for (; K <= N; K++) { long dep = 1L, cnt = 1L, c = 1L; long t = 1L; while (cnt < N) { c = c * K; dep++; t += (dep * Math.min(c, N - cnt)); cnt += c; } if (t <= dest) break; } out.println("Yes"); int dep = 1; long cnt = 1L, c = 1L; long t = 1L; d[1] = 1; while (cnt < N) { dep++; c = c * K; long x = (long)N - cnt; int min; if (c >= x) min = (int)x; else min = (int)c; d[dep] = min; t += (dep * Math.min(c, (long)N - cnt)); cnt += c; } dest -= t; int curDep = dep; int nextDep = dep + 1; while (dest > 0) { if (d[curDep] <= 1) curDep--; d[curDep]--; long next = Math.min(nextDep++, dest + curDep); dest -= ((int)next - curDep); d[(int)next]++; } int first = 1; for (int i = 2; i < nextDep; i++) { int p = 0, fn = first - d[i - 1] + 1; for (int j = first + 1; j <= first + d[i]; j++) { if (p == K) { fn++; p = 0; } p++; f[j] = fn; } first += d[i]; } for (int i = 2; i <= N; i++) out.format("%d ", f[i]); out.close(); } static class FastScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public FastScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } public String next() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n"); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } /* public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; }*/ } }
nlogn
1098_C. Construct a tree
CODEFORCES
import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author coderbd */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int m, n, k; n = in.readInt(); m = in.readInt(); k = in.readInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.readInt() - 1; Arrays.sort(a); int ans = -1; if (k >= m) ans = 0; else for (int i = 0; i < n; i++) { k += a[n-i-1]; if (k >= m) { ans = i + 1; break; } } System.out.println(ans); } } class InputReader { private boolean finished = false; 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 peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public int 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 long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0L; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } 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 boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } public String next() { return readString(); } } 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 printLine(char[] array) { writer.print(array); } public void printFormat(String format, Object...objects) { writer.printf(format, objects); } public void close() { writer.close(); } public void flush() { writer.flush(); } }
nlogn
257_A. Sockets
CODEFORCES
import java.util.*; import java.io.*; public class _1000_A { public static void main(String[] args) throws IOException { HashMap<String, Integer> map1 = new HashMap<>(), map2 = new HashMap<>(); int N = readInt(); for(int i = 1; i<=N; i++) { String s = read(); if(!map1.containsKey(s)) map1.put(s, 1); else map1.put(s, map1.get(s)+1); } int tot = 0; for(int i = 1; i<=N; i++) { String s = read(); if(!map2.containsKey(s)) map2.put(s, 1); else map2.put(s, map2.get(s)+1); } for(String s : map2.keySet()) { tot += Math.max(0, map2.get(s) - (map1.containsKey(s) ? map1.get(s) : 0)); } println(tot); exit(); } final private static int BUFFER_SIZE = 1 << 16; private static DataInputStream din = new DataInputStream(System.in); private static byte[] buffer = new byte[BUFFER_SIZE]; private static int bufferPointer = 0, bytesRead = 0; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = Read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public static String read() throws IOException { byte[] ret = new byte[1024]; int idx = 0; byte c = Read(); while (c <= ' ') { c = Read(); } do { ret[idx++] = c; c = Read(); } while (c != -1 && c != ' ' && c != '\n' && c != '\r'); return new String(ret, 0, idx); } public static int readInt() throws IOException { int ret = 0; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public static long readLong() throws IOException { long ret = 0; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public static double readDouble() throws IOException { double ret = 0, div = 1; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (c == '.') { while ((c = Read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private static void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private static byte Read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } static void print(Object o) { pr.print(o); } static void println(Object o) { pr.println(o); } static void flush() { pr.flush(); } static void println() { pr.println(); } static void exit() throws IOException { din.close(); pr.close(); System.exit(0); } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.util.Comparator; 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; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); E2RotateColumnsHardVersion solver = new E2RotateColumnsHardVersion(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class E2RotateColumnsHardVersion { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); E2RotateColumnsHardVersion.Column[] columns = new E2RotateColumnsHardVersion.Column[m]; for (int i = 0; i < columns.length; ++i) columns[i] = new E2RotateColumnsHardVersion.Column(new int[n]); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { columns[j].v[i] = in.nextInt(); if (i == n - 1) columns[j].initMax(); } } Arrays.sort(columns, new Comparator<E2RotateColumnsHardVersion.Column>() { public int compare(E2RotateColumnsHardVersion.Column o1, E2RotateColumnsHardVersion.Column o2) { return o2.max - o1.max; } }); if (columns.length > n) columns = Arrays.copyOf(columns, n); long[] dp = new long[1 << n]; for (E2RotateColumnsHardVersion.Column c : columns) { long[] ndp = new long[1 << n]; System.arraycopy(dp, 0, ndp, 0, dp.length); for (int rot = 0; rot < n; ++rot) { long[] temp = new long[1 << n]; System.arraycopy(dp, 0, temp, 0, dp.length); for (int i = 0, pos = rot; i < n; ++i, ++pos) { if (pos >= n) pos = 0; int val = c.v[pos]; for (int j = 0; j < temp.length; ++j) { if ((j & (1 << i)) == 0) temp[j | (1 << i)] = Math.max(temp[j | (1 << i)], temp[j] + val); } } for (int i = 0; i < ndp.length; ++i) ndp[i] = Math.max(ndp[i], temp[i]); } dp = ndp; } out.println(dp[dp.length - 1]); } static class Column { int[] v; int max; public Column(int[] v) { this.v = v; } void initMax() { max = 0; for (int vv : v) max = Math.max(max, vv); } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public String next() { return nextString(); } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = pread(); while (isSpaceChar(c)) c = pread(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = pread(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
np
1209_E2. Rotate Columns (hard version)
CODEFORCES
import java.util.Scanner; public class Hello { public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); boolean[][] graph = new boolean[n][n]; for(int i = 0; i < m; i++) { int from = scan.nextInt() - 1; int to = scan.nextInt() - 1; graph[from][to] = graph[to][from] = true; } int max = 1 << n; long[][] dp = new long[max][n]; for(int mask = 1; mask < max; mask++) { for(int i = 0; i < n; i++) { boolean existI = (mask & (1 << i)) > 0; if(Integer.bitCount(mask) == 1 && existI) { dp[mask][i] = 1; } else if(Integer.bitCount(mask) > 1 && existI && first(mask) != i) { long sum = 0; for(int j = 0; j < n; j++) { if(graph[i][j]) sum += dp[mask ^ (1 << i)][j]; } dp[mask][i] = sum; } } } long countCycles = 0; for(int mask = 7; mask < max; mask++) { for(int i = 0; i < n; i++) { if(Integer.bitCount(mask) >= 3 && graph[first(mask)][i]) { countCycles += dp[mask][i]; } } } System.out.println(countCycles / 2); } public static int first(int mask) { int i = 0; while((mask & (1 << i++)) == 0); return i - 1; } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String x[]=br.readLine().split(" "); long l=Long.parseLong(x[0]); long r=Long.parseLong(x[1]); if(l%2!=0) { l++; } if(l+2>r) { System.out.println("-1"); } else { System.out.println(l+" "+(l+1)+" "+(l+2)); } } }
constant
483_A. Counterexample
CODEFORCES
import java.util.Scanner; public class Problem { public static void main(String[] args) throws Exception { Scanner input = new Scanner(System.in); int side = input.nextInt()-1; int x = input.nextInt()-1; int y = input.nextInt()-1; long target = input.nextLong(); int[] to_sides = {y, side - x, side - y, x}; int[] to_corners = {(y+1)+(side-x+1),(side-x+1)+(side-y+1),(side-y+1)+(x+1), (x+1)+(y+1)}; int min = Math.min(Math.min(y, x), Math.min(side - x, side - y)); int[] after_pass = {1, 1, 1, 1}; int[] corner_share = {1,1,1,1}; int steps = 0 , i; long init = 1 ; int grown = 4; while (init < target) { init += grown; steps++; if (steps >= min) { for (i = 0; i < 4; i++) { if (steps > to_sides[i]) { init -= after_pass[i]; after_pass[i] += 2; } if (steps >= to_corners[i]){ init += corner_share[i]++; //corner_share[i]++; } } } grown += 4; } System.out.println(steps); } }
logn
256_B. Mr. Bender and Square
CODEFORCES
import java.io.*; import java.util.*; public class B { static int i(String s) { return Integer.parseInt(s); } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] arr = in.readLine().split(" "); int n = i(arr[0]); int k = i(arr[1]); int[] A = new int[n]; arr = in.readLine().split(" "); for(int i=0; i<n; i++) A[i] = i(arr[i]); int st = 0; int cnt = 0; int[] cnts = new int[100*100*10+1]; for(int i=0; i<n; i++) { cnts[A[i]]++; if(cnts[A[i]] == 1) cnt++; else while(cnts[A[st]] > 1) { cnts[A[st]]--; st++; } if(cnt == k) { System.out.println((st+1)+" "+(i+1)); return; } } System.out.println(-1+" "+-1); } }
linear
224_B. Array
CODEFORCES
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.ArrayList; import java.util.Scanner; /** * * @author Ahmed */ public class Watermelon { static class Passengers { public int floor ; public int time; public Passengers( int floor , int time){ this.floor =floor; this.time =time; } } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner in = new Scanner(System.in); int x = in.nextInt() , y = in.nextInt(); ArrayList<Passengers> list = new ArrayList<>(); for(int i = 1 ; i <= x ; ++i){ list.add(new Passengers(in.nextInt(), in.nextInt())); } int sum = 0 ; for(int i = list.size() - 1 ; i >= 0 ; --i) { int s = y - list.get(i).floor; sum = sum + s ; if(sum < list.get(i).time) { sum = sum + ( list.get(i).time - sum); } y = list.get(i).floor; } if( list.get(list.size() - 1).floor != 0){ sum = sum + (list.get(0).floor); } System.out.println(sum); } }
linear
608_A. Saitama Destroys Hotel
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Solution{ public static long mod = 1000000007; public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st.nextToken()); int[] d = new int[n]; int[] g = new int[n]; for(int i=0;i<n;i++){ st = new StringTokenizer(br.readLine()); d[i] = Integer.parseInt(st.nextToken()); g[i] = Integer.parseInt(st.nextToken())-1; } long[][] dp = new long[(1<<n)][3]; for(int i=0;i<n;i++){ dp[(1<<i)][g[i]] = 1; } long res = 0; for(int i=1;i<(1<<n);i++){ int k = i; int sum = 0; for(int j=n-1;j>=0;j--){ if(k>=(1<<j)){ k-=(1<<j); sum += d[j]; } else{ for(int r=0;r<3;r++) if(r!=g[j]) dp[i+(1<<j)][g[j]] += dp[i][r]; dp[i+(1<<j)][g[j]] %= mod; } } if(sum==t){ res += dp[i][0] +dp[i][1] +dp[i][2]; res %= mod; } } out.println(res); out.flush(); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.Scanner; public class A { public static boolean realbig (long num, long s) { String str = num + ""; String[] digs = str.split(""); int sum = 0; for(String dig : digs) { sum+= Integer.parseInt(dig); } if(num-sum < s) { return false; } else { return true; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long s = sc.nextLong(); sc.close(); long count = 0; long i = s; for(; i < s+200 && i <= n; i++) { if(realbig(i,s)) { count++; } } if(i <= n) { count+=n-i+1; } System.out.println(count); } }
logn
817_C. Really Big Numbers
CODEFORCES
// package cf1209; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.Random; public class CFA { private static final String INPUT = "8\n" + "7 6 5 4 3 2 2 3\n"; private static final int MOD = 1_000_000_007; private PrintWriter out; private FastScanner sc; public static void main(String[] args) { new CFA().run(); } public void run() { sc = new FastScanner(oj ? System.in : new ByteArrayInputStream(INPUT.getBytes())); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } static class Color { int nr; boolean used; public Color(int nr) { this.nr = nr; } } private void solve() { int n = sc.nextInt(); Color[] a = new Color[n]; for (int i = 0; i < n; i++) { a[i] = new Color(sc.nextInt()); } Arrays.sort(a, Comparator.comparingInt(c -> c.nr)); int ans = 0; for (int i = 0; i < n; i++) { if (a[i].used) continue; ans++; for (int j = i+1; j < n; j++) { if (a[j].nr % a[i].nr == 0) { a[j].used = true; } } } out.println(ans); } //******************************************************************************************** //******************************************************************************************** //******************************************************************************************** static class SolutionFailedException extends Exception { int code; public SolutionFailedException(int code) { this.code = code; } } int [] sort(int [] a) { final int SHIFT = 16, MASK = (1 << SHIFT) - 1, SIZE = (1 << SHIFT) + 1; int n = a.length, ta [] = new int [n], ai [] = new int [SIZE]; for (int i = 0; i < n; ai[(a[i] & MASK) + 1]++, i++); for (int i = 1; i < SIZE; ai[i] += ai[i - 1], i++); for (int i = 0; i < n; ta[ai[a[i] & MASK]++] = a[i], i++); int [] t = a; a = ta; ta = t; ai = new int [SIZE]; for (int i = 0; i < n; ai[(a[i] >> SHIFT) + 1]++, i++); for (int i = 1; i < SIZE; ai[i] += ai[i - 1], i++); for (int i = 0; i < n; ta[ai[a[i] >> SHIFT]++] = a[i], i++); return ta; } private static void shuffle(int[] array) { Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { int index = random.nextInt(i + 1); int temp = array[index]; array[index] = array[i]; array[i] = temp; } } /** * If searched element doesn't exist, returns index of first element which is bigger than searched value.<br> * If searched element is bigger than any array element function returns first index after last element.<br> * If searched element is lower than any array element function returns index of first element.<br> * If there are many values equals searched value function returns first occurrence.<br> */ private static int lowerBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key <= arr[mid]) { hi = mid - 1; } else { lo = mid + 1; } } return arr[lo] < key ? lo + 1 : lo; } /** * Returns index of first element which is grater than searched value. * If searched element is bigger than any array element, returns first index after last element. */ private static int upperBound(long[] arr, long key) { int lo = 0; int hi = arr.length - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (key >= arr[mid]) { lo = mid + 1; } else { hi = mid; } } return arr[lo] <= key ? lo + 1 : lo; } private static int ceil(double d) { int ret = (int) d; return ret == d ? ret : ret + 1; } private static int round(double d) { return (int) (d + 0.5); } private static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } private static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } private int[] readIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextInt(); } return res; } private long[] readLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = sc.nextLong(); } return res; } @SuppressWarnings("unused") static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; FastScanner(InputStream stream) { this.stream = stream; } int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
// LM10: The next Ballon d'or import java.util.*; import java.io.*; import java.math.*; import javafx.util.Pair; public class Main { static class FastReader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public FastReader() { this(System.in); }public FastReader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String next(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();} public long l(){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 int i(){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 double d() throws IOException {return Double.parseDouble(next()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void scanIntArr(int [] arr){ for(int li=0;li<arr.length;++li){ arr[li]=i();}} public void scanLongArr(long [] arr){for (int i=0;i<arr.length;++i){arr[i]=l();}} public void shuffle(int [] arr){ for(int i=arr.length;i>0;--i) { int r=(int)(Math.random()*i); int temp=arr[i-1]; arr[i-1]=arr[r]; arr[r]=temp; } } } public static void main(String[] args)throws IOException { /* inputCopy 4 2 1 2 1 outputCopy 4 inputCopy 5 0 -1 -1 -1 -1 outputCopy 4 */ PrintWriter pw = new PrintWriter(System.out); FastReader fr = new FastReader(); int n=fr.i(); int [] arr=new int[n]; fr.scanIntArr(arr); int min=Integer.MAX_VALUE; int max=Integer.MIN_VALUE; long sum=0; if(n==1) { pw.println(arr[0]); pw.flush(); pw.close(); return; } for(int i=0;i<n;++i) { if(arr[i]<min) min=arr[i]; if(arr[i]>max) max=arr[i]; sum+=Math.abs(arr[i]); } if(min>0) { sum-=2*min; } if(max<0) { sum+=2*max; } pw.println(sum); pw.flush(); pw.close(); } }
linear
1038_D. Slime
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; import java.util.HashMap; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){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 long l(){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 int i(){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 double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String args[]) { Reader sc=new Reader(); PrintWriter out=new PrintWriter(System.out); int n=sc.i(); String s1=sc.s(); String s2=sc.s(); int pos1=-1; int pos2=-1; int arr[][][]=new int[100][100][2]; for(int i=0;i<n;i++) { if(s1.charAt(i)!=s2.charAt(i)) { if(arr[s2.charAt(i)-97][s1.charAt(i)-97][0]==1) { pos2=i; pos1=arr[s2.charAt(i)-97][s1.charAt(i)-97][1]; break; } arr[s1.charAt(i)-97][s2.charAt(i)-97][0]=1; arr[s1.charAt(i)-97][s2.charAt(i)-97][1]=i; } } int ham=0; for(int i=0;i<n;i++) { if(s1.charAt(i)!=s2.charAt(i)) ham++; } if(pos1!=-1&&pos2!=-1) { System.out.println(ham-2); System.out.println(pos1+1+" "+(pos2+1)); System.exit(0); } int arr1[][]=new int[100][2]; int arr2[][]=new int[100][2]; for(int i=0;i<n;i++) { if(s1.charAt(i)!=s2.charAt(i)) { if(arr1[s1.charAt(i)-97][0]==1) { pos2=i; pos1=arr1[s1.charAt(i)-97][1]; break; } if(arr2[s2.charAt(i)-97][0]==1) { pos2=i; pos1=arr2[s2.charAt(i)-97][1]; break; } arr1[s2.charAt(i)-97][0]=1; arr1[s2.charAt(i)-97][1]=i; arr2[s1.charAt(i)-97][0]=1; arr2[s1.charAt(i)-97][1]=i; } } if(pos1!=-1&&pos2!=-1) { System.out.println(ham-1); System.out.println(pos1+1+" "+(pos2+1)); System.exit(0); } System.out.println(ham); System.out.println(pos1+" "+pos2); } }
linear
527_B. Error Correct System
CODEFORCES
import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedList; import java.util.Scanner; public class C { static class Struct { int x, y, count; public Struct(int xx, int yy, int c) { x = xx; y = yy; count = c; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new FileReader("input.txt")); int n = sc.nextInt(); int m = sc.nextInt(); FileWriter fw=new FileWriter("output.txt"); boolean[][] grid = new boolean[n][m]; int[] dx = new int[] { 1, 0, -1, 0 }; int[] dy = new int[] { 0, -1, 0, 1 }; int k = sc.nextInt(); LinkedList<Struct> a = new LinkedList<Struct>(); for (int i = 0; i < k; i++) { a.add(new Struct(sc.nextInt() - 1, sc.nextInt() - 1, 0)); } int max = Integer.MIN_VALUE, maxX = -1, maxY = -1; while (!a.isEmpty()) { Struct tmp = a.remove(); if (grid[tmp.x][tmp.y] == true) continue; grid[tmp.x][tmp.y] = true; if (tmp.count > max) { max = tmp.count; maxX = tmp.x; maxY = tmp.y; } for (int i = 0; i < 4; i++) { int nx = tmp.x + dx[i]; int ny = tmp.y + dy[i]; if (nx < n && nx >= 0 && ny < m && ny >= 0) { if (grid[nx][ny] == false) { a.add(new Struct(nx, ny, tmp.count + 1)); } } } } fw.write((maxX + 1) + " " + (maxY + 1)+"\n"); System.out.println((maxX + 1) + " " + (maxY + 1)); fw.flush(); } }
cubic
35_C. Fire Again
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 Jaynil */ 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); BSportMafia solver = new BSportMafia(); solver.solve(1, in, out); out.close(); } static class BSportMafia { public void solve(int testNumber, InputReader in, PrintWriter out) { long n = in.nextLong(); long k = in.nextLong(); long b = 2 * n + 3; long c = n * n - 2 * k + n; long d = b * b - 4 * c; long val = (b - (long) Math.sqrt(d)) / 2; out.println(val); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class c { public static void main(String[] args) { Scanner in = new Scanner(System.in); int numbOfStatements = in.nextInt(); long[] dp = new long[numbOfStatements]; dp[0] = 1L; boolean priorFor = in.next().equals("f"); for(int i=0; i<numbOfStatements-1; i++) { String type = in.next(); if (priorFor) { for(int j=numbOfStatements-1;j>0;j--) { dp[j] = dp[j-1]; } dp[0] = 0L; } else { long sum = 0; for(int j = numbOfStatements - 1; j >= 0; --j) { sum = (sum + dp[j]) % 1000000007; dp[j] = sum; } } priorFor = type.equals("f"); } long ans = 0; for(int j=0; j<numbOfStatements; j++) { ans = (ans + dp[j]) % 1000000007; } System.out.println(ans); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import static java.lang.Math.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Map.Entry; import java.util.StringTokenizer; import java.util.TreeMap; /** * * @author pttrung */ public class C { public static double Epsilon = 1e-6; public static long x, y, d; public static long MOD = 1000000007; public static int[][][] dp; public static int min, max, need; public static void main(String[] args) { Scanner in = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); min = Math.min(n, m); max = (m + n) - min; dp = new int[max][1 << min][1 << min]; for (int[][] temp : dp) { for (int[] val : temp) { Arrays.fill(val, -1); } } need = (1 << min) - 1; //System.out.println(add + total); // System.out.println(min + " " + max); out.println(cal(0, 0, 0)); out.close(); } public static int cal(int index, int last, int lastHold) { if (index == max) { return 0; } if (dp[index][lastHold][last] != -1) { return dp[index][lastHold][last]; } int result = 0; for (int i = 0; i < 1 << min; i++) { if ((i | last) == need || (index == 0)) { // System.out.println("PREV " + index + " " + i + " " + last + " " + lastHold); // System.out.println("NEXT " + index + " " + i + " " + (i | lastHold) + " " + i); // System.out.println(Integer.bitCount(i) + " " + i); // if (index == 3) { // System.out.println(last + " " + i + " " + match(i, last) + " " + next); // } if(index + 1 == max && match(i,lastHold)!= need){ continue; } int temp = cal(index + 1, match(i,lastHold), i) + (min - Integer.bitCount(i)); result = result < temp ? temp : result; // break; } } dp[index][lastHold][last] = result; return result; } public static int match(int mask, int last) { int result = last; for (int i = 0; i < min; i++) { if (((1 << i) & mask) != 0) { int a = i - 1; int b = i + 1; result |= (1 << i); if (a >= 0) { result |= (1 << a); } if (b < min) { result |= (1 << b); } } } // System.out.println(mask + " " + result + " " + need); return result ; } public static long pow(long a, long b) { if (b == 0) { return 1; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return a * (val * val % MOD) % MOD; } } public static void extendEuclid(long a, long b) { if (b == 0) { x = 1; y = 0; d = a; return; } extendEuclid(b, a % b); long x1 = y; long y1 = x - (a / b) * y; x = x1; y = y1; } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } static class Line { double a, b, c; Line(double x1, double y1, double x2, double y2) { if (Math.abs(x1 - x2) < Epsilon && Math.abs(y1 - y2) < Epsilon) { throw new RuntimeException("Two point are the same"); } a = y1 - y2; b = x2 - x1; c = -a * x1 - b * y1; } Line(Point x, Point y) { this(x.x, x.y, y.x, y.y); } public Line perpendicular(Point p) { return new Line(p, new Point(p.x + a, p.y + b)); } public Point intersect(Line l) { double d = a * l.b - b * l.a; if (d == 0) { throw new RuntimeException("Two lines are parallel"); } return new Point((l.c * b - c * l.b) / d, (l.a * c - l.c * a) / d); } } static void check(Point a, Point b, ArrayList<Point> p, Point[] rec, int index) { for (int i = 0; i < 4; i++) { int m = (i + index) % 4; int j = (i + 1 + index) % 4; Point k = intersect(minus(b, a), minus(rec[m], rec[j]), minus(rec[m], a)); if (k.x >= 0 && k.x <= 1 && k.y >= 0 && k.y <= 1) { Point val = new Point(k.x * minus(b, a).x, k.x * minus(b, a).y); p.add(add(val, a)); // System.out.println(a + " " + b + " " + rec[i] + " " + rec[j]); // System.out.println(add(val, a)); } } } static Point intersect(Point a, Point b, Point c) { double D = cross(a, b); if (D != 0) { return new Point(cross(c, b) / D, cross(a, c) / D); } return null; } static Point convert(Point a, double angle) { double x = a.x * cos(angle) - a.y * sin(angle); double y = a.x * sin(angle) + a.y * cos(angle); return new Point(x, y); } static Point minus(Point a, Point b) { return new Point(a.x - b.x, a.y - b.y); } static Point add(Point a, Point b) { return new Point(a.x + b.x, a.y + b.y); } static double cross(Point a, Point b) { return a.x * b.y - a.y * b.x; } static class Point { double x, y; Point(double x, double y) { this.x = x; this.y = y; } @Override public String toString() { return "Point: " + x + " " + y; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
np
111_C. Petya and Spiders
CODEFORCES