src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; import static java.lang.Integer.MAX_VALUE; import static java.lang.Integer.parseInt; /** * 8C * * @author artyom */ public class LookingForOrder { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] parsedString = parsedString = in.readLine().split(" "); int xStart = parseInt(parsedString[0]); int yStart = parseInt(parsedString[1]); int objectNum = parseInt(in.readLine()); int[] xLocs = new int[objectNum + 1]; int[] yLocs = new int[objectNum + 1]; int[] bitMasks = new int[1 << objectNum]; Arrays.fill(bitMasks, MAX_VALUE); int[] previous = new int[1 << objectNum]; xLocs[objectNum] = xStart; yLocs[objectNum] = yStart; for (int i = 0; i < objectNum; i++) { parsedString = in.readLine().split(" "); xLocs[i] = parseInt(parsedString[0]); yLocs[i] = parseInt(parsedString[1]); } //go through all pairs and find time requirement for each pair of objects //the entry at point [i][j] is equal to the time it takes to get from point i to point j int[][] times = new int[objectNum + 1][objectNum + 1]; for (int i = 0; i <= objectNum; i++) { for (int j = 0; j <= objectNum; j++) { times[i][j] = times[j][i] = (xLocs[i] - xLocs[j]) * (xLocs[i] - xLocs[j]) + (yLocs[i] - yLocs[j]) * (yLocs[i] - yLocs[j]); } } //each value in bitmasks represents the minimum time necessary to get //the unmasked bits //so bitmasks[5] (5=101) is the fastest time in which you can get //items 1 and 3 bitMasks[0] = 0; //collecting zero objects takes 0 time for (int i = 0; i < (1 << objectNum); i++) { if (bitMasks[i] != MAX_VALUE) { for (int j = 0; j < objectNum; j++) { if (((1 << j) & i) == 0) { //if our current j object hasn't been picked up yet int curState = (1 << j) | i; //ith state after picking up j object int curTime = bitMasks[i] + 2 * times[objectNum][j]; //time required to get object j from bag at state i if (curTime < bitMasks[curState]) { bitMasks[curState] = curTime; //put fastest time in for gettingto our current state previous[curState] = i; } //find another thing while you're out for (int k = 0; k < objectNum; k++) { if (((1 << k) & curState) == 0) { //if the kth position in our current state hasn't been picked up int kState = ((1 << k) | curState); //curstate after picking up the kth object //kTime is time it takes to go from bag, to j, to k and back int kTime = bitMasks[i] + times[objectNum][j] + times[j][k] + times[k][objectNum]; if (kTime < bitMasks[kState]) { bitMasks[kState] = kTime; //put shortest time for getting to kState in previous[kState] = i; } } } break; } } } } int finalState = (1 << objectNum) - 1; StringBuilder sb = new StringBuilder(); sb.append(bitMasks[finalState]).append('\n'); Deque<Integer> outputQ = new ArrayDeque<>(); outputQ.add(0); int curState = finalState; while (curState > 0) { //difference is the objects picked up in this state but not in previous state int difference = curState ^ previous[curState]; int firstItem = -1; int secondItem = -1; for (int i = 0; i < objectNum; i++) { if (((1 << i) & difference) > 0) { //if the ith object was picked up in this state secondItem = firstItem; //keep track of how many items are picked up firstItem = i; } } if (secondItem != -1) { //put in two items followed by a return to 0 outputQ.add(firstItem + 1); outputQ.add(secondItem + 1); outputQ.add(0); } else { outputQ.add(firstItem + 1); outputQ.add(0); } curState = previous[curState]; } sb.append(outputQ.removeLast()); while (!outputQ.isEmpty()) { sb.append(' ').append(outputQ.removeLast()); } System.out.print(sb); } }
np
8_C. Looking for Order
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.io.*; import java.util.*; import static java.lang.Math.*; public class codeforces { public static long cnt = 0; public static void f(int g1, int g2, int g3, int last) { if (g1 == 0 && g2 == 0 && g3 == 0) cnt++; if (g1 > 0 && last != 1) f(g1 - 1, g2, g3, 1); if (g2 > 0 && last != 2) f(g1, g2 - 1, g3, 2); if (g3 > 0 && last != 3) f(g1, g2, g3 - 1, 3); } public static void main(String[] args) throws IOException { BufferedReader scan = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(scan.readLine()); int n = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st.nextToken()); int T[] = new int[n]; int G[] = new int[n]; for (int i = 0; i < n; i++) { st = new StringTokenizer(scan.readLine()); T[i] = Integer.parseInt(st.nextToken()); G[i] = Integer.parseInt(st.nextToken()); } long ans = 0; for (int mask = 1; mask < (1 << n); mask++) { int sum = 0; int g1 = 0; int g2 = 0; int g3 = 0; for (int i = 0; i < n; i++) { if (((1 << i) & mask) > 0) { sum += T[i]; if (G[i] == 1) g1++; if (G[i] == 2) g2++; if (G[i] == 3) g3++; } } cnt = 0; if (sum == t) f(g1, g2, g3, -1); for (long i = 1; i <= g1; i++) cnt *= i; for (long i = 1; i <= g2; i++) cnt *= i; for (long i = 1; i <= g3; i++) cnt *= i; ans += cnt; } System.out.println(ans % 1000000007); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Main { /** * @param args */ static int N, M; static long[] C; static int[][] g; static long[][] DP; public static void main(String[] args) { InputReader r = new InputReader(System.in); N = r.nextInt(); M = r.nextInt(); g = new int[N][N]; C = new long[N + 1]; DP = new long[1 << N][N]; for(int k = 0; k < M; k++){ int i = r.nextInt() - 1; int j = r.nextInt() - 1; g[i][j] = g[j][i] = 1; } for(long[] i : DP) Arrays.fill(i, -1); long ret = 0; for(int s = 0; s < N; s++){ ret += go(s, 1 << s, s); } System.out.println(ret / 2); } private static long go(int s, int m, int e) { if(DP[m][e] != -1)return DP[m][e]; long cnt = 0; for(int j = s; j < N; j++)if(g[e][j] == 1){ if((m & (1 << j)) != 0){ if(s == j && Integer.bitCount(m) >= 3){ cnt++; } }else{ cnt += go(s, m | 1 << j, j); } } return DP[m][e] = cnt; } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class CodeForces { public static void main(String[] args) throws IOException,NumberFormatException{ try { FastScanner sc=new FastScanner(); int t=sc.nextInt(); while(t-->0) { int a=sc.nextInt(),b=sc.nextInt(); int count=0; while(a!=0&&b!=0) { if(a>b) { int temp=a; a=b; b=temp; } count+=(b/a); b=b%a; } System.out.println(count); } } catch(Exception e) { return ; } } public static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) {} return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
constant
267_A. Subtractions
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; public class Main { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws NumberFormatException, IOException { String[] s = br.readLine().trim().split(" "); int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); long b[] = new long[n]; s = br.readLine().trim().split(" "); for(int i = 0; i < n; i++) { b[i] = Integer.parseInt(s[i]); } long g[] = new long[m]; s = br.readLine().trim().split(" "); for(int i = 0; i < m; i++) { g[i] = Integer.parseInt(s[i]); } Arrays.sort(b); Arrays.sort(g); if(g[0] < b[n-1]) { System.out.println("-1"); } else if(g[0] == b[n-1]){ long ans = 0; for(int i = 0; i < m; i++) { ans += g[i]; } for(int i = 0; i < n-1; i++) { ans += (m)*b[i]; } System.out.println(ans); } else { long ans = 0; for(int i = 0; i < m; i++) { ans += g[i]; } for(int i = 0; i < n-1; i++) { ans += (m)*b[i]; } ans += b[n-1]-b[n-2]; System.out.println(ans); } } }
nlogn
1159_C. The Party and Sweets
CODEFORCES
import java.io.*; import java.util.*; public class A { void run() throws IOException { int n = ni(); int m = ni(); int k = ni(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni() - 1; Arrays.sort(a); int ans = 0; if (m > k) { m -= k - 1; for (int i = n - 1; i >= 0; i--) { ans++; m -= a[i]; if (m < 2) break; } if (m > 1) ans = -1; } pw.print(ans); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } String nl() throws IOException { return br.readLine(); } PrintWriter pw; BufferedReader br; StringTokenizer st; public static void main(String[] args) throws IOException { long timeout = System.currentTimeMillis(); boolean CF = System.getProperty("ONLINE_JUDGE") != null; PrintWriter _pw = new PrintWriter(System.out); BufferedReader _br = new BufferedReader(CF ? new InputStreamReader(System.in) : new FileReader(new File("in.txt"))); new A(_br, _pw).run(); if (!CF) { _pw.println(); _pw.println(System.currentTimeMillis() - timeout); } _br.close(); _pw.close(); } public A(BufferedReader _br, PrintWriter _pw) { br = _br; pw = _pw; } }
nlogn
257_A. Sockets
CODEFORCES
import java.io.*; import java.util.*; public class B implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int n = scn.nextInt(); int[] arr = scn.nextIntArray(n); int[][] a = new int[n * (n + 1) / 2][]; int[] need = new int[a.length]; int pos = 0; for (int l = 0; l < n; l++) { int sum = 0; for (int r = l; r < n; r++) { sum += arr[r]; a[pos] = new int[] { l, r, sum }; need[pos++] = sum; } } need = scn.uniq(need); int[][][] list = new int[need.length][][]; int[] size = new int[list.length]; for (int i = 0; i < pos; i++) { size[Arrays.binarySearch(need, a[i][2])]++; } for (int i = 0; i < list.length; i++) { list[i] = new int[size[i]][]; } for (int i = 0; i < pos; i++) { int ind = Arrays.binarySearch(need, a[i][2]); list[ind][--size[ind]] = new int[] { a[i][0], a[i][1] }; } int ind = -1, max = 0; for (int i = 0; i < list.length; i++) { if(list[i].length == 0) { continue; } Arrays.sort(list[i], (o1, o2) -> o1[1] - o2[1]); int count = 1, last = list[i][0][1]; for(int j = 1; j < list[i].length; j++) { if(list[i][j][0] > last) { count++; last = list[i][j][1]; } } if (count > max) { max = count; ind = i; } } out.println(max); int last = list[ind][0][1]; out.println((list[ind][0][0] + 1) + " " + (list[ind][0][1] + 1)); for(int i = 1; i < list[ind].length; i++) { if(list[ind][i][0] > last) { out.println((list[ind][i][0] + 1) + " " + (list[ind][i][1] + 1)); last = list[ind][i][1]; } } } public void run() { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) { new Thread(null, new B(), "Main", 1 << 26).start(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } int[] uniq(int[] arr) { Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } int[] reverse(int[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; public class CodehorsesT_shirts { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); HashMap<String, Integer> map = new HashMap<String, Integer>(); String input; for (int i = 0; i < n; i++) { input = reader.readLine(); if (map.containsKey(input)) { map.put(input, map.get(input) + 1); } else { map.put(input, 1); } } int change = 0; for (int i = 0; i < n; i++) { input = reader.readLine(); if (map.containsKey(input)) { map.put(input, map.get(input) - 1); } else { map.put(input, -1); } } for (int x : map.values()) { change += Math.abs(x); } System.out.println(change/2); } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.io.*; import java.awt.geom.Point2D; import java.text.*; import java.math.*; import java.util.*; public class Main implements Runnable { final String filename = ""; public void solve() throws Exception { int n = iread(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = iread(); Arrays.sort(a); boolean test = true; for (int i = 0; i < n; i++) { if (a[i] != 1) test = false; int min = (i == 0) ? 1 : a[i - 1]; if (test && i == n - 1) out.write((min + 1) + ""); else out.write(min + ""); if (i == n - 1) out.write("\n"); else out.write(" "); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); // in = new BufferedReader(new FileReader(filename+".in")); // out = new BufferedWriter(new FileWriter(filename+".out")); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public int iread() throws Exception { return Integer.parseInt(readword()); } public double dread() throws Exception { return Double.parseDouble(readword()); } public long lread() throws Exception { return Long.parseLong(readword()); } BufferedReader in; BufferedWriter out; public String readword() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) { try { Locale.setDefault(Locale.US); } catch (Exception e) { } // new Thread(new Main()).start(); new Thread(null, new Main(), "1", 1 << 25).start(); } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.*; import java.util.*; public class utkarsh{ BufferedReader br; void solve(){ br = new BufferedReader(new InputStreamReader(System.in)); int i, j, n, mod = (int)(1e9 + 7); n = ni(); char c[] = new char[n]; for(i = 0; i < n; i++) c[i] = ns().charAt(0); long dp[][] = new long[n][n]; dp[0][0] = 1; for(i = 1; i < n; i++){ if(c[i-1] == 'f'){ for(j = 0; j < i; j++){ dp[i][j+1] = dp[i-1][j]; } }else{ for(j = i-1; j >= 0; j--){ dp[i][j] = dp[i-1][j] + dp[i][j+1]; dp[i][j] %= mod; } } } long ans = 0; for(long x : dp[n-1]){ ans += x; ans %= mod; } System.out.println(ans); } int ni(){ return Integer.parseInt(ns()); } String ip[]; int len, sz; String ns(){ if(len >= sz){ try{ ip = br.readLine().split(" "); len = 0; sz = ip.length; }catch(IOException e){ throw new InputMismatchException(); } if(sz <= 0) return "-1"; } return ip[len++]; } public static void main(String[] args){ new utkarsh().solve(); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pradyumn */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { FastReader in; PrintWriter out; int n; public void solve(int testNumber, FastReader in, PrintWriter out) { this.in = in; this.out = out; n = in.nextInt(); if (n % 4 != 0) { out.println("! -1"); return; } int low = 0; int high = n >> 1; int fSign = Integer.signum(BValue(low)); if (fSign == 0) { out.println("! " + (low + 1)); return; } while (high - low > 1) { int mid = (high + low) >> 1; int mSign = Integer.signum(BValue(mid)); if (mSign == 0) { out.println("! " + (mid + 1)); return; } if (mSign == -fSign) { high = mid; } else { low = mid; } } out.println("! -1"); } public int BValue(int index) { out.println("? " + (index + 1)); out.flush(); int f = in.nextInt(); out.println("? " + (index + 1 + (n >> 1))); out.flush(); int s = in.nextInt(); return f - s; } } 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 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; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
logn
1019_B. The hat
CODEFORCES
import java.util.*; import java.io.*; public class Longest { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String str=sc.nextLine(); int max=0; for(int i=0;i<str.length();i++) { for(int x=0;x+i<=str.length();x++) { if(contains(str,str.substring(x,x+i),x)) { //System.out.println(str.substring(x,x+i)); max=Math.max(max, i); } } } System.out.println(max); } public static boolean contains(String whole,String part,int start) { if(whole.indexOf(part, start+1)>=0)return true; return false; } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; /** * * @author Dstoical */ public class G { private static int M = 1000000007, MM = 998244353; private static int N = 15,n,T; private static int[] time,gi; private static int[][][] dp; public static void process() throws IOException { n = sc.nextInt();T = sc.nextInt(); time = new int[n+1]; gi = new int[n+1]; for(int i=0; i<n; i++) { int a = sc.nextInt(),b = sc.nextInt(); time[i] = a; gi[i] = b-1; } dp = new int[1<<n][T+1][3]; for(int i=0; i<1<<n; i++) { for(int j=0; j<T+1; j++) { for(int k=0; k<3; k++)dp[i][j][k] = -1; } } int ans = 0; for(int i=0; i<n; i++) { if(time[i] <= T) { ans = (ans + solve(1<<i,time[i],gi[i]))%M; } } println(ans); } private static int solve(int mask, int tim, int code) { if(tim == T)return 1; if(dp[mask][tim][code] != -1)return dp[mask][tim][code]; int ans = 0; for(int i=0; i<n; i++) { if((mask>>i & 1) > 0)continue; if(code == gi[i])continue; if(tim + time[i] > T)continue; ans = (ans + solve(mask|(1<<i), time[i]+tim, gi[i]))%M; } return dp[mask][tim][code] = (ans%M); } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= static FastScanner sc; static PrintWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new PrintWriter(System.out); } else { sc = new FastScanner(100); out = new PrintWriter("output.txt"); } int t = 1; // t = sc.nextInt(); while (t-- > 0) { process(); } out.flush(); out.close(); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static void println(Object o) { out.println(o); } static void println() { out.println(); } static void print(Object o) { out.print(o); } static void pflush(Object o) { out.println(o); out.flush(); } static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static int max(int x, int y) { return Math.max(x, y); } static int min(int x, int y) { return Math.min(x, y); } static int abs(int x) { return Math.abs(x); } static long abs(long x) { return Math.abs(x); } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } static long max(long x, long y) { return Math.max(x, y); } static long min(long x, long y) { return Math.min(x, y); } public static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } public 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(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(System.in)); } FastScanner(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; } int[] readArray(int n) throws IOException { int[] A = new int[n]; for (int i = 0; i != n; i++) { A[i] = sc.nextInt(); } return A; } long[] readArrayLong(int n) throws IOException { long[] A = new long[n]; for (int i = 0; i != n; i++) { A[i] = sc.nextLong(); } return A; } } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.io.PrintWriter; import java.util.*; import java.util.Arrays ; import java .lang.String.* ; import java .lang.StringBuilder ; public class Test{ static int pos = 0 ; static int arr[] ; static LinkedList l1 = new LinkedList() ; static void find(int p ,char[]x,int put[],String s){ int c= 0 ; for (int i = 0; i < s.length(); i++) { if(x[p]==s.charAt(i)){ c++ ; } } put[p] = c ; } static int mode(int m ,int[]x ){ int temp = 0 ; for (int i = x.length-1; i >=0; i--) { if(x[i]<=m){ temp= x[i] ; /// break ; return m-temp ; } } return m-temp ; } static int mode2(int m ,int[]x ){ int temp = 0 ; for (int i = x.length-1; i >=0; i--) { if(x[i]<=m){ temp= x[i] ; /// break ; return x[i] ; } } return 0 ; } static int find(int x[],int temp){ int j = 0 ; for (int i = x.length-1; i >=0; i--) { if(x[i]==temp) return j+1 ; j++ ; } return -1 ; } static String ch(long[]x,long b){ for (int i = 0; i < x.length; i++) { if(x[i]==b)return "YES" ; } return "NO" ; } public static void main(String[] args) { Scanner in = new Scanner(System.in) ; PrintWriter pw = new PrintWriter(System.out); long n = in.nextLong() ; long count =1 ; long temp =n/2; temp+=count ; System.out.println(temp); } }
constant
964_A. Splits
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class A{ Scanner sc=new Scanner(System.in); void run(){ String s=sc.nextLine(); int n=s.length(); int ans=0; for(int len=1; len<n; len++){ for(int i=0; i+len<=n; i++){ String t=s.substring(i, i+len); // println(t); if(s.indexOf(t,i+1)!=-1){ ans=len; break; } } } println(ans+""); } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } public static void main(String[] args){ new A().run(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; public class Main { static int mod = 1000000007; static int size = 200000; static long[] fac = new long[size]; static long[] finv = new long[size]; static long[] inv = new long[size]; static int INF = Integer.MAX_VALUE; public static void main(String[] args){ Scanner scanner = new Scanner(System.in); String[] s = new String[2]; for(int i = 0; i < 2; i++){ s[i] = scanner.next(); } int n = s[0].length(); char[][] c = new char[2][n]; for(int i = 0; i < 2; i++){ for(int j = 0; j < n; j++){ c[i][j] = s[i].charAt(j); } } int count = 0; for(int i = 0; i < n-1; i++){ if(c[0][i] == '0' && c[1][i] == '0' && c[0][i+1] == '0'){ c[0][i] = 'X'; c[1][i] = 'X'; c[0][i+1] = 'X'; count++; } if(c[0][i] == '0' && c[1][i] == '0' && c[1][i+1] == '0'){ c[0][i] = 'X'; c[1][i] = 'X'; c[1][i+1] = 'X'; count++; } if(c[0][i] == '0' && c[0][i+1] == '0' && c[1][i+1] == '0'){ c[0][i] = 'X'; c[0][i+1] = 'X'; c[1][i+1] = 'X'; count++; } if(c[0][i+1] == '0' && c[1][i+1] == '0' && c[1][i] == '0'){ c[1][i] = 'X'; c[0][i+1] = 'X'; c[1][i+1] = 'X'; count++; } } System.out.println(count); } public static boolean isPrime(int n){ if(n == 1) return false; if(n == 2 || n == 3) return true; for(int i = 2; i <= Math.sqrt(n); i++){ if(n % i == 0) return false; } return true; } // tar の方が数字が大きいかどうか static boolean compare(String tar, String src) { if (src == null) return true; if (src.length() == tar.length()) { int len = tar.length(); for (int i = 0; i < len; i++) { if (src.charAt(i) > tar.charAt(i)) { return false; } else if (src.charAt(i) < tar.charAt(i)) { return true; } } return tar.compareTo(src) > 0 ? true : false; } else if (src.length() < tar.length()) { return true; } else if (src.length() > tar.length()) { return false; } return false; } public static class Edge{ int to; Edge(int to){ this.to = to; } } public static void swap(long a, long b){ long tmp = 0; if(a > b){ tmp = a; a = b; b = tmp; } } static class Pair implements Comparable<Pair>{ int first, second; Pair(int a, int b){ first = a; second = b; } @Override public boolean equals(Object o){ if (this == o) return true; if (!(o instanceof Pair)) return false; Pair p = (Pair) o; return first == p.first && second == p.second; } @Override public int compareTo(Pair p){ return first == p.first ? second - p.second : first - p.first; //firstで昇順にソート //return (first == p.first ? second - p.second : first - p.first) * -1; //firstで降順にソート //return second == p.second ? first - p.first : second - p.second;//secondで昇順にソート //return (second == p.second ? first - p.first : second - p.second)*-1;//secondで降順にソート } } //繰り返し二乗法 public static long pow(long x, long n){ long ans = 1; while(n > 0){ if((n & 1) == 1){ ans = ans * x; ans %= mod; } x = x * x % mod; n >>= 1; } return ans; } public static long div(long x, long y){ return (x*pow(y, mod-2))%mod; } //fac, inv, finvテーブルの初期化、これ使う場合はinitComb()で初期化必要 public static void initComb(){ fac[0] = finv[0] = inv[0] = fac[1] = finv[1] = inv[1] = 1; for (int i = 2; i < size; ++i) { fac[i] = fac[i - 1] * i % mod; inv[i] = mod - (mod / i) * inv[(int) (mod % i)] % mod; finv[i] = finv[i - 1] * inv[i] % mod; } } //nCk % mod public static long comb(int n, int k){ return fac[n] * finv[k] % mod * finv[n - k] % mod; } //n! % mod public static long fact(int n){ return fac[n]; } //(n!)^-1 with % mod public static long finv(int n){ return finv[n]; } static class UnionFind { int[] parent; public UnionFind(int size) { parent = new int[size]; Arrays.fill(parent, -1); } public boolean unite(int x, int y) { x = root(x); y = root(y); if (x != y) { if (parent[y] < parent[x]) { int tmp = y; y = x; x = tmp; } parent[x] += parent[y]; parent[y] = x; return true; } return false; } public boolean same(int x, int y) { return root(x) == root(y); } public int root(int x) { return parent[x] < 0 ? x : (parent[x] = root(parent[x])); } public int size(int x) { return -parent[root(x)]; } } public static int upperBound(int[] array, int value) { int low = 0; int high = array.length; int mid; while( low < high ) { mid = ((high - low) >>> 1) + low; // (high + low) / 2 if( array[mid] <= value ) { low = mid + 1; } else { high = mid; } } return low; } public static final int lowerBound(final int[] arr, final int value) { int low = 0; int high = arr.length; int mid; while (low < high){ mid = ((high - low) >>> 1) + low; //(low + high) / 2 (オーバーフロー対策) if (arr[mid] < value) { low = mid + 1; } else { high = mid; } } return low; } //n,mの最大公約数 public static long gcd(long n, long m){ if(m > n) return gcd(m,n); if(m == 0) return n; return gcd(m, n%m); } //3要素のソート private class Pair2 implements Comparable<Pair2> { String s; int p; int index; public Pair2(String s, int p, int index) { this.s = s; this.p = p; this.index = index; } public int compareTo(Pair2 other) { if (s.equals(other.s)) { return other.p - this.p; } return this.s.compareTo(other.s); } } //c -> intに変換 public static int c2i(char c){ if('A' <= c && c <= 'Z'){ return c - 'A'; }else{ return c - 'a' + 26; } } // int -> charに変換 public static char i2c(int i){ if(0 <= i && i < 26){ return (char)(i + 'A'); }else{ return (char)(i + 'a' - 26); } } }
constant
991_D. Bishwock
CODEFORCES
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.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.StringTokenizer; import java.util.concurrent.LinkedBlockingDeque; import javax.swing.border.Border; public class a { public static long mod = (long) Math.pow(10, 9) + 7; private static class node implements Comparable<node> { int x; int y; node(int x, int c) { this.x = x; this.y = c; } @Override public int compareTo(node o) { if (o.x < x) return 1; else if (o.x > x) return -1; else if (o.y < y) return 1; else if (o.y > y) return -1; else return 0; } } 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) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder qq = new StringBuilder(); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); // int n = Integer.parseInt(in.readLine()); String y[] = in.readLine().split(" "); long n = Long.parseLong(y[0]); long m = Long.parseLong(y[1]); if (m - n < 2) { System.out.println(-1); } else if (m - n == 2) { if (gcd(n, m) != 1) System.out.println(n + " " + (n + 1) + " " + (n + 2)); else System.out.println(-1); } else { if (n % 2 == 0) System.out.println(n + " " + (n + 1) + " " + (n + 2)); else System.out.println((n + 1) + " " + (n + 2) + " " + (n + 3)); } out.close(); } }
constant
483_A. Counterexample
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class B { private void solve() throws IOException { int n = nextInt(); int k = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); int[] f = new int[100000 + 2]; int min = Integer.MAX_VALUE; int cur = 0; int start = 0; int from = -1, to = -1; for (int i = 0; i < n; i++) { f[a[i]]++; if (f[a[i]] == 1) cur++; if (cur == k) { while (f[a[start]] > 1) { f[a[start]]--; start++; } if (i - start + 1 < min) { min = i - start + 1; from = start; to = i; } } } pl(from == -1 ? "-1 -1" : ((1 + from) + " " + (1 + to))); } public static void main(String[] args) { new B().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } void p(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.flush(); writer.print(objects[i]); writer.flush(); } } void pl(Object... objects) { p(objects); writer.flush(); writer.println(); writer.flush(); } int cc; void pf() { writer.printf("Case #%d: ", ++cc); writer.flush(); } }
linear
224_B. Array
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in/*new File("input.txt")*/); int n = sc.nextInt(), t = sc.nextInt(), x, a, kol = 2; ArrayList<Double> al = new ArrayList<Double>(); for(int i=0;i<n;i++) { x = sc.nextInt(); a = sc.nextInt(); al.add(x - a/2.); al.add(x + a/2.); } Collections.sort(al); double d0 = 0; int k = 0, kn = al.size(); for(Double d: al) { if (k == 2) { if (d-d0>t) kol+=2; else if (d-d0==t) kol++; d0 = d; k = 1; } else { k++; d0 = d; } } System.out.print(kol); } }
nlogn
15_A. Cottage Village
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.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author null */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, Input in, PrintWriter out) { try { int kt = in.readInt(); for (int nt = 0; nt < kt; nt++) { int n = in.readInt(); int m = in.readInt(); int[][] a = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[j][i] = in.readInt(); } } Arrays.sort(a, (x, y) -> { int xMax = 0; for (int i = 0; i < x.length; i++) { xMax = Math.max(xMax, x[i]); } int yMax = 0; for (int i = 0; i < y.length; i++) { yMax = Math.max(yMax, y[i]); } return Integer.compare(-xMax, -yMax); }); int ans = 0; int[] s = new int[4]; for (s[0] = 0; s[0] < n; s[0]++) { for (s[1] = 0; s[1] < n; s[1]++) { for (s[2] = 0; s[2] < n; s[2]++) { for (s[3] = 0; s[3] < n; s[3]++) { int cur = 0; for (int i = 0; i < n; i++) { int max = 0; for (int j = 0; j < Math.min(m, n); j++) { max = Math.max(max, a[j][(i + s[j]) % n]); } cur += max; } ans = Math.max(cur, ans); } } } } out.println(ans); } } catch (Exception e) { throw new RuntimeException(e); } } } static class Input { public final BufferedReader reader; private String line = ""; private int pos = 0; public Input(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private boolean isSpace(char ch) { return ch <= 32; } public String readWord() throws IOException { skip(); int start = pos; while (pos < line.length() && !isSpace(line.charAt(pos))) { pos++; } return line.substring(start, pos); } public int readInt() throws IOException { return Integer.parseInt(readWord()); } private void skip() throws IOException { while (true) { if (pos >= line.length()) { line = reader.readLine(); pos = 0; } while (pos < line.length() && isSpace(line.charAt(pos))) { pos++; } if (pos < line.length()) { return; } } } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.IOException; import java.util.Scanner; public class A199 { static int n[][] = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; public static void main(String[] args) throws IOException { new A199().solve(); } public void solve() throws IOException { Scanner scan = new Scanner(System.in); int N = scan.nextInt(); // int f1 = 0; // int f2 = 1; // // while(true){ // int t = f1 + f2; // if(t == N){ // //guaranteed that n is a Fibonacci number // break; // } // f1 = f2; // f2 = t; // } System.out.println("0 0 " + N ); } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.*; import java.util.*; import java.math.BigInteger; public class Main { // main public static void main(String [] args) throws IOException { // makes the reader and writer BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); // read in StringTokenizer st = new StringTokenizer(f.readLine()); BigInteger l = new BigInteger(st.nextToken()); BigInteger r = new BigInteger(st.nextToken()); // write if (r.subtract(l).intValue()<2 || (r.subtract(l).intValue()==2 && r.mod(new BigInteger("2")).intValue()==1)) out.println(-1); else out.println(l.add(l.mod(new BigInteger("2"))).toString()+" "+l.add(l.mod(new BigInteger("2"))).add(new BigInteger("1")).toString()+" "+l.add(l.mod(new BigInteger("2"))).add(new BigInteger("2")).toString()); // cleanup out.close(); System.exit(0); } }
constant
483_A. Counterexample
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 Washoum */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; inputClass in = new inputClass(inputStream); PrintWriter out = new PrintWriter(outputStream); G1PlaylistForPolycarpEasyVersion solver = new G1PlaylistForPolycarpEasyVersion(); solver.solve(1, in, out); out.close(); } static class G1PlaylistForPolycarpEasyVersion { static final int mod = (int) 1e9 + 7; public void solve(int testNumber, inputClass sc, PrintWriter out) { int n = sc.nextInt(); int t = sc.nextInt(); G1PlaylistForPolycarpEasyVersion.Song[] songs = new G1PlaylistForPolycarpEasyVersion.Song[n]; for (int i = 0; i < n; i++) { songs[i] = new G1PlaylistForPolycarpEasyVersion.Song(sc.nextInt(), sc.nextInt()); } long ans = 0; for (int mask = 1; mask < (1 << n); mask++) { int nb = 0; int tot = 0; int type1 = 0; int type2 = 0; int type3 = 0; for (int j = 0; j < n; j++) { if (((1 << j) & mask) > 0) { nb++; tot += songs[j].l; if (songs[j].type == 1) { type1++; } else if (songs[j].type == 2) { type2++; } else { type3++; } } } if (tot == t) { long[][][][][] dp = new long[nb + 1][3][type1 + 1][type2 + 1][type3 + 1]; boolean[][][][][] go = new boolean[nb + 1][3][type1 + 1][type2 + 1][type3 + 1]; if (type1 > 0) { go[1][0][type1 - 1][type2][type3] = true; dp[1][0][type1 - 1][type2][type3] = type1; } if (type2 > 0) { go[1][1][type1][type2 - 1][type3] = true; dp[1][1][type1][type2 - 1][type3] = type2; } if (type3 > 0) { go[1][2][type1][type2][type3 - 1] = true; dp[1][2][type1][type2][type3 - 1] = type3; } for (int i = 0; i < nb; i++) { for (int m = 0; m < 3; m++) { for (int j = 0; j <= type1; j++) { for (int k = 0; k <= type2; k++) { for (int l = 0; l <= type3; l++) { if (go[i][m][j][k][l]) { if (m == 0) { if (k > 0) { dp[i + 1][1][j][k - 1][l] += dp[i][m][j][k][l] * k; dp[i + 1][1][j][k - 1][l] %= mod; go[i + 1][1][j][k - 1][l] = true; } if (l > 0) { dp[i + 1][2][j][k][l - 1] += dp[i][m][j][k][l] * l; dp[i + 1][2][j][k][l - 1] %= mod; go[i + 1][2][j][k][l - 1] = true; } } else if (m == 1) { if (j > 0) { dp[i + 1][0][j - 1][k][l] += dp[i][m][j][k][l] * j; dp[i + 1][0][j - 1][k][l] %= mod; go[i + 1][0][j - 1][k][l] = true; } if (l > 0) { dp[i + 1][2][j][k][l - 1] += dp[i][m][j][k][l] * l; dp[i + 1][2][j][k][l - 1] %= mod; go[i + 1][2][j][k][l - 1] = true; } } else { if (j > 0) { dp[i + 1][0][j - 1][k][l] += dp[i][m][j][k][l] * j; dp[i + 1][0][j - 1][k][l] %= mod; go[i + 1][0][j - 1][k][l] = true; } if (k > 0) { dp[i + 1][1][j][k - 1][l] += dp[i][m][j][k][l] * k; dp[i + 1][1][j][k - 1][l] %= mod; go[i + 1][1][j][k - 1][l] = true; } } } } } } } } long toadd = 0; for (int i = 0; i < 3; i++) { toadd += dp[nb][i][0][0][0]; } ans += toadd; ans %= (int) 1e9 + 7; } } out.println(ans); } static class Song { int l; int type; public Song(int x, int y) { l = x; type = y; } } } static class inputClass { BufferedReader br; StringTokenizer st; public inputClass(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.util.Scanner; public class C { private static final int MOD = (int) 1e9 + 7; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] DP = new int[n][n + 1]; DP[0][0] = 1; for (int i = 0; i < n - 1; i++) { if (in.next().charAt(0) == 'f') { for (int j = 1; j < n; j++) DP[i+1][j] = DP[i][j-1]; } else { for (int j = n - 1; j >= 0; j--) DP[i+1][j] = (DP[i][j] + DP[i+1][j+1]) % MOD; } } int answer = 0; for (int i = 0; i < n; i++) answer = (answer + DP[n-1][i]) % MOD; System.out.println(answer); } }
quadratic
909_C. Python Indentation
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.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class Div1_526C { static int nV; static ArrayList<Integer>[] chldn; static int root; static int[][] anc; static int[] depth; static int[] num; static int[] nLoc; static int[][] tree; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); nV = Integer.parseInt(reader.readLine()); chldn = new ArrayList[nV]; for (int i = 0; i < nV; i++) { chldn[i] = new ArrayList<>(); } anc = new int[nV][21]; depth = new int[nV]; num = new int[nV]; nLoc = new int[nV]; tree = new int[nV * 4][2]; for (int[] a : tree) { a[0] = a[1] = -1; } root = 0; StringTokenizer inputData = new StringTokenizer(reader.readLine()); for (int i = 0; i < nV; i++) { num[i] = Integer.parseInt(inputData.nextToken()); nLoc[num[i]] = i; } inputData = new StringTokenizer(reader.readLine()); for (int i = 1; i < nV; i++) { anc[i][0] = Integer.parseInt(inputData.nextToken()) - 1; chldn[anc[i][0]].add(i); } preprocess(); build(1, 0, nV - 1); int nQ = Integer.parseInt(reader.readLine()); while (nQ-- > 0) { inputData = new StringTokenizer(reader.readLine()); if (inputData.nextToken().equals("1")) { int a = Integer.parseInt(inputData.nextToken()) - 1; int b = Integer.parseInt(inputData.nextToken()) - 1; int temp = num[a]; num[a] = num[b]; num[b] = temp; nLoc[num[a]] = a; nLoc[num[b]] = b; update(1, 0, nV - 1, num[a]); update(1, 0, nV - 1, num[b]); } else { printer.println(query(1, 0, nV - 1, nLoc[0], nLoc[0]) + 1); } } printer.close(); } static void build(int nI, int cL, int cR) { if (cL == cR) { tree[nI][0] = nLoc[cL]; tree[nI][1] = nLoc[cL]; } else { int mid = (cL + cR) >> 1; build(nI * 2, cL, mid); build(nI * 2 + 1, mid + 1, cR); if (tree[nI * 2][0] != -1 && tree[nI * 2 + 1][0] != -1) { merge(tree[nI * 2][0], tree[nI * 2][1], tree[nI * 2 + 1][0], tree[nI * 2 + 1][1]); tree[nI][0] = mResp[0]; tree[nI][1] = mResp[1]; } } } static int query(int nI, int cL, int cR, int e1, int e2) { if (cL == cR) { merge(e1, e2, nLoc[cL], nLoc[cL]); if (mResp[0] != -1) { return cL; } else { return cL - 1; } } int mid = (cL + cR) >> 1; merge(tree[nI * 2][0], tree[nI * 2][1], e1, e2); if (mResp[0] != -1) { return query(nI * 2 + 1, mid + 1, cR, mResp[0], mResp[1]); } return query(nI * 2, cL, mid, e1, e2); } static void update(int nI, int cL, int cR, int uI) { if (cL == cR) { tree[nI][0] = nLoc[cL]; tree[nI][1] = nLoc[cL]; } else { int mid = (cL + cR) >> 1; if (uI <= mid) { update(nI * 2, cL, mid, uI); } else { update(nI * 2 + 1, mid + 1, cR, uI); } merge(tree[nI * 2][0], tree[nI * 2][1], tree[nI * 2 + 1][0], tree[nI * 2 + 1][1]); tree[nI][0] = mResp[0]; tree[nI][1] = mResp[1]; } } static int[] mResp = new int[2]; static void merge1(int... a) { for (int i = 0; i < 3; i++) { if (a[i] == -1) { mResp[0] = mResp[1] = -1; return; } } if (onPath(a[0], a[1], a[2])) { mResp[0] = a[0]; mResp[1] = a[1]; return; } if (onPath(a[0], a[2], a[1])) { mResp[0] = a[0]; mResp[1] = a[2]; return; } if (onPath(a[1], a[2], a[0])) { mResp[0] = a[1]; mResp[1] = a[2]; return; } mResp[0] = mResp[1] = -1; } static void merge(int... a) { merge1(a[0], a[1], a[2]); merge1(mResp[0], mResp[1], a[3]); } static boolean onPath(int a, int b, int c) { if (a == c || b == c) { return true; } if (depth[a] > depth[c]) { a = jump(a, depth[a] - depth[c] - 1); } if (depth[b] > depth[c]) { b = jump(b, depth[b] - depth[c] - 1); } if (a == b) { return false; } if (anc[a][0] == c || anc[b][0] == c) { return true; } return false; } // good for depth of up to 1_048_576 = 2^20 static void preprocess() { anc[root][0] = root; fParent(root); for (int k = 1; k <= 20; k++) { for (int i = 0; i < nV; i++) { anc[i][k] = anc[anc[i][k - 1]][k - 1]; } } } static void fParent(int cV) { for (int aV : chldn[cV]) { anc[aV][0] = cV; depth[aV] = depth[cV] + 1; fParent(aV); } } static int fLCA(int a, int b) { if (depth[a] > depth[b]) { int temp = b; b = a; a = temp; } b = jump(b, depth[b] - depth[a]); if (a == b) { return a; } for (int i = 20; i >= 0; i--) { if (anc[a][i] != anc[b][i]) { a = anc[a][i]; b = anc[b][i]; } } return anc[a][0]; } static int jump(int cV, int d) { for (int i = 0; i <= 20; i++) { if ((d & (1 << i)) != 0) { cV = anc[cV][i]; } } return cV; } static Comparator<Integer> BY_DEPTH = new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return -Integer.compare(depth[o1], depth[o2]); // greatest depth first } }; }
nlogn
1084_F. Max Mex
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class A{ void solve(){ int n=ni(); int P[]=new int[n+1]; for(int i=1;i<=n;i++) P[i]=ni(); a=new int[n+1]; BIT=new long[n+1]; long cnt=0; long p=0; for(int i=n;i>=1;i--){ p+=querry(P[i]); if(p>=M) p%=M; update(n,P[i],1); } int d=0; if(p%2==0) d=1; int m=ni(); while(m-->0){ int l=ni(),r=ni(); long sz=r-l+1; sz=(sz*(sz-1))/2; if(d==1 && sz%2==0) d=1; else if(d==1 && sz%2!=0) d=0; else if(d==0 && sz%2==0) d=0; else if(d==0 && sz%2!=0) d=1; if(d==1) pw.println("even"); else pw.println("odd"); } } int a[]; long BIT[]; void update(int n,int x,int val){ a[x]=val; for(;x<=n;x+=(x&-x)) BIT[x]+=val; } long querry(int x){ long ans=0; for(;x>0;x-=(x&-x)) ans+=BIT[x]; return ans; } static long d, x, y; static void extendedEuclid(long A, long B) { if(B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A%B); long temp = x; x = y; y = temp - (A/B)*y; } } static long modInverse(long A, long M) { extendedEuclid(A,M); return (x%M+M)%M; } long M=(long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().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 void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { var sc = new Scanner(System.in); var pw = new PrintWriter(System.out); int T = Integer.parseInt(sc.next()); for(int t = 0; t < T; t++){ int n = Integer.parseInt(sc.next()); boolean ok = false; if(n%2 == 0){ int a = n/2; int b = (int) Math.sqrt(a); if(b*b == a){ ok = true; } } if(n%4 == 0){ int a = n/4; int b = (int) Math.sqrt(a); if(b*b == a){ ok = true; } } if(ok){ pw.println("YES"); }else{ pw.println("NO"); } } pw.flush(); } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Set; /** * @author Egor Kulikov (egor@egork.net) * Created on 14.03.2010 */ public class TaskA implements Runnable { private InputReader in; private PrintWriter out; public static void main(String[] args) { new Thread(new TaskA()).start(); // new Template().run(); } public TaskA() { // String id = getClass().getName().toLowerCase(); // try { // System.setIn(new FileInputStream(id + ".in")); // System.setOut(new PrintStream(new FileOutputStream(id + ".out"))); // System.setIn(new FileInputStream("input.txt")); // System.setOut(new PrintStream(new FileOutputStream("output.txt"))); // } catch (FileNotFoundException e) { // throw new RuntimeException(); // } in = new InputReader(System.in); out = new PrintWriter(System.out); } public void run() { // int numTests = in.readInt(); // for (int testNumber = 0; testNumber < numTests; testNumber++) { // out.print("Case " + (testNumber + 1) + ": "); // } String s = in.readString(); Set<String> m = new HashSet<String>(); int ans = 0; for (int i = 0; i < s.length(); i++) { for (int j = i + 1; j <= s.length(); j++) { if (m.contains(s.substring(i, j))) ans = Math.max(ans, j - i); else m.add(s.substring(i, j)); } } out.print(ans); out.close(); } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } 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 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 = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { 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 < '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 < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.Scanner; public class B { public static String toB(String str){ String row,col; int i=0; while(i<str.length() && str.charAt(i)<='Z'&&str.charAt(i)>='A')i++; col = str.substring(0,i); row = str.substring(i,str.length()); StringBuffer sb = new StringBuffer(col); col = sb.reverse().toString(); int accum = 0; for(i=0;i<col.length();i++){ int val = getValue(col.charAt(i)); accum+=val*Math.pow(26, i); } return "R"+row+"C"+accum; } public static String toA(String str){ int i = str.indexOf('C'); String row,col,ans=""; row = str.substring(1,i); col = str.substring(i+1,str.length()); int colVal = Integer.parseInt(col),mod; while(colVal>0){ mod = colVal%26; if(mod==0){ ans+='Z'; colVal--; } else{ ans+=getLetter(mod); } colVal/=26; } StringBuffer sb = new StringBuffer(ans); ans = sb.reverse().toString(); return ans+row; } public static int getValue(char c){ return c-'A'+1; } public static char getLetter(int n){ return (char)(n+'A'-1); } public static void main(String[] args)throws Exception{ Scanner in = new Scanner(System.in); int cases = in.nextInt(); for(int i = 0;i<cases;i++){ String str = in.next(); if(str.charAt(0)=='R' && str.charAt(1)>='0'&&str.charAt(1)<='9' && str.indexOf('C')!=-1){ System.out.println(toA(str)); } else System.out.println(toB(str)); } } }
linear
1_B. Spreadsheets
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++) { arr[i]=s.nextInt(); } Arrays.sort(arr); int[] visited=new int[n]; int ans=0; for(int i=0;i<n;i++) { if(visited[i]==0) { ans++; for(int j=i+1;j<n;j++) { if(arr[j]%arr[i]==0&&visited[j]==0) { visited[j]=1; } } } } System.out.println(ans); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; import java.lang.*; import java.math.*; public class USACO { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(reader.readLine()," "); int n= Integer.parseInt(st.nextToken()); int r= Integer.parseInt(st.nextToken()); StringTokenizer st2 = new StringTokenizer(reader.readLine()," "); double[][] coord = new double[n][2]; for (int i=0;i<n;i++) { coord[i][0] = Integer.parseInt(st2.nextToken()); double y=r; for (int j=0;j<i;j++) { if (coord[j][0]<=coord[i][0]+2*r&&coord[j][0]>=coord[i][0]-2*r) { if (coord[j][1]+Math.sqrt(4*r*r-(coord[i][0]-coord[j][0])*(coord[i][0]-coord[j][0]))>y) { y=coord[j][1]+Math.sqrt(4*r*r-(coord[i][0]-coord[j][0])*(coord[i][0]-coord[j][0])); } } } coord[i][1]=y; } for (int i=0;i<n;i++) { System.out.print(coord[i][1]); if (i<n-1) { System.out.print(" "); } else { System.out.print("\n"); } } reader.close(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; public class A { public static void main(String[] args) { Scanner s = new Scanner(new InputStreamReader(System.in)); int n = s.nextInt(); if (n == 1) { System.out.println("NO"); System.exit(0); } int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = s.nextInt(); } Arrays.sort(nums); int x = 1; while (x < n && nums[x] == nums[x - 1]) x++; if (x == n) { System.out.println("NO"); System.exit(0); } else { System.out.println(nums[x]); System.exit(0); } } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author AndrewShmig */ 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) { String n = in.nextLine(); int a = Integer.parseInt(n); int b = Integer.parseInt(n.substring(0, n.length() - 1)); int c = Integer.parseInt(n.substring(0, n.length() - 2) + n.charAt(n.length() - 1)); out.println(Math.max(a, Math.max(b, c))); } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.io.*; import java.util.*; public class A implements Runnable { private MyScanner in; private PrintWriter out; private void solve() { int n = in.nextInt(); int[] a = new int[n]; int all = 0; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); all += a[i]; } Arrays.sort(a); int sum = 0, ans = 0; for (int i = n - 1; i >= 0; --i) { sum += a[i]; ++ans; if (sum > all - sum) { break; } } out.println(ans); } @Override public void run() { in = new MyScanner(); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } public static void main(String[] args) { new A().run(); } static class MyScanner { private BufferedReader br; private StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); return null; } } return st.nextToken(); } public String nextLine() { try { st = null; return br.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public boolean hasNext() { if (st != null && st.hasMoreTokens()) { return true; } try { while (br.ready()) { st = new StringTokenizer(br.readLine()); if (st != null && st.hasMoreTokens()) { return true; } } } catch (IOException e) { e.printStackTrace(); } return false; } } }
nlogn
160_A. Twins
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()); // int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); StringBuilder ans1 = new StringBuilder(); StringBuilder ans2 = new StringBuilder(); for(int i=0; i<2229; i++) ans1.append('5'); ans1.append('6'); for(int i=0; i<2230; i++) ans2.append('4'); out.println(ans1.toString()); out.println(ans2.toString()); out.close(); System.exit(0); } }
constant
1028_B. Unnatural Conditions
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class AnnoyingPresent { //UPSOLVED public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); long n = Long.parseLong(st.nextToken()) , m = Long.parseLong(st.nextToken()); long sum = 0; for(int i=0;i<m;i++){ StringTokenizer st1 = new StringTokenizer(br.readLine()); sum+= n* Long.parseLong(st1.nextToken()); Long a= Long.parseLong(st1.nextToken()); if(a < 0){ if(n % 2 == 0) sum += n*n / 4*a; else{ sum += (n/2) * (n/2+1) * a; } } else sum += (a*(n) * (n-1) / 2); } System.out.println((double)sum/n); } }
linear
1009_C. Annoying Present
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.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rishabhdeep Singh */ 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 MOD = (int) 1e9 + 7; public void solve(int testNumber, InputReader in, OutputWriter out) { long x = in.nextLong(), k = in.nextLong(); long res = Utilities.mul(x, Utilities.power(2, k + 1, MOD), MOD) % MOD - Utilities.power(2, k, MOD) + 1; while (res < 0) res += MOD; out.println(x == 0 ? 0 : res); } } 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 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 boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } static class Utilities { public static long mul(long x, long y, long mod) { return (x % mod) * (y % mod) % mod; } public static long power(long a, long k, long m) { long res = 1; while (k > 0) { if ((k & 1) != 0) { res = mul(res, a, m); } a = mul(a, a, m); k >>= 1; } return res; } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.Scanner; public class main1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a = n / 2; int b = n - a; if (n % 2 == 0) { if (a % 2 == 1) { a++; b--; } System.out.println(a + " " + b); } else { if (a % 2 == 1) { int x = a; a = b; b= x; } if (b % 3 == 0) { } else if (b % 3 == 1) { a-=2; b+=2; } else { a+=2; b-=2; } System.out.println(a + " " + b); } } }
constant
472_A. Design Tutorial: Learn from Math
CODEFORCES
import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = in.nextInt(); double r = in.nextInt(); double[] x = new double[n+1]; double[] y = new double[n+1]; for (int i = 1; i <= n; i++) { x[i] = in.nextInt(); } int[] lastx = new int[1001]; for (int i = 1; i <= n; i++) { double s = x[i] - r, e = x[i] + r; for (int j = (int)Math.max(0, s); j <= (int)Math.min(1000, e); j++) { if (lastx[j] == 0) { y[i] = Math.max(y[i], findY(x[i], x[i], 0 - r, 2 * r)); } else { y[i] = Math.max(y[i], findY(x[lastx[j]], x[i], y[lastx[j]], 2 * r)); } lastx[j] = i; } } for (int i = 1; i <= n; i++) { out.println(y[i]); } out.close(); } public static double findY(double x1, double x2, double y1, double d) { return Math.max(y1 + Math.sqrt(-1 * Math.pow(x1, 2) + 2 * x1 * x2 + Math.pow(d, 2) - Math.pow(x2, 2)), y1 - Math.sqrt(-1 * Math.pow(x1, 2) + 2 * x1 * x2 + Math.pow(d, 2) - Math.pow(x2, 2))); } static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; public class Main{ private static final int MAX_SIZE = 100005; public static void main(String args[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); if(((m + 1) / 60 < a) || ((m + 1) / 60 == a && (m + 1) % 60 <= b)) { out(0, 0); System.exit(0); } for(int i = 2; i <= n; i++) { int x = sc.nextInt(); int y = sc.nextInt(); int bb = b + 2 * m + 2; int aa = a + bb / 60; bb %= 60; if((aa < x) || (aa == x && bb <= y)) { b = b + m + 1; a = a + b / 60; b %= 60; out(a, b); System.exit(0); } a = x; b = y; } b = b + m + 1; a = a + b / 60; b = b % 60; out(a, b); } private static void out(int a, int b) { cout(a); cout(" "); cout(b); } private static void cout(Object a) { System.out.print(a); } }
linear
967_A. Mind the Gap
CODEFORCES
import java.io.*; import java.util.*; public class Main { StreamTokenizer in; PrintWriter out; public static void main(String[] args) throws Exception { new Main().run(); } public void run() throws Exception { in = new StreamTokenizer (new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); } int nextInt() throws Exception { in.nextToken(); return (int) in.nval; } public void solve() throws Exception { int n=nextInt(); long ans=0; for (int i=0;i<n;i+=2) ans+=3; out.println(ans); } }
constant
84_A. Toy Army
CODEFORCES
import java.util.*; import java.io.*; public class EdA { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; public static void main(String[] havish) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); int n = sc.nextInt(); mod = sc.nextLong(); long[] fact = new long[401]; long[] twopowers = new long[401]; fact[0] = 1; twopowers[0] = 1; for(int j = 1;j<=400;j++){ twopowers[j] = twopowers[j-1] * 2L; twopowers[j] %= mod; fact[j] = fact[j-1] * j; fact[j] %= mod; } long[][] choose = new long[401][401]; for(int j = 0;j<=400;j++){ for(int k = 0;k<=j;k++){ choose[j][k] = fact[j]; choose[j][k] *= inv(fact[k]); choose[j][k] %= mod; choose[j][k] *= inv(fact[j-k]); choose[j][k] %= mod; } } long[][] dp = new long[n+1][n+1]; //prefix, # of autos for(int j = 1;j<=n;j++){ dp[j][0] = twopowers[j-1]; } for(int k = 0;k<n;k++){ //number of autos for(int j = 1;j<=n;j++){ //prefix if (k > j) continue; for(int add = 2; j+add <= n; add++){ long prod = dp[j][k] * choose[j-k+add-1][add-1]; prod %= mod; prod *= twopowers[add-2]; dp[j+add][k+1] += prod; dp[j+add][k+1] %= mod; } } } long ans = 0; for(int s = 0;s<=n;s++){ ans+=dp[n][s]; ans %= mod; } out.println(ans); out.close(); } public static long inv(long n){ return power(n, mod-2); } public static void sort(int[] array){ ArrayList<Integer> copy = new ArrayList<>(); for (int i : array) copy.add(i); Collections.sort(copy); for(int i = 0;i<array.length;i++) array[i] = copy.get(i); } static String[] readArrayString(int n){ String[] array = new String[n]; for(int j =0 ;j<n;j++) array[j] = sc.next(); return array; } static int[] readArrayInt(int n){ int[] array = new int[n]; for(int j = 0;j<n;j++) array[j] = sc.nextInt(); return array; } static int[] readArrayInt1(int n){ int[] array = new int[n+1]; for(int j = 1;j<=n;j++){ array[j] = sc.nextInt(); } return array; } static long[] readArrayLong(int n){ long[] array = new long[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextLong(); return array; } static double[] readArrayDouble(int n){ double[] array = new double[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextDouble(); return array; } static int minIndex(int[] array){ int minValue = Integer.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(long[] array){ long minValue = Long.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(double[] array){ double minValue = Double.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static long power(long x, long y){ if (y == 0) return 1; if (y%2 == 1) return (x*power(x, y-1))%mod; return power((x*x)%mod, y/2)%mod; } static void verdict(boolean a){ out.println(a ? "YES" : "NO"); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } //StringJoiner sj = new StringJoiner(" "); //sj.add(strings) //sj.toString() gives string of those stuff w spaces or whatever that sequence is
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class B { static BufferedReader in; static StringTokenizer st; static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = nextInt(); int k = nextInt(); int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = nextInt(); } Set<Integer> set_1 = new HashSet<Integer>(); for (int i = 1; i <= n; i++) { set_1.add(a[i]); if (set_1.size() == k) { Set<Integer> set_2 = new HashSet<Integer>(); for (int j = i; j >= 1; j--) { set_2.add(a[j]); if (set_2.size() == k) { out.print(j + " " + i); out.close(); return; } } } } out.print("-1 -1"); out.close(); } }
linear
224_B. Array
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; import java.util.Locale; public class E16 { static StreamTokenizer in; static PrintWriter out; static int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } static double nextDouble() throws IOException { in.nextToken(); return in.nval; } static String nextString() throws IOException { in.nextToken(); return in.sval; } public static void main(String[] args) throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); n = nextInt(); t = 1 << n; m = new double[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) m[i][j] = nextDouble(); memo = new double[t]; Arrays.fill(memo, Double.POSITIVE_INFINITY); for (int i = 0; i < n; i++) out.print(String.format(Locale.US, "%.6f", solve(1 << i)) + " "); out.println(); out.flush(); } static int n, t; static double[][] m; static double[] memo; static double solve(int mask) { if (memo[mask] != Double.POSITIVE_INFINITY) return memo[mask]; if (mask == t-1) return memo[mask] = 1; int k = Integer.bitCount(mask); k = (k+1)*k/2; double res = 0; for (int i = 0; i < n; i++) if ((mask&(1 << i)) != 0) for (int j = 0; j < n; j++) if ((mask&(1 << j)) == 0) res += m[i][j]*solve(mask|(1 << j)); return memo[mask] = res/k; } }
np
16_E. Fish
CODEFORCES
import java.util.*; import java.io.*; import static java.util.Arrays.*; import static java.lang.Math.*; import java.math.*; public class Main { void run() throws IOException { String s = token(); HashSet <String> h; int n = s.length(); int r = 0; loop: for (int i = 1; i <= n; i++) { h = new HashSet(); for (int j = 0; j < n - i + 1; j++) { String t = s.substring(j, j + i); if (h.contains(t)) { r = i; continue loop; } else { h.add(t); } } } System.out.println(r); } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); //final String FILENAME = "dvd"; //in = new BufferedReader(new FileReader(new File(FILENAME + ".in"))); //out = new PrintWriter(new File(FILENAME + ".out")); in = new BufferedReader(new InputStreamReader(System.in)); //in = new Scanner(System.in); out = new PrintWriter(System.out); st = new StringTokenizer(" "); new Main().run(); out.close(); } static BufferedReader in; //static Scanner in; static PrintWriter out; static StringTokenizer st; String token() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nint() throws IOException { return Integer.parseInt(token()); } long nlong() throws IOException { return Long.parseLong(token()); } double ndouble() throws IOException { return Double.parseDouble(token()); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.DataInputStream; import java.io.InputStream; import java.util.Arrays; import java.util.TreeSet; public class Main{ public static void main(String[] args) throws Exception { Parserdoubt3 s = new Parserdoubt3(System.in); int n = s.nextInt(); long k = s.nextInt(); Long a[] = new Long[n]; TreeSet<Long> tree = new TreeSet<Long>(); for (int i = 0; i < a.length; i++) { a[i] = s.nextLong(); tree.add(a[i]); } Arrays.sort(a); int ans = 0; for (int i = 0; i < a.length; i++) { if(tree.contains(a[i])){ ans++; long next = a[i] * k; if(tree.contains(next)) tree.remove(next); } } System.out.println(ans); } } class Parserdoubt3 { final private int BUFFER_SIZE = 1 << 17; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parserdoubt3(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString() throws Exception { StringBuffer sb = new StringBuffer(""); byte c = read(); while (c <= ' ') c = read(); do { sb.append((char) c); c = read(); } while (c > ' '); return sb.toString(); } public char nextChar() throws Exception { byte c = read(); while (c <= ' ') c = read(); return (char) c; } public int nextInt() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } public long nextLong() throws Exception { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Scanner; public class Loader { private final static Scanner in = new Scanner(System.in); public static void main(String[] args) { int n = in.nextInt(); ArrayList<Integer> l = new ArrayList<>(); for (int i = 0; i < n; i++) { l.add(in.nextInt()); } Collections.sort(l); int k = 0; for (int i = 0; i < l.size(); i++) { if (l.get(i) == 0) continue; for (int j = i + 1; j < l.size(); j++) { if (l.get(j) == 0) continue; if (l.get(j) % l.get(i) == 0) { l.set(j, 0); } } l.set(i, 0); k++; } System.out.println(k); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; import java.io.*; public class Main { static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader fileReader) { br = new BufferedReader(fileReader); } 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(); } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in);PrintWriter pw = new PrintWriter(System.out); int n=sc.nextInt(),d=sc.nextInt();int[] a = new int[n];int ans=2;a[0]=sc.nextInt(); for (int i=1;i<n;i++){ a[i]=sc.nextInt(); if (a[i]-a[i-1]==2*d)ans++; else if (a[i]-a[i-1]>2*d)ans+=2; } System.out.println(ans); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class ProblemA { public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] line = s.readLine().split(" "); int n = Integer.valueOf(line[0]); int ht = Integer.valueOf(line[1]); int[][] house = new int[n][2]; Set<Integer> candidates = new HashSet<Integer>(); for (int i = 0 ; i < n ; i++) { String[] data = s.readLine().split(" "); house[i][0] = Integer.valueOf(data[0]) * 2; house[i][1] = Integer.valueOf(data[1]); candidates.add(house[i][0] - house[i][1] - ht); candidates.add(house[i][0] + house[i][1] + ht); } int ans = 0; for (int p : candidates) { int f = p - ht; int t = p + ht; boolean isok = true; for (int i = 0 ; i < n ; i++) { if (house[i][0] + house[i][1] <= f) { } else if (house[i][0] - house[i][1] >= t) { } else { isok = false; break; } } if (isok) { ans++; } } out.println(ans); out.flush(); } public static void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.util.*; public class ProblemA { InputReader in; PrintWriter out; long power(long a, long b, long mod) { long ret = 1; long mul = a; while (b > 0) { if (b % 2 == 1) { ret = (ret * mul % mod); } mul = (mul * mul) % mod; b = b / 2; } return ret; } void solve() { long n = in.nextLong(); long m = in.nextLong(); long k = in.nextLong(); long mod = 1000000009; long x = m - (n - n / k); if (x <= 0) { out.println(m); } else { long score = 1; score = power(2, x + 1, mod); score = (score + mod - 2) % mod; // out.println(score); long ans = ((score * k) + m - x * k + mod) % mod; out.println(ans); } } ProblemA(){ boolean oj = System.getProperty("ONLINE_JUDGE") != null; try { if (oj) { in = new InputReader(System.in); out = new PrintWriter(System.out); } else { Writer w = new FileWriter("output.txt"); in = new InputReader(new FileReader("input.txt")); out = new PrintWriter(w); } } catch(Exception e) { throw new RuntimeException(e); } solve(); out.close(); } public static void main(String[] args){ new ProblemA(); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public InputReader(FileReader fr) { reader = new BufferedReader(fr); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
logn
338_A. Quiz
CODEFORCES
import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); // 1 = H, 0 = T int n = in.nextInt(); String line = in.next(); int h = 0; for (int i = 0; i < line.length(); i++) { if(line.charAt(i)=='H') h++; } line = line + line; int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int ans = 0; for (int j = i; j < i+h; j++) { if(line.charAt(j)!='H') ans++; } if(min>ans) min = ans; } out.print(min); in.close(); out.close(); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class first { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int n=s.nextInt(); int[] a=new int[n]; for (int i = 0; i < a.length; i++) { a[i]=s.nextInt(); } Arrays.sort(a); int count=0; for (int i = 0; i < a.length; i++) { if(a[i]!=0) { int x=a[i]; count++; for (int j = i; j < a.length; j++) { if(a[j]%x==0) { a[j]=0; } } } } System.out.println(count); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class B_574 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] input = br.readLine().split(" "); int N = Integer.valueOf(input[0]); int K = Integer.valueOf(input[1]); long sum = 0; for(int i = 0; i < N; i++){ if(sum - (N - i) == K){ System.out.println(Integer.valueOf(N-i)); return; } sum += (i+1); } System.out.println("0"); } }
logn
1195_B. Sport Mafia
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 * @author codeKNIGHT */ 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(),i,sum=0; int a[]=new int[n]; for(i=0;i<n;i++) { a[i]=in.nextInt(); sum+=a[i]; } Arrays.sort(a); int s=0,c=0; for(i=n-1;i>=0;i--) { if(s>sum) break; s+=a[i]; sum-=a[i]; c++; } out.println(c); } }
nlogn
160_A. Twins
CODEFORCES
import java.io.IOException; import java.util.Scanner; public class A { public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println((2*n) - (n/2)); } }
constant
84_A. Toy Army
CODEFORCES
import java.io.*; import java.util.*; public class Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); pineapple(); reader.close(); writer.close(); } static void pineapple() throws NumberFormatException, IOException { int n = nextInt(); int a = nextInt(); int b = nextInt(); HashSet<Integer> al = new HashSet<Integer>(); HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); int[] ans = new int[n]; Arrays.fill(ans, -1); HashSet<Integer> used = new HashSet<Integer>(); int[] mas = new int[n]; for (int i = 0; i < n; i++) { int t = nextInt(); al.add(t); mas[i] = t; mp.put(t, i); } for (int st : al) { if (used.contains(st)) continue; { int pr = st; int cc = -1; HashSet<Integer> u2 = new HashSet<Integer>(); u2.add(pr); if (!u2.contains(a - pr) && al.contains(a - pr)) cc = a - pr; if (!u2.contains(a - pr) && al.contains(b - pr)) cc = b - pr; if (cc != -1) { u2.add(cc); boolean bGo = true; while (bGo) { bGo = false; int nxt = -1; if (!u2.contains(a - cc) && al.contains(a - cc)) nxt = a - cc; if (!u2.contains(b - cc) && al.contains(b - cc)) nxt = b - cc; if (nxt != -1) { bGo = true; u2.add(nxt); cc = nxt; pr = cc; } } st = cc; } } LinkedList<Integer> ll = new LinkedList<Integer>(); ll.add(st); while (!ll.isEmpty()) { int curr = ll.pollFirst(); used.add(curr); int next1 = a - curr; if (al.contains(next1)) { if (!used.contains(next1)) { ll.addLast(next1); if (ans[mp.get(curr)] == -1 && ans[mp.get(next1)] == -1) { ans[mp.get(next1)] = 0; ans[mp.get(curr)] = 0; } } } int next2 = b - curr; if (al.contains(next2)) { if (!used.contains(next2)) { ll.addLast(next2); if (ans[mp.get(curr)] == -1 && ans[mp.get(next2)] == -1) { ans[mp.get(next2)] = 1; ans[mp.get(curr)] = 1; } } } } } for (int i = 0; i < n; i++) { if (ans[i] == -1) { if (2 * mas[i] == a) { ans[i] = 0; continue; } if (2 * mas[i] == b) { ans[i] = 1; continue; } writer.println("NO"); return; } } writer.println("YES"); for (int i = 0; i < n; i++) { writer.print(ans[i] + " "); } } }
linear
468_B. Two Sets
CODEFORCES
import java.io.*; import java.util.*; public class CF_35C { public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new FileReader("input.txt")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); StringTokenizer st1 = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st1.nextToken()); int m = Integer.parseInt(st1.nextToken()); boolean[][] visited = new boolean[n][m]; int k = Integer.parseInt(f.readLine()); LinkedList<state1> ll = new LinkedList<state1>(); StringTokenizer st = new StringTokenizer(f.readLine()); for(int i = 0; i < k; i++) { int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); ll.add(new state1(x - 1, y - 1)); visited[x - 1][y - 1] = true; } int lastx = 1; int lasty = 1; while(!ll.isEmpty()) { state1 focus = ll.remove(); lastx = focus.x+1; lasty = focus.y+1; //System.out.println(lastx + " " + lasty); visited[focus.x][focus.y] = true; if(focus.x+1 < n && !visited[focus.x+1][focus.y]) { ll.add(new state1(focus.x+1, focus.y)); visited[focus.x+1][focus.y] = true; } if(focus.x-1 >= 0 && !visited[focus.x-1][focus.y]) { ll.add(new state1(focus.x-1, focus.y)); visited[focus.x-1][focus.y] = true; } if(focus.y+1 < m && !visited[focus.x][focus.y+1]) { ll.add(new state1(focus.x, focus.y+1)); visited[focus.x][focus.y+1] = true; } if(focus.y-1 >= 0 && !visited[focus.x][focus.y-1]) { ll.add(new state1(focus.x, focus.y-1)); visited[focus.x][focus.y-1] = true; } } out.println(lastx + " " + lasty); out.close(); } } class state1 { int x, y; state1(int x, int y) { this.x = x; this.y = y; } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main2 { static long mod = 998244353; static FastScanner scanner; static StringBuilder result = new StringBuilder(); public static void main(String[] args) { scanner = new FastScanner(); int t = scanner.nextInt(); for (int i = 0; i < t; i++) { solve(); result.append("\n"); } System.out.print(result.toString()); } static void solve() { int n = scanner.nextInt(); int m = scanner.nextInt(); PriorityQueue<WithIdx2> queue = new PriorityQueue<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { queue.add(new WithIdx2(scanner.nextInt(), i, j)); } } if (n <= 3) { int res = 0; for (int k = 0; k < n; k++) { res += queue.poll().val; } result.append(res); } else { List<WithIdx2> a = new ArrayList<>(); for (int i = 0; i < 9; i++) { if (!queue.isEmpty()) a.add(queue.poll()); } int[] offsets = new int[m]; best = -1; Arrays.fill(offsets, -100); put(0, a, offsets, new int[4]); result.append(best); } } static int best = -1; static void put(int current, List<WithIdx2> vals, int[] offsets, int[] rows) { if (current == vals.size()) { for (int i = 0; i < rows.length; i++) if (rows[i] == 0) return; int sum = IntStream.of(rows).sum(); best = Math.max(best, sum); return; } for (int row = 0; row < 4; row++) { if (rows[row] == 0) { WithIdx2 c = vals.get(current); if (offsets[c.y] == -100) { rows[row] = c.val; offsets[c.y] = row - c.x; put(current + 1, vals, offsets, rows); rows[row] = 0; offsets[c.y] = -100; } else { int bind = c.x + offsets[c.y]; if (bind < 0) bind += 4; if (bind >= 4) bind -= 4; if (row == bind) { rows[row] = c.val; put(current + 1, vals, offsets, rows); rows[row] = 0; } } } } put(current + 1, vals, offsets, rows); } static class WithIdx2 implements Comparable<WithIdx2>{ int x, y, val; public WithIdx2(int val, int x, int y) { this.val = val; this.x = x; this.y = y; } @Override public int compareTo(WithIdx2 o) { return -Integer.compare(val, o.val); } } static class WithIdx implements Comparable<WithIdx>{ int val, idx; public WithIdx(int val, int idx) { this.val = val; this.idx = idx; } @Override public int compareTo(WithIdx o) { return Integer.compare(val, o.val); } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] nextLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } String[] nextStringArray(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = nextToken(); return res; } } static class PrefixSums { long[] sums; public PrefixSums(long[] sums) { this.sums = sums; } public long sum(int fromInclusive, int toExclusive) { if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value"); return sums[toExclusive] - sums[fromInclusive]; } public static PrefixSums of(int[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } public static PrefixSums of(long[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } } static class ADUtils { static void sort(int[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } static void reverse(int[] arr) { int last = arr.length / 2; for (int i = 0; i < last; i++) { int tmp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = tmp; } } static void sort(long[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap long a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } } static class MathUtils { static long[] FIRST_PRIMES = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89 , 97 , 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051}; static long[] primes(int to) { long[] all = new long[to + 1]; long[] primes = new long[to + 1]; all[1] = 1; int primesLength = 0; for (int i = 2; i <= to; i ++) { if (all[i] == 0) { primes[primesLength++] = i; all[i] = i; } for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j]; j++) { all[(int) (i * primes[j])] = primes[j]; } } return Arrays.copyOf(primes, primesLength); } static long modpow(long b, long e, long m) { long result = 1; while (e > 0) { if ((e & 1) == 1) { /* multiply in this bit's contribution while using modulus to keep * result small */ result = (result * b) % m; } b = (b * b) % m; e >>= 1; } return result; } static long submod(long x, long y, long m) { return (x - y + m) % m; } } } /* 1 4 2 5 7 6 2 2 5 3 6 */
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if ((n%4==0)||(n%7==0)||(n%44==0)||(n%47==0)||(n%74==0)||(n%77==0)||(n%444==0)||(n%447==0)||(n%474==0)||(n%477==0)||(n%744==0)||(n%747==0)||(n%774==0)||(n%777==0)) { System.out.println("YES"); } else { System.out.println("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.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 */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = in.nextInt(); } long ninv = 0; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (ar[i] > ar[j]) ninv++; } } int m = in.nextInt(); for (int i = 0; i < m; i++) { int l = in.nextInt(); int r = in.nextInt(); int s = (r - l) * (r - l + 1) / 2; ninv += s; if (ninv % 2 == 0) out.println("even"); else out.println("odd"); } } } static class InputReader { StringTokenizer st; BufferedReader br; public InputReader(InputStream is) { BufferedReader br = new BufferedReader(new InputStreamReader(is)); this.br = br; } public String next() { if (st == null || !st.hasMoreTokens()) { String nextLine = null; try { nextLine = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (nextLine == null) return null; st = new StringTokenizer(nextLine); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.util.InputMismatchException; import java.util.Stack; public class D527A2 { public static void main(String[] args) { FastScanner in = new FastScanner(System.in); int N = in.nextInt(); Stack<Integer> stack = new Stack<>(); for(int i = 0; i < N; i++) { int num = in.nextInt() % 2; if(stack.size() >= 1 && stack.lastElement() == num) stack.pop(); else stack.add(num); } System.out.println(stack.size() <= 1 ? "YES" : "NO"); } /** * Source: Matt Fontaine */ static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int chars; public FastScanner(InputStream stream) { this.stream = stream; } int read() { if (chars == -1) throw new InputMismatchException(); if (curChar >= chars) { curChar = 0; try { chars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (chars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } } /* 5 2 1 1 2 5 outputCopy YES inputCopy 3 4 5 3 outputCopy YES inputCopy 2 10 10 outputCopy YES inputCopy 3 1 2 3 outputCopy NO 5 2 3 2 2 3 YES */
linear
1092_D1. Great Vova Wall (Version 1)
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(), d = s.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++){ arr[i] = s.nextInt(); } Arrays.sort(arr); int count = 0; for(int i = 1; i < n; i++){ int dist = arr[i] - arr[i - 1]; if(dist > 2 * d){ count += 2; }else if(dist == 2 * d){ count++; } } System.out.println(count + 2); } }
linear
1004_A. Sonya and Hotels
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int V = in.nextInt(); int E = in.nextInt(); boolean [][] G = new boolean [V][V]; for (int i = 0; i < E; i++) { int u = in.nextInt()-1; int v = in.nextInt()-1; G[u][v] = true; G[v][u] = true; } int pset = 1 << V; long [][] dp = new long [pset][V]; long cycles = 0; for (int set = 1; set < pset; set++) { int bit = Integer.bitCount(set); int src = first(set); if (bit == 1) { dp[set][src] = 1; } else if(bit > 1) { for (int i = 0; i < V; i++) { if(i == src) continue; // Check if i is in set if ((set & (1 << i)) != 0) { int S_1 = set ^ (1 << i); for (int v = 0; v < V; v++) { if (G[v][i] == true) { dp[set][i] += dp[S_1][v]; } } } //Count Cycles: if (bit >= 3 && G[src][i]) { cycles += dp[set][i]; } } } } System.out.println(cycles/2); } public static int first(int n) { int cnt = 0; while ((n & 1) != 1) { cnt++; n >>= 1; } return cnt; } }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; public class B { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1, in, out); out.close(); } static class Task { int n = 0; int query(int p, InputReader in) { p %= n; if (p <= 0) p += n; System.out.println("? " + p); System.out.flush(); int x = in.nextInt(); return x; } public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); if (n % 4 != 0) { out.println("! -1"); return; } int p = query(0, in); int q = query(n / 2, in); int l = 0; int r = n / 2; if (p == q) { out.println("! " + (n / 2)); return; } while (l + 1 < r) { int mid = (l + r) / 2; int u = query(mid, in); int v = query(mid + n / 2, in); if (u == v) { out.println("! " + (mid + n / 2)); return; } if ((p < q) == (u < v)) { l = mid; } else { r = mid; } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
logn
1019_B. The hat
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class Ds { static long lim; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] line = in.readLine().split("\\s+"); long n = Long.parseLong(line[0]); lim = Long.parseLong(line[1]); long pos = -1; for(int i=61; i>=0; i--) { long shift = (long) Math.pow(2, i); if(pos + shift - sumOfDigits(pos + shift) < lim) { pos += shift; } } pos++; if(pos <= n && pos- sumOfDigits(pos) >= lim) { System.out.println(n - pos + 1); } else { System.out.println(0); } } private static long sumOfDigits(long d) { long sum = 0; long num = d; while(num != 0) { sum += (num%10); num /= 10; } return sum; } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Locale; import java.util.StringTokenizer; public class Solution implements Runnable { public static void main(String[] args) { (new Thread(new Solution())).start(); } BufferedReader in; PrintWriter out; StringTokenizer st; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } class Dom implements Comparable<Dom>{ int x, a; public int compareTo(Dom o) { return x - o.x; } } void solve() throws Exception { int n = nextInt(); int t = nextInt() * 2; Dom[] a = new Dom[n]; for (int i = 0; i < n; i++) { a[i] = new Dom(); a[i].x = nextInt() * 2; a[i].a = nextInt(); } Arrays.sort(a); int ans = 2; for (int i = 0; i < n - 1; i++) { if (t < a[i + 1].x - a[i + 1].a - a[i].x - a[i].a) ans += 2; if (t == a[i + 1].x - a[i + 1].a - a[i].x - a[i].a) ans += 1; } out.print(ans); } public void run() { try { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); } catch (Exception e) { e.printStackTrace(); } out.flush(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.*; import java.util.*; public class TestClass { public static class FastWriter { private static final int BUF_SIZE = 1 << 13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter() { out = null; } public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) innerflush(); return this; } public FastWriter write(char c) { return write((byte) c); } public FastWriter write(char[] s) { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if (x == Integer.MIN_VALUE) { return write((long) x); } if (ptr + 12 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if (x == Long.MIN_VALUE) { return write("" + x); } if (ptr + 21 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if (x < 0) { write('-'); x = -x; } x += Math.pow(10, -precision) / 2; // if(x < 0){ x = 0; } write((long) x).write("."); x -= (long) x; for (int i = 0; i < precision; i++) { x *= 10; write((char) ('0' + (int) x)); x -= (int) x; } return this; } public FastWriter writeln(char c) { return write(c).writeln(); } public FastWriter writeln(int x) { return write(x).writeln(); } public FastWriter writeln(long x) { return write(x).writeln(); } public FastWriter writeln(double x, int precision) { return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for (int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for (long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte) '\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for (char[] line : map) write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c) { return writeln(c); } public FastWriter println(int x) { return writeln(x); } public FastWriter println(long x) { return writeln(x); } public FastWriter println(double x, int precision) { return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final int readInt() throws IOException { return (int) readLong(); } public final long readLong() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); if (c == -1) throw new IOException(); } boolean negative = false; if (c == '-') { negative = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return negative ? -res : res; } public final int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } public final long[] readLongArray(int size) throws IOException { long[] array = new long[size]; for (int i = 0; i < size; i++) { array[i] = readLong(); } return array; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static long mulmod(long a, long b, long mod) { long res = 0; // Initialize result a = a % mod; while (b > 0) { // If b is odd, add 'a' to result if (b % 2 == 1) { res = (res + a) % mod; } // Multiply 'a' with 2 a = (a * 2) % mod; // Divide b by 2 b /= 2; } // Return result return res % mod; } static long pow(long a, long b, long MOD) { long x = 1, y = a; while (b > 0) { if (b % 2 == 1) { x = (x * y); if (x > MOD) x %= MOD; } y = (y * y); if (y > MOD) y %= MOD; b /= 2; } return x; } static long[] f = new long[200001]; static long InverseEuler(long n, long MOD) { return pow(n, MOD - 2, MOD); } static long C(int n, int r, long MOD) { return (f[n] * ((InverseEuler(f[r], MOD) * InverseEuler(f[n - r], MOD)) % MOD)) % MOD; } static int[] h = {0, 0, -1, 1}; static int[] v = {1, -1, 0, 0}; public static class Pair { public int a; public int b; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return a == pair.a && b == pair.b; } @Override public int hashCode() { return Objects.hash(a, b); } public Pair(int a, int b) { this.a = a; this.b = b; } } static class Pair2 { public long cost; int node; public Pair2(long cos, int node) { this.cost = cos; this.node = node; } } static long compute_hash(String s) { int p = 31; int m = 1000000007; long hash_value = 0; long p_pow = 1; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m; p_pow = (p_pow * p) % m; } return hash_value; } public static class SegmentTree { long[][] tree; int n; public SegmentTree(int[] nodes) { tree = new long[nodes.length * 4][2]; n = nodes.length; build(0, n - 1, 0, nodes); } private void build(int l, int r, int pos, int[] nodes) { if (l == r) { tree[pos][0] = nodes[l]; tree[pos][1] = l; return; } int mid = (l + r) / 2; build(l, mid, 2 * pos + 1, nodes); build(mid + 1, r, 2 * pos + 2, nodes); if (tree[2 * pos + 1][0] > tree[2 * pos + 2][0]) { tree[pos][1] = tree[2 * pos + 1][1]; } else { tree[pos][1] = tree[2 * pos + 2][1]; } tree[pos][0] = Math.max(tree[2 * pos + 1][0], tree[2 * pos + 2][0]); } // public void update(int pos, int val) { // updateUtil(0, n - 1, 0, pos, val); // } public long[] get(int l, int r) { return getUtil(0, n - 1, 0, l, r); } private long[] getUtil(int l, int r, int pos, int ql, int qr) { if (ql > r || qr < l) { return new long[]{-1, -1}; } if (l >= ql && r <= qr) { return tree[pos]; } int mid = (l + r) / 2; long[] left = getUtil(l, mid, 2 * pos + 1, ql, qr); long[] right = getUtil(mid + 1, r, 2 * pos + 2, ql, qr); long choice = right[1]; if (left[0] > right[0]) choice = left[1]; return new long[]{Math.max(left[0], right[0]), choice}; } // private void updateUtil(int l, int r, int pos, int i, int val) { // if (i < l || i > r) { // return; // } // if (l == r) { // tree[pos] = val; // return; // } // int mid = (l + r) / 2; // updateUtil(l, mid, 2 * pos + 1, i, val); // updateUtil(mid + 1, r, 2 * pos + 2, i, val); // tree[pos] = tree[2 * pos + 1] + tree[2 * pos + 2]; // } } static int counter = 0; static int[] rIn; static int[] rOut; static int[] lIn; static int[] lOut; private static int[] flatten; private static int[] lFlatten; static long answer = 0; static int VISITED = 1; static int VISITING = 2; static int[] DIRX = new int[]{0, 0, 1, -1}; static int[] DIRY = new int[]{1, -1, 0, 0}; public static class Pair22 { int num, pos; public Pair22(int x, int y) { this.num = x; this.pos = y; } } public static long sumofdig(long n) { long sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } public static void main(String[] args) throws Exception { //https://i...content-available-to-author-only...e.com/ebRGa6 InputReader in = new InputReader(System.in); FastWriter out = new FastWriter(System.out); // // f[0] = 1; // f[1] = 1; // for (int i = 2; i < 200001; ++i) { // f[i] = f[i-1] * i; // f[i] %= 1000000007; // } int t = in.readInt(); while (t-- > 0) { int n = in.readInt(); Stack<Integer> s = new Stack<>(); System.out.println("1"); int i1 = in.readInt(); assert i1 == 1; s.add(1); for (int i = 1; i < n; ++i) { int next = in.readInt(); if (next == 1) { } else { while ((s.peek() + 1) != next) { s.pop(); } s.pop(); } s.add(next); StringBuilder ans = new StringBuilder(); for (int c: s) { ans.append(c).append("."); } out.println(ans.substring(0, ans.length() - 1)); out.flush(); } } } private static void solvedd(int[] arr, int left, int right, int[] ans, int depth) { if (left > right) return; int maxInd = left; for (int i = left; i <= right; ++i) { if (arr[i] > arr[maxInd]) { maxInd = i; } } ans[maxInd] = depth; solvedd(arr, left, maxInd - 1, ans, depth + 1); solvedd(arr, maxInd + 1, right, ans, depth + 1); } private static void solved(List<List<Integer>> g, int node, int[][] dp, int last, int[] a) { int donttake = 0; int take = 0; for (int i = 0; i < g.get(node).size(); ++i) { int ntb = g.get(node).get(i); if (ntb != last) { solved(g, ntb, dp, node, a); donttake += Math.max(dp[ntb][0], dp[ntb][1]); take += dp[ntb][1]; } } dp[node][0] = a[node] + take; dp[node][1] = donttake; } private static boolean solve(int n, List<Integer> nums, int cur, int pos, Boolean[][] dp) { if (cur > n) return false; if (cur == n) return true; if (pos >= nums.size()) return false; if (dp[cur][pos] != null) { return dp[cur][pos]; } boolean without = solve(n, nums, cur, pos + 1, dp); boolean with = false; int ogcur = cur; for (int i = 1; i < 12; ++i) { with |= solve(n, nums, cur + nums.get(pos), pos + 1, dp); cur += nums.get(pos); } return dp[ogcur][pos] = with | without; } // private static Pair22 dfss(List<LinkedHashSet<Integer>> g, int node, HashSet<Integer> vis, int[] dis, int[] dis2) { // if (vis.contains(node)) return new Pair22(dis[node], dis2[node], -1); // vis.add(node); // int min = dis[node]; // for (Integer ntb : g.get(node)) { // if (dis[ntb] > dis[node]) // dfss(g, ntb, vis, dis, dis2); // if (dis[ntb] <= dis[node]) { // min = Math.min(min, dis[ntb]); // } else { // min = Math.min(min, dis2[ntb]); // } // } // // if (dis) // dis2[node] = min; // return new Pair22(dis[node], min, -1); // } private static int dfs(HashMap<Pair, TreeSet<Pair>> grid, int x, int y, int ti, HashSet<Pair> vis, int r, int startX, int startY) { // System.out.println(x + " " + y); int taken = ti - Math.abs(startX - x) - Math.abs(startY - y); if (taken < 0) return 0; if (x < 0 || y < 0 || x > r || y > r) return 0; if (vis.contains(new Pair(x, y))) return 0; int max = 0; if (grid.containsKey(new Pair(x, y))) { TreeSet<Pair> times = grid.get(new Pair(x, y)); for (Pair t : times) { if (t.a <= taken) { max = Math.max(t.b, max); } else break; } } vis.add(new Pair(x, y)); max = Math.max(dfs(grid, x + 1, y, ti, vis, r, startX, startY), max); max = Math.max(dfs(grid, x, y + 1, ti, vis, r, startX, startY), max); max = Math.max(dfs(grid, x - 1, y, ti, vis, r, startX, startY), max); max = Math.max(dfs(grid, x, y - 1, ti, vis, r, startX, startY), max); return max; } private static int solver(int[] nums, int pos, int[] dp) { if (pos >= nums.length) return 0; if (dp[pos] != Integer.MAX_VALUE) return dp[pos]; int min = solver(nums, pos + 2, dp) + nums[pos]; min = Math.min(solver(nums, pos + 3, dp) + nums[pos], min); if (pos + 1 < nums.length) min = Math.min(min, nums[pos] + nums[pos + 1] + solver(nums, pos + 3, dp)); if (pos + 1 < nums.length) min = Math.min(min, nums[pos] + nums[pos + 1] + solver(nums, pos + 4, dp)); // System.out.println(pos + " " + min); return dp[pos] = min; } static int countFreq(String pattern, String text) { int m = pattern.length(); int n = text.length(); int res = 0; for (int i = 0; i <= n - m; i++) { int j; for (j = 0; j < m; j++) { if (text.charAt(i + j) != pattern.charAt(j)) { break; } } if (j == m) { res++; j = 0; } } return res; } private static void dfsR(List<List<Integer>> g, int node, int[] v) { rIn[node] = counter; flatten[counter++] = v[node]; for (int i = 0; i < g.get(node).size(); ++i) { dfsR(g, g.get(node).get(i), v); } rOut[node] = counter; flatten[counter++] = v[node] * -1; } private static void dfsL(List<List<Integer>> g, int node, int[] v) { lIn[node] = counter; lFlatten[counter++] = v[node]; for (int i = 0; i < g.get(node).size(); ++i) { dfsL(g, g.get(node).get(i), v); } lOut[node] = counter; lFlatten[counter++] = v[node] * -1; TreeMap<String, Integer> map = new TreeMap<>(); } private static void preprocess(int pos, int[][] pre, List<List<Integer>> tree, int[] traverse, int depth, int last, int[] tin, int[] tout) { tin[pos] = counter++; traverse[depth] = pos; for (int i = 0; depth - (1 << i) >= 0; ++i) { pre[pos][i] = traverse[depth - (1 << i)]; } for (int i = 0; i < tree.get(pos).size(); ++i) { if (tree.get(pos).get(i) != last) preprocess(tree.get(pos).get(i), pre, tree, traverse, depth + 1, pos, tin, tout); } tout[pos] = counter++; } static long gcd(long a, long b) { while (b != 0) { long t = a; a = b; b = t % b; } return a; } static boolean submit = true; static void debug(String s) { if (!submit) System.out.println(s); } static void debug(int s) { LinkedHashSet<Integer> exist = new LinkedHashSet<>(); /* 4 2 3 _ 2 4 3 _ */ } /** 0 1 2 3 4 5 6 7 8 9 10 1 1 1 * Your ExamRoom object will be instantiated and called as such: * ExamRoom obj = new ExamRoom(N); * int param_1 = obj.seat(); * obj.leave(p); */ }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.io.*; import java.util.*; public class Hack{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) arr[i]=sc.nextInt(); Arrays.sort(arr); Set<Integer> set = new TreeSet<Integer>(); for(int i=0;i<n;i++){ boolean flag=false; for(Integer x:set){ if(arr[i]%x==0){ flag=true; break; } } if(!flag) set.add(arr[i]); } System.out.println(set.size()); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; public class CF16E { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); double[][] aa = new double[n][n]; for (int i = 0; i < n; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); for (int j = 0; j < n; j++) aa[i][j] = Double.parseDouble(st.nextToken()); } double[][] pp = new double[1 << n][n]; for (int k = 0; k < n; k++) pp[1 << k][k] = 1; for (int b = 1; b < 1 << n; b++) { int c = 0; for (int i = 0; i < n; i++) { if ((b & 1 << i) == 0) continue; c++; for (int j = i + 1; j < n; j++) { if ((b & 1 << j) == 0) continue; for (int k = 0; k < n; k++) { if ((b & 1 << k) == 0) continue; pp[b][k] += aa[i][j] * pp[b ^ 1 << j][k]; pp[b][k] += aa[j][i] * pp[b ^ 1 << i][k]; } } } if (c > 1) { double p = (double) c * (c - 1) / 2; for (int k = 0; k < n; k++) pp[b][k] /= p; } } StringBuilder sb = new StringBuilder(); int b = (1 << n) - 1; for (int k = 0; k < n; k++) sb.append(pp[b][k]).append(k == n - 1 ? '\n' : ' '); System.out.print(sb); } }
np
16_E. Fish
CODEFORCES
import java.io.*; import java.util.*; public class Codeforces455Div2C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] sp = br.readLine().split(" "); int n = Integer.parseInt(sp[0]); char[] list = new char[n]; for (int i = 0; i < n; i++) { sp = br.readLine().split(" "); list[i] = sp[0].charAt(0); } int[] list2 = new int[n]; int counter = 0; for (int i = 0; i < n; i++) { if (list[i] == 's') { counter++; } else { list2[counter]++; } } int[][] dp = new int[counter][n-counter+1]; int[][] dpsum = new int[counter][n-counter+1]; int[] count = new int[counter]; count[0] = list2[0]; for (int i = 1; i < counter; i++) { count[i] = count[i-1] + list2[i]; } for (int i = 0; i <= count[0]; i++) { dp[0][i] = 1; dpsum[0][i] = i+1; } for (int i = 1; i < counter; i++) { for (int j = 0; j <= count[i]; j++) { dp[i][j] = dpsum[i-1][Math.min(j, count[i-1])]; } dpsum[i][0] = dp[i][0]; for (int j = 1; j <= count[i]; j++) { dpsum[i][j] = (dpsum[i][j-1]+dp[i][j])%1000000007; } } System.out.println(dp[counter-1][n-counter]); } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.util.*; import java.awt.image.BandedSampleModel; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.Scanner; public class D{ static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } public static void main(String args[]) { Scanner sc=new Scanner(System.in); //int cases = sc.nextInt(); //for(int i=0;i<cases;i++) { int n = sc.nextInt(); int m=sc.nextInt(); int steps=sc.nextInt(); long arr[][][] = new long[n][m][5]; for(int j=0;j<n;j++) { for(int k=0;k<m-1;k++) { long num=sc.nextLong(); arr[j][k][1]=num; arr[j][k+1][3]=num; } } for(int j=0;j<n-1;j++) { for(int k=0;k<m;k++) { long num=sc.nextLong(); arr[j][k][2]=num; arr[j+1][k][4]=num; } } long temp[][]=new long[n][m]; long ans[][]=new long[n][m]; for(int i=0;i<steps/2;i++) { for(int j=0;j<n;j++) { for(int k=0;k<m;k++) { long min=Long.MAX_VALUE; if(k>0) { long f=arr[j][k][3]+ans[j][k-1]; min=Math.min(min,f); } if(k<m-1) { long f=arr[j][k][1]+ans[j][k+1]; min=Math.min(min,f); } if(j>0) { long f=arr[j][k][4]+ans[j-1][k]; min=Math.min(min,f); } if(j<n-1) { long f=arr[j][k][2]+ans[j+1][k]; min=Math.min(min,f); } temp[j][k]=min; } } for(int j=0;j<n;j++) { for(int k=0;k<m;k++) { ans[j][k]=temp[j][k]; } } } StringBuilder p=new StringBuilder(); for(int j=0;j<n;j++) { for(int k=0;k<m;k++) { if(steps%2!=0) { p.append(-1+" "); } else { p.append(2*ans[j][k]+" ");} } p.append("\n"); } System.out.println(p); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); if ((n % 4 == 0) || (n % 7 == 0) || (n % 44 == 0) || (n % 47 == 0) || (n % 74 == 0) || (n % 77 == 0) || (n % 444 == 0) || (n % 447 == 0) || (n % 474 == 0) || (n % 477 == 0) || (n % 744 == 0) || (n % 747 == 0) || (n % 774 == 0) || (n % 777 == 0)) { System.out.println("YES"); return; } System.out.println("NO"); } }
constant
122_A. Lucky Division
CODEFORCES
import java.util.Scanner; public class BDigitSequence { public static void main(String[] args) { Scanner scan = new Scanner(System.in); long k = scan.nextLong(); long digits = 1; long counter = 9L; while(k > counter * digits) { k -= counter * digits; counter *= 10; digits++; } long num = (long)(Math.ceil((double)k/digits)); String s = String.valueOf((long)Math.pow(10,digits-1) - 1 + num ); System.out.println(s.charAt((int)((k+digits-1)%digits))); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); long n = in.nextLong(); long k = in.nextLong(); long disc = (long)(Math.sqrt(9 - 4 * (-2 * n - 2 * k))); long x = (-3 + disc) / 2; System.out.println(n - x); } }
logn
1195_B. Sport Mafia
CODEFORCES
// Working program using Reader Class import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class Main1 { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader s=new Reader(); int n = s.nextInt(), i, j, ans=0; int[] a = new int[101]; for(i=0;i<n;i++){ a[s.nextInt()]++; } for(i=1;i<=100;i++){ if(a[i]>0){ ans++; for(j=i;j<=100;j++){ if(j%i==0){ a[j]=0; } } } } System.out.println(ans); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author ocelopilli */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { long LL = in.nextLong(); long RR = in.nextLong(); long L = LL; long R = RR; long ans = 0L; long X = Long.highestOneBit( R ); while ( X > 0L && (L & X) == (R & X) ) X >>= 1; while ( X > 0L ) { long a = L & X; long b = R & X; if ( (a ^ b) == X ) ans |= X; else { if ( b == 0L ) { if ( (R | X) <= RR ) { R |= X; ans |= X; } else if ( (L | X) <= RR ) { L |= X; ans |= X; } } else { if ( (L ^ X) >= LL ) { L ^= X; ans |= X; } else if ( (R ^ X) >= LL ) { R ^= X; ans |= X; } } } X >>= 1; } out.println( ans ); } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st==null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.io.*; import java.util.*; import org.omg.PortableServer.ForwardRequestHelper; public class A{ private BufferedReader in; private StringTokenizer st; void solve() throws IOException{ int n = nextInt(); int i = 0; int[]nums = new int[n]; int numeven = 0; int numodd = 0; while(n-->0){ nums[i] = nextInt(); if(nums[i]%2==0) numeven++; else numodd++; i++; } for (int j = 0; j < nums.length; j++) { if(numeven==1&&nums[j]%2==0){ System.out.println(j+1); break; } if(numodd==1&&nums[j]%2!=0){ System.out.println(j+1); break; } } } A() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); eat(""); solve(); } 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 A(); } int gcd(int a,int b){ if(b>a) return gcd(b,a); if(b==0) return a; return gcd(b,a%b); } }
linear
25_A. IQ test
CODEFORCES
import java.io.*; import java.util.*; public class CF1185G2 { static final int MD = 1000000007; static int[][] solve1(int[] aa, int t, int n) { int[][] da = new int[t + 1][n + 1]; da[0][0] = 1; for (int i = 0; i < n; i++) { int a = aa[i]; for (int s = t - 1; s >= 0; s--) for (int m = 0; m < n; m++) { int x = da[s][m]; if (x != 0) { int s_ = s + a; if (s_ <= t) da[s_][m + 1] = (da[s_][m + 1] + x) % MD; } } } return da; } static int[][][] solve2(int[] aa, int[] bb, int t, int na, int nb) { int[][] da = solve1(aa, t, na); int[][][] dab = new int[t + 1][na + 1][nb + 1]; for (int s = 0; s <= t; s++) for (int ma = 0; ma <= na; ma++) dab[s][ma][0] = da[s][ma]; for (int i = 0; i < nb; i++) { int b = bb[i]; for (int s = t - 1; s >= 0; s--) for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb < nb; mb++) { int x = dab[s][ma][mb]; if (x != 0) { int s_ = s + b; if (s_ <= t) dab[s_][ma][mb + 1] = (dab[s_][ma][mb + 1] + x) % MD; } } } return dab; } static long power(int a, int k) { if (k == 0) return 1; long p = power(a, k / 2); p = p * p % MD; if (k % 2 == 1) p = p * a % MD; return p; } static int[] ff, gg; static int ch(int n, int k) { return (int) ((long) ff[n] * gg[n - k] % MD * gg[k] % MD); } static int[][][] init(int n, int na, int nb, int nc) { ff = new int[n + 1]; gg = new int[n + 1]; for (int i = 0, f = 1; i <= n; i++) { ff[i] = f; gg[i] = (int) power(f, MD - 2); f = (int) ((long) f * (i + 1) % MD); } int[][][] dp = new int[na + 1][nb + 1][nc + 1]; for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb <= nb; mb++) for (int mc = 0; mc <= nc; mc++) { int x = (int) ((long) ff[ma + mb + mc] * gg[ma] % MD * gg[mb] % MD * gg[mc] % MD); for (int ma_ = ma == 0 ? 0 : 1; ma_ <= ma; ma_++) { int cha = ma == 0 ? 1 : ch(ma - 1, ma_ - 1); for (int mb_ = mb == 0 ? 0 : 1; mb_ <= mb; mb_++) { int chb = mb == 0 ? 1 : ch(mb - 1, mb_ - 1); for (int mc_ = mc == 0 ? 0 : 1; mc_ <= mc; mc_++) { int chc = mc == 0 ? 1 : ch(mc - 1, mc_ - 1); int y = dp[ma_][mb_][mc_]; if (y == 0) continue; x = (int) ((x - (long) y * cha % MD * chb % MD * chc) % MD); } } } if (x < 0) x += MD; dp[ma][mb][mc] = x; } for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb <= nb; mb++) for (int mc = 0; mc <= nc; mc++) dp[ma][mb][mc] = (int) ((long) dp[ma][mb][mc] * ff[ma] % MD * ff[mb] % MD * ff[mc] % MD); return dp; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int t = Integer.parseInt(st.nextToken()); int[] aa = new int[n]; int[] bb = new int[n]; int[] cc = new int[n]; int na = 0, nb = 0, nc = 0; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int g = Integer.parseInt(st.nextToken()); if (g == 1) aa[na++] = a; else if (g == 2) bb[nb++] = a; else cc[nc++] = a; } int[][][] dp = init(n, na, nb, nc); int[][][] dab = solve2(aa, bb, t, na, nb); int[][] dc = solve1(cc, t, nc); int ans = 0; for (int tab = 0; tab <= t; tab++) { int tc = t - tab; for (int ma = 0; ma <= na; ma++) for (int mb = 0; mb <= nb; mb++) { int xab = dab[tab][ma][mb]; if (xab == 0) continue; for (int mc = 0; mc <= nc; mc++) { int xc = dc[tc][mc]; if (xc == 0) continue; ans = (int) ((ans + (long) xab * xc % MD * dp[ma][mb][mc]) % MD); } } } System.out.println(ans); } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class B { public static void main(String[] args) throws IOException { // Scanner scan = new Scanner(System.in); BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); // int t = scan.nextInt(); int t= Integer.parseInt(br.readLine()); while (t-->0) { String[] s1= br.readLine().split(" "); int n= Integer.parseInt(s1[0]); // Integer[] a= new Integer[n]; // String[] s2= br.readLine().split(" "); // long sum=0; // for (int i=0;i<n;i++){ // a[i]= Integer.parseInt(s2[i]); // sum+= Math.abs(a[i]); // } int x= 1; boolean ans=true; while (n%2==0){ x*=2; n/=2; } if (x==1) ans= false; int z= (int)Math.sqrt(n); if (z*z!=n) ans= false; if (ans) System.out.println("YES"); else System.out.println("NO"); } } }
linear
1515_B. Phoenix and Puzzle
CODEFORCES
import java.io.*; import java.util.*; public class Main { // static Scanner in; static PrintWriter out; static BufferedReader in; public static void main(String[] args) throws Exception { // in = new Scanner(System.in); out = new PrintWriter(System.out); in = new BufferedReader(new InputStreamReader(System.in)); int n = new Integer(in.readLine()); for (int i = 0; i < n; i++) { String s = in.readLine(); int x = 0; while (s.charAt(x) - 'A' >= 0 && s.charAt(x) - 'Z' <= 0) x++; int y = s.length() - 1; while (s.charAt(y) - '0' >= 0 && s.charAt(y) - '9' <= 0) y--; if (x > y) { int k = 1; int a = 1; for (int j = 1; j < x; j++) { k *= 26; a += k; } for (int j = 0; j < x; j++) { a += k*(s.charAt(j) - 'A'); k /= 26; } int b = Integer.parseInt(s.substring(x)); out.println("R" + b + "C" + a); } else { while (s.charAt(x) - '0' >= 0 && s.charAt(x) - '9' <= 0) x++; int b = Integer.parseInt(s.substring(1, x)); int a = Integer.parseInt(s.substring(x + 1)); int num = 0; int k = 1; while (a >= k) { a -= k; k *= 26; } k /= 26; while (k > 0) { out.print((char)('A' + (a/k))); a %= k; k /= 26; } out.println(b); } } out.close(); } }
linear
1_B. Spreadsheets
CODEFORCES
/* Codeforces Template */ import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { static long initTime; static final Random rnd = new Random(7777L); static boolean writeLog = false; public static void main(String[] args) throws IOException { initTime = System.currentTimeMillis(); try { writeLog = "true".equals(System.getProperty("LOCAL_RUN_7777")); } catch (SecurityException e) {} new Thread(null, new Runnable() { public void run() { try { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) {} long prevTime = System.currentTimeMillis(); new Main().run(); log("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); log("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); in.close(); } /*************************************************************** * Solution **************************************************************/ void solve() throws IOException { int n = nextInt(); long k = nextLong(); int[] a = nextIntArray(n); Set<Long> bad = new TreeSet<Long>(); sort(a); int ans = 0; for (int x : a) { if (!bad.contains((long) x)) { bad.add(x * k); ans++; } } out.println(ans); } /*************************************************************** * Input **************************************************************/ BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int[] nextIntArray(int size) throws IOException { int[] ret = new int [size]; for (int i = 0; i < size; i++) ret[i] = nextInt(); return ret; } long[] nextLongArray(int size) throws IOException { long[] ret = new long [size]; for (int i = 0; i < size; i++) ret[i] = nextLong(); return ret; } double[] nextDoubleArray(int size) throws IOException { double[] ret = new double [size]; for (int i = 0; i < size; i++) ret[i] = nextDouble(); return ret; } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } /*************************************************************** * Output **************************************************************/ void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { if (array == null || array.length == 0) return; boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings("rawtypes") void printCollection(Collection collection) { if (collection == null || collection.isEmpty()) return; boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } /*************************************************************** * Utility **************************************************************/ static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } static void checkMemory() { System.err.println(memoryStatus()); } static long prevTimeStamp = Long.MIN_VALUE; static void updateTimer() { prevTimeStamp = System.currentTimeMillis(); } static long elapsedTime() { return (System.currentTimeMillis() - prevTimeStamp); } static void checkTimer() { System.err.println(elapsedTime() + " ms"); } static void chk(boolean f) { if (!f) throw new RuntimeException("Assert failed"); } static void chk(boolean f, String format, Object ... args) { if (!f) throw new RuntimeException(String.format(format, args)); } static void log(String format, Object ... args) { if (writeLog) System.err.println(String.format(Locale.US, format, args)); } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { long mod = (long) 1e9 + 7; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); char ar[] = new char[n]; for (int i = 0; i < n; i++) { ar[i] = in.readString().charAt(0); } long dp[][] = new long[n + 1][n + 1]; for (int i = 0; i < n; i++) { dp[n - 1][i] = 1; } long prev = n; for (int i = n - 2; i >= 0; i--) { if (ar[i] == 'f') { if (ar[i + 1] == 's') { for (int j = n - 2; j >= 0; j--) { dp[i][j] = dp[i + 1][j + 1]; } } else { for (int j = n - 2; j >= 0; j--) { dp[i][j] = dp[i + 1][j + 1]; } } } else { for (int j = n - 1; j >= 0; j--) { if (prev < 0) { prev += mod; } dp[i][j] = prev; prev = prev - dp[i + 1][j]; } } prev = 0; for (int j = 0; j < n; j++) { prev += dp[i][j]; prev = prev % mod; } } out.println(dp[0][0] % mod); } } 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------ 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 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) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.File; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Scanner; public class Main { public String[][] a; public void run () throws Exception { Scanner in = new Scanner(new File("input.txt")); PrintWriter pw = new PrintWriter(new File("output.txt")); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int[] xx = new int[k]; int[] yy = new int[k]; for(int i=0;i<k;i++){ xx[i] = in.nextInt(); yy[i]= in.nextInt(); } int x=0,y=0,r; r=-1; for(int i=0;i<n;i++) for(int j=0;j<m;j++){ int rr = 1000000; for(int q=0;q<k;q++) rr = Math.min(rr, Math.abs(xx[q]-1-i)+Math.abs(yy[q]-1-j)); if(rr>r){ r=rr; x=i; y=j; } } pw.print((x+1)+" "+(y+1)); pw.close(); } public static void main(String[] args) throws Exception { new Main ().run(); } }
cubic
35_C. Fire Again
CODEFORCES
/** * Created with IntelliJ IDEA. * User: yuantian * Date: 3/24/13 * Time: 2:18 AM * Copyright (c) 2013 All Right Reserved, http://github.com/tyuan73 */ import java.util.*; public class Pipeline { public static void main(String[] args) { Scanner in = new Scanner(System.in); long n = in.nextLong(); long k = in.nextLong(); if (n == 1) { System.out.println(0); return; } if (k >= n) { System.out.println(1); return; } long total = (k + 2) * (k - 1) / 2 - (k - 2); if (total < n) { System.out.println(-1); return; } int i = 2, j = (int) k; while (i <= j) { int m = (i + j) / 2; total = (k + m) * (k - m + 1) / 2 - (k - m); if (total == n) { System.out.println(k - m + 1); return; } if (total < n) j = m - 1; else i = m + 1; } System.out.println(k-i+2); } }
logn
287_B. Pipeline
CODEFORCES
// by agus.mw import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) throws Exception { new Main().doWork(); } void doWork() throws Exception{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); int ncase = Integer.valueOf(reader.readLine()); double[][] p = new double[ncase][]; for(int icase=0;icase<ncase;icase++){ p[icase] = toDoubleArray(reader.readLine()); } double[] prob = new double[1<<ncase]; prob[0] = 1; for(int x=0;x<(1<<ncase);x++){ double cp = prob[x]; int count = 0; for(int i=0;i<ncase;i++){ if((x&(1<<i))!=0) continue; count ++; } if(count == 1) continue; double np = cp*2.0/(count)/(count-1); for(int i=0;i<ncase;i++){ if((x&(1<<i))!=0) continue; for(int j=i+1;j<ncase;j++){ if((x&(1<<j))!=0) continue; prob[x^(1<<j)] += np*p[i][j]; prob[x^(1<<i)] += np*p[j][i]; } } } String out = ""; for(int i=0;i<ncase;i++){ if(i>0) out += " "; int index = ((1<<ncase)-1)^(1<<i); out += String.format("%.6f",prob[index]); } out += "\r\n"; writer.write(out,0,out.length()); writer.flush(); writer.close(); reader.close(); } String process(){ return "1"; } double[] toDoubleArray(String line){ String[] p = line.split("[ ]+"); double[] out = new double[p.length]; for(int i=0;i<p.length;i++) out[i] = Double.valueOf(p[i]); return out; } }
np
16_E. Fish
CODEFORCES
import java.util.*; import java.io.*; public class E { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out, false); int t = scanner.nextInt(); while(t-->0) { int n = scanner.nextInt(); int m = scanner.nextInt(); Col[] cols = new Col[m]; int[][] mat = new int[m][n]; for(int i = 0; i < n; i++) { for(int j =0; j < m; j++) { mat[j][i] = scanner.nextInt(); } } for(int i = 0; i < m; i++) { cols[i] = new Col(mat[i]); } Arrays.sort(cols); int maxMask = 1 << n; int[] dp = new int[maxMask]; Arrays.fill(dp, -1); dp[0] = 0; int sz = Math.min(n, m); int[][] ss = new int[sz][maxMask]; //2^n * n^3 for(int i = 0; i < sz; i++) { int[] curArr = cols[i].arr.clone(); for(int j = 0; j < n; j++) { for(int mask = 0; mask < maxMask; mask++) { int cur = 0; for(int k = 0; k < n; k++) if ((( 1 << k) & mask) > 0) cur += curArr[k]; ss[i][mask] = Math.max(ss[i][mask], cur); } curArr = shift(curArr); } } for(int i = 0; i < Math.min(n, m); i++) { for(int mask = maxMask-1; mask>=0; mask--) { for(int smask = mask; smask >= 0; smask = (smask-1)&mask) { if (dp[smask] == -1) continue; dp[mask] = Math.max(dp[mask], dp[smask] + ss[i][mask ^ smask]); if (smask == 0) break; } } } out.println(dp[maxMask-1]); } out.flush(); } static int[] shift (int[] a) { int[] b = new int[a.length]; b[0] = a[a.length-1]; for(int i = 0; i < a.length-1; i++) { b[i+1] = a[i]; } return b; } static class Col implements Comparable<Col> { int[] arr; int[] sorted; public Col(int[] a) { arr = a; sorted= arr.clone(); Arrays.sort(sorted); } public int compareTo(Col col) { return -sorted[sorted.length-1] + col.sorted[sorted.length-1]; } } 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
1209_E2. Rotate Columns (hard version)
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { public static void main(String[] args) throws IOException { try { if (new File("input.txt").exists()) { System.setIn(new FileInputStream("input.txt")); } } catch (SecurityException e) { } new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int N = nextInt(); int T = nextInt(); Pair[] p = new Pair [N]; for (int i = 0; i < N; i++) p[i] = new Pair(nextInt(), nextInt()); sort(p); int ans = 2; for (int i = 1; i < N; i++) { int dif = (2 * p[i].x - p[i].a) - (2 * p[i - 1].x + p[i - 1].a); if (dif == 2 * T) ans++; else if (dif > 2 * T) ans += 2; } out.println(ans); out.close(); } class Pair implements Comparable<Pair> { int x, a; public Pair(int xx, int aa) { x = xx; a = aa; } @Override public int compareTo(Pair p) { return x < p.x ? -1 : 1; } } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
nlogn
15_A. Cottage Village
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)); List<Integer> fibs = new ArrayList<Integer>(); int fib0 = 0; int fib1 = 1; int fibN = fib0+fib1; fibs.add(fib0); fibs.add(fib1); while(fibN < 1000000000){ fibs.add(fibN); fib0 = fib1; fib1 = fibN; fibN = fib0+fib1; } int n = Integer.parseInt(br.readLine()); if(n == 0){System.out.println(0+" "+0+" "+0);} else{ if(n == 1){System.out.println(0+" "+0+" "+1);} else{ if(n == 2){System.out.println(0+" "+1+" "+1);} else{ int i = fibs.indexOf(n); System.out.println(fibs.get(i-4)+" "+fibs.get(i-3)+" "+fibs.get(i-1)); }} } } }
constant
199_A. Hexadecimal's theorem
CODEFORCES
import java.io.*; import java.util.*; public class Main{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int x,y; boolean graph[][]=new boolean[n][n]; for(int i=0;i<m;i++){ x=sc.nextInt()-1; y=sc.nextInt()-1; graph[x][y]=graph[y][x]=true; } long dp[][]=new long[1<<n][n]; long res=0; for(int i=0;i<n;i++){ dp[1<<i][i]=1; } for(int mask=1;mask<(1<<n);mask++){ int first=-1; for(int f=0;f<n;f++){ if((mask&(1<<f))!=0){ first=f; break; } } for(int i=0;i<n;i++){ if((mask&(1<<i))!=0&&i!=first){ for(int j=0;j<n;j++){ if(graph[j][i]&&((mask&1<<j)!=0)){ dp[mask][i]+=dp[mask^1<<i][j]; } } } if(Integer.bitCount(mask)>2&&graph[first][i]){ res+=dp[mask][i]; } } } System.out.println(res/2); } }
np
11_D. A Simple Task
CODEFORCES
import java.io.IOException; /** * Created by ww on 13.02.2016. */ public class rgb { public static void main(String[] args) throws IOException { System.out.print(25); return ; } }
constant
630_A. Again Twenty Five!
CODEFORCES
import java.util.*; import java.io.*; import java.math.BigInteger; public class Problem { static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; static int[] rt; static int[] size; static void initialize(int n){ rt = new int[n + 1]; size = new int[n + 1]; for(int i = 0; i < rt.length; i++){ rt[i] = i; size[i] = 1; } } static int root(int x){ while(rt[x] != x){ rt[x] = rt[rt[x]]; x = rt[x]; } return x; } static long union(int x,int y){ int root_x = root(x); int root_y = root(y); if(root_x == root_y) return 0; long val = size[root_x] *1l* size[root_y]; if(size[root_x]<size[root_y]){ rt[root_x] = rt[root_y]; size[root_y] += size[root_x]; } else{ rt[root_y] = rt[root_x]; size[root_x] += size[root_y]; } return val; } static void solve() { in = new InputReader(System.in); out = new PrintWriter(System.out); int t = 1; while(t-- > 0){ int n = in.nextInt(); int[] arr = in.nextIntArray(n); ArrayList<Pair> list = new ArrayList<>(); for(int i = 1; i < n; i++){ int u = in.nextInt() - 1; int v = in.nextInt() - 1; list.add(new Pair(u, v, Math.max(arr[u],arr[v]))); } list.sort((p1,p2) -> Integer.compare(p1.i, p2.i)); initialize(n); long s1 = 0; for(int i = 0; i < list.size(); i++){ s1 += union(list.get(i).x, list.get(i).y) * list.get(i).i; } for(int i = 0; i < list.size(); i++){ Pair p = list.get(i); p.i = Math.min(arr[p.x],arr[p.y]); } list.sort((p1,p2) -> -Integer.compare(p1.i, p2.i)); initialize(n); long s2 = 0; for(int i = 0; i < list.size(); i++){ s2 += union(list.get(i).x, list.get(i).y) * list.get(i).i; } out.println(s1 - s2); } out.close(); } public static void main(String[] args) { new Thread(null ,new Runnable(){ public void run(){ try{ solve(); } catch(Exception e){ e.printStackTrace(); } } },"1",1<<26).start(); } 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) { if(this.x != o.x) return -Integer.compare(this.x, o.y); return -Integer.compare(this.y,o.y); //return 0; } 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 long add(long a,long b){ long x=(a+b); while(x>=mod) x-=mod; return x; } static long sub(long a,long b){ long x=(a-b); while(x<0) x+=mod; return x; } static long mul(long a,long b){ long x=(a*b); while(x>=mod) x-=mod; return x; } 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 n; } 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); } } }
nlogn
915_F. Imbalance Value of a Tree
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class Main { static final long MOD = 998244353; //static final long MOD = 1000000007; static boolean[] visited; public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); int N = sc.nextInt(); int[] nums = new int[N]; for (int i = 0; i < N; i++) { nums[i] = sc.nextInt(); } Arrays.sort(nums); boolean[] hit = new boolean[N]; int colors = 0; int index = 0; while (index < N) { if (hit[index] == false) { colors++; int div = nums[index]; for (int i = index; i < N; i++) { if (nums[i] % div == 0) { hit[i] = true; } } } index++; } System.out.println(colors); } public static int[][] sort(int[][] array) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i< array.length; i++) { int randomPosition = rgen.nextInt(array.length); int[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } Arrays.sort(array, new Comparator<int[]>() { @Override public int compare(int[] arr1, int[] arr2) { //Ascending order if (arr1[0] != arr2[0]) return arr1[0]-arr2[0]; else return arr2[1]-arr1[1]; } }); return array; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } class Node { public HashSet<Node> children; public int n; public Node(int n) { this.n = n; children = new HashSet<Node>(); } public void addChild(Node node) { children.add(node); } public void removeChild(Node node) { children.remove(node); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return n; } @Override public boolean equals(Object obj) { if (! (obj instanceof Node)) { return false; } else { Node node = (Node) obj; return (n == node.n); } } public String toString() { return (this.n+1)+""; } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.ArrayList; import java.util.Scanner; public class PaintTheNumber { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); ArrayList<Integer> l=new ArrayList<Integer>(); for(int i=0; i<n; i++) { l.add(sc.nextInt()); } boolean c=false; for(int i=0; i<l.size(); i++) { if(l.get(i)==-1) continue; for(int j=0; j<l.size(); j++) { if(i==j || l.get(j)==-1) continue; else { if(l.get(j)%l.get(i)==0) { l.set(j, -1); } } } } int nbr=0; for(int i=0; i<l.size(); i++) if(l.get(i)!=-1) nbr++; System.out.println(nbr); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; import java.io.*; public class C599 { static ArrayList<Integer> [] adj; static long [] a; static int [] type; static Map<Long, Integer> map; static int [] vis; static HashSet<Integer> cy; static boolean [] good; static int [] dp; static HashSet<Integer> [] nodes; public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int k = sc.nextInt(); int cur = 0; a = new long[75007]; long sum = 0; type = new int[75007]; map = new HashMap<>(); long [] typeSum = new long[k]; for (int i = 0; i < k; i++) { int n = sc.nextInt(); long temp = sum; for (int j = 0; j < n; j++) { cur++; a[cur] = sc.nextLong(); type[cur] = i; map.put(a[cur], cur); sum += a[cur]; } typeSum[i] = sum - temp; } boolean notDiv = sum % k != 0; long need = sum / k; int n = cur; adj = new ArrayList[n + 1]; for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>(); for (int i = 1; i <= n; i++) { long delta = need - typeSum[type[i]]; long find = a[i] + delta; if (map.containsKey(find)) { if (type[map.get(find)] != type[i] || delta == 0) adj[i].add(map.get(find)); } } vis = new int[n + 1]; good = new boolean[1 << k]; good[0] = true; nodes = new HashSet[1 << k]; for (int i = 1; i <= n; i++) { if (vis[i] == 0) { cy = new HashSet<>(); boolean b = dfs(i); int mask = 0; for (Integer node: cy) { mask |= (1 << type[node]); } if (mask != 0) nodes[mask] = cy; good[mask] = true; } } dp = new int[1 << k]; Arrays.fill(dp, -1); int possible = solve((1 << k) - 1); if (possible == 1 && !notDiv) { ArrayList<Integer> masks = dfs2((1 << k) - 1); long [] num = new long[k]; int [] ret = new int[k]; for (Integer mask: masks) { for (Integer node: nodes[mask]) { num[type[node]] = a[node]; ret[type[adj[node].get(0)]] = type[node] + 1; } } boolean good = true; Set<Integer> soFar = new HashSet<>(); for (int i = 0; i < ret.length; i++) { if (soFar.contains(ret[i])) good = false; soFar.add(ret[i]); } if (!good) { out.println("No"); out.close(); return; } out.println("Yes"); for (int i = 0; i < k; i++) { out.println(num[i] + " " + ret[i]); } } else { out.println("No"); } out.close(); } static int solve(int mask) { if (dp[mask] != -1) return dp[mask]; if (good[mask]) return dp[mask] = 1; int ret = 0; for (int i = (mask - 1) & mask; i > 0; i = (i - 1) & mask) { ret = solve(i) & solve(mask ^ i); if (ret == 1) break; } return dp[mask] = ret; } static ArrayList<Integer> dfs2(int mask) { ArrayList<Integer> ret = new ArrayList<>(); if (good[mask]) { ret.add(mask); return ret; } for (int i = (mask - 1) & mask; i > 0; i = (i - 1) & mask) { if (dp[i] == 1 && dp[mask ^ i] == 1) { ArrayList<Integer> one = dfs2(i); ArrayList<Integer> two = dfs2(mask ^ i); ret.addAll(one); ret.addAll(two); break; } } return ret; } static boolean dfs(int cur) { vis[cur] = 1; boolean ret = false; for (Integer next: adj[cur]) { if (vis[next] == 0) { boolean cycle = dfs(next); if (cycle) { if (!cy.contains(cur)) { cy.add(cur); ret = true; break; } } } else if (vis[next] == 1) { cy.add(next); cy.add(cur); if (next != cur) ret = true; break; } } vis[cur] = 2; return ret; } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
np
1242_C. Sum Balance
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { long mod = (long) (1e9 + 7); void solve() throws Throwable { long x = readLong(), k = readLong(); if (x == 0) { System.out.println(0); return; } long r = solveFast(x, k); //long r2 = solveSlow(x, k) % mod; System.out.println(r); //System.out.println(r2); } private long solveSlow(long x, long k) { List<Long> a = new ArrayList<>(); a.add(x); for (int i = 0; i < k; i++) { dodouble(a); a = eat(a); } dodouble(a); long sum = 0; for (Long v : a) { sum = (sum + v) % mod; } return sum * rev(a.size(), mod) % mod; } private List<Long> eat(List<Long> a) { List<Long> r = new ArrayList<>(); for (Long v : a) { r.add(v); r.add((v - 1 + mod) % mod); } return r; } private void dodouble(List<Long> a) { for (int i = 0; i < a.size(); i++) { a.set(i, a.get(i) * 2 % mod); } } private long solveFast(long x, long k) { long n = binpow(2, k, mod); long ma = (binpow(2, k + 1, mod) * (x % mod)) % mod; long mi = (ma - n * 2 + 2 + mod * 100) % mod; return ((ma + mi) * rev(2, mod)) % mod; } private long rev(long a, long mod) { return binpow(a, mod - 2, mod); } //------------------------------------------------- final boolean ONLINE_JUDGE = !new File("input.txt").exists(); BufferedReader in; PrintWriter out; StringTokenizer tok; public void run() { Runnable run = () -> { try { long startTime = System.currentTimeMillis(); Locale.setDefault(Locale.US); if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } tok = new StringTokenizer(""); solve(); in.close(); out.close(); long endTime = System.currentTimeMillis(); long totalMemory = Runtime.getRuntime().totalMemory(); long freeMemory = Runtime.getRuntime().freeMemory(); System.err.println(); System.err.println("Time = " + (endTime - startTime) + " ms"); //System.err.println("Memory = " + ((totalMemory - freeMemory) / 1024) + " KB"); } catch (Throwable e) { e.printStackTrace(System.err); System.exit(-1); } }; new Thread(null, run, "run", 256 * 1024 * 1024).start(); min(0, 0); } String readString() { while (!tok.hasMoreTokens()) { String line; try { line = in.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) return null; tok = new StringTokenizer(line); } return tok.nextToken(); } int readInt() { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } void debug(Object... o) { if (!ONLINE_JUDGE) { System.err.println(Arrays.deepToString(o)); } } /*long binpow(long a, long n) { long r = 1; while (n > 0) { if ((n & 1) > 0) { r *= a; } a *= a; n /= 2; } return r; }/**/ long binpow(long a, long n, long mod) { long r = 1; while (n > 0) { if ((n & 1) > 0) { r = (r * a) % mod; } a = (a * a) % mod; n /= 2; } return r; }/**/ static long gcd(long x, long y) { return y == 0 ? x : gcd(y, x % y); } private long[] readLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = readLong(); } return a; } public static void main(String[] args) { new Main().run(); } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner s = new Scanner(System.in); long l = s.nextLong(); long r = s.nextLong(); s.close(); if (r-l<2 || (r-l==2 && l%2==1)) { System.out.print("-1"); return; } long beg = l%2==0 ? l : l+1; if (beg+2>r) System.out.print("-1"); else System.out.print(beg+" "+(beg+1)+" "+(beg+2)); } }
constant
483_A. Counterexample
CODEFORCES
import java.util.*; import static java.lang.Math.*; public final class FollowTrafficRules { private static double[] acce(double i, double a, double v) { double[] r = new double[2]; r[0] = (v - i)/a; r[1] = 1d/2d * a * pow(r[0], 2) + i * r[0]; return r; } private static double solve(double i, double a, double l) { double e = sqrt(pow(i, 2) + 2d * a * l); e = a > 0 ? e : -1d * e; return (e - i)/a; } private static double time(double i, double a, double v, double l) { double[] r = acce(i, a, v); if (r[1] >= l) return solve(i, a, l); return r[0] + (l - r[1])/v; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); double a = sc.nextDouble(); double v = sc.nextDouble(); double l = sc.nextDouble(); double d = sc.nextDouble(); double w = sc.nextDouble(); double t = 0d; double[] r = acce(0, a, w); if (v <= w || r[1] >= d) t = time(0, a, v, l); else { t += r[0]; t += 2d * time(w, a, v, (d - r[1])/2d); t += time(w, a, v, l - d); } System.out.println(t); } }
constant
5_D. Follow Traffic Rules
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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int r = in.nextInt(); int[] xs = new int[n]; for (int i = 0; i < n; i++) xs[i] = in.nextInt(); double[] ys = new double[n]; for (int i = 0; i < n; i++) { int x = xs[i]; double y = r; for (int j = 0; j < i; j++) { y = Math.max(y, calc(xs[j], ys[j], x, r)); } ys[i] = y; } for (int i = 0; i < n; i++) { out.printf("%.10f ", ys[i]); } out.println(); } private double calc(int x, double y, int x1, int r) { int dx = Math.abs(x - x1); if (dx > 2 * r) return 0; double dy = Math.sqrt(4 * r * r - dx * dx); return y + dy; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in), 32768); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } public boolean hasNext() { while (st == null || !st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; st = new StringTokenizer(s); } return true; } public String next() { hasNext(); return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class P255D { @SuppressWarnings("unchecked") public void run() throws Exception { long n = nextLong(); long x = nextLong(); long y = nextLong(); long c = nextLong(); if ((n == 1) || (c == 1)) { println(0); return; } x = Math.min(x, n - x + 1); y = Math.min(y, n - y + 1); long t = 0; long s = 1; while (s < c) { t++; s += (t * 4) + ((t >= x + y) ? (t - x - y + 1) : 0) - ((t >= x) ? (t - x) * 2 + 1 : 0) - ((t >= y) ? (t - y) * 2 + 1 : 0) + ((t >= x + n - y + 1) ? (t - x - n + y) : 0) + ((t >= n - x + 1 + y) ? (t - n + x - y) : 0) - ((t >= n - x + 1) ? (t - n + x - 1) * 2 + 1 : 0) - ((t >= n - y + 1) ? (t - n + y - 1) * 2 + 1 : 0); } println(t); } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P255D().run(); br.close(); pw.close(); } static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(""); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } }
logn
256_B. Mr. Bender and Square
CODEFORCES