src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.io.*; import java.util.*; import java.math.*; public class Main2 { public static void main(String[] args) throws Exception { new Main2().run(); } public void solve() throws Exception { n = nextInt(); int a[]= new int[n], pos = 1; for(int i=0; i<n; i++) a[i] = nextInt(); Arrays.sort(a); if(n == 1){ out.println("NO"); return; } boolean has = false; for(; pos<n; pos++){ if(a[pos] != a[0]){ has = true; break; } } if(!has){ out.println("NO"); } else{ out.println(a[pos]); } } public int n, m; public void run() throws Exception { inter = new StreamTokenizer(new BufferedReader(new InputStreamReader( System.in))); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); } public BufferedReader in; public StreamTokenizer inter; public PrintWriter out; public int nextInt() throws Exception { inter.nextToken(); return (int) inter.nval; } public String nextLine() throws Exception{ return in.readLine(); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nipuna Samarasekara */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { ///////////////////////////////////////////////////////////// long n,x,y,c; public void solve(int testNumber, FastScanner in, FastPrinter out) { n=in.nextLong(); x=in.nextLong(); y=in.nextLong(); c=in.nextLong(); long td=-1,tup=2*(n-1); while(Math.abs(td-tup)>1){ long mid=(td+tup)/2; if(chk(mid))tup=mid; else td=mid; } out.println(tup); } private boolean chk(long t) { long ct=-3; long d=x,w=y; if(w>d){ long tt=w; w=d;d=tt; } if(t>=d+w-2) ct+=d*w; else if(t<w&&t<d) { // long k=w; ct+=(t+1)*(t+2)/2; } else if(t>=w&&t<d) { // long k=w; ct+=w*(w+1)/2; long k=t-(w-1); ct+=k*w; } else if(t>=w&&t>=d) { // long k=w; ct+=w*d; long k=w-2-(t-d); ct-=k*(k+1)/2; } //// w=x;d=n+1-y; if(w>d){ long tt=w; w=d;d=tt; } if(t>=d+w-2) ct+=d*w; else if(t<w&&t<d) { // long k=w; ct+=(t+1)*(t+2)/2; } else if(t>=w&&t<d) { // long k=w; ct+=w*(w+1)/2; long k=t-(w-1); ct+=k*w; } else if(t>=w&&t>=d) { // long k=w; ct+=w*d; long k=w-2-(t-d); ct-=k*(k+1)/2; } w=n+1-x;d=y; if(w>d){ long tt=w; w=d;d=tt; } if(t>=d+w-2) ct+=d*w; else if(t<w&&t<d) { // long k=w; ct+=(t+1)*(t+2)/2; } else if(t>=w&&t<d) { // long k=w; ct+=w*(w+1)/2; long k=t-(w-1); ct+=k*w; } else if(t>=w&&t>=d) { // long k=w; ct+=w*d; long k=w-2-(t-d); ct-=k*(k+1)/2; } w=n+1-x;d=n+1-y; if(w>d){ long tt=w; w=d;d=tt; } if(t>=d+w-2) ct+=d*w; else if(t<w&&t<d) { // long k=w; ct+=(t+1)*(t+2)/2; } else if(t>=w&&t<d) { // long k=w; ct+=w*(w+1)/2; long k=t-(w-1); ct+=k*w; } else if(t>=w&&t>=d) { // long k=w; ct+=w*d; long k=w-2-(t-d); ct-=k*(k+1)/2; } ct-=Math.min(t,x-1); ct-=Math.min(t,y-1); ct-=Math.min(t,n-x); ct-=Math.min(t,n-y); // System.out.println(t+" "+ct); if(ct>=c)return true; else return false; } } class FastScanner extends BufferedReader { public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); // if (isEOF && ret < 0) { // throw new InputMismatchException(); // } // isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } public String next() { StringBuilder sb = new StringBuilder(); int c = read(); while (isWhiteSpace(c)) { c = read(); } if (c < 0) { return null; } while (c >= 0 && !isWhiteSpace(c)) { sb.appendCodePoint(c); c = read(); } return sb.toString(); } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public long nextLong() { return Long.parseLong(next()); } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } }
logn
256_B. Mr. Bender and Square
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 max = -1, maxp = -1; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); if (a[i] > max) { max = a[i]; maxp = i; } } if (max == 1) { for (int i = 0; i < n - 1; ++i) { out.print(1 + " "); } out.println(2); return; } a[maxp] = 1; Arrays.sort(a); for (int i = 0; i < n; ++i) { out.print(a[i] + " "); } out.println(); } @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(); } } private String nextToken() { 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 { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } public String next() { return nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
nlogn
135_A. Replacement
CODEFORCES
// upsolve with rainboy import java.io.*; import java.util.*; public class CF1187G extends PrintWriter { CF1187G() { super(System.out); } static class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; int k, l; byte[] bb = new byte[1 << 15]; byte getc() { if (k >= l) { k = 0; try { l = in.read(bb); } catch (IOException e) { l = 0; } if (l <= 0) return -1; } return bb[k++]; } int nextInt() { byte c = 0; while (c <= 32) c = getc(); int a = 0; while (c > 32) { a = a * 10 + c - '0'; c = getc(); } return a; } } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1187G o = new CF1187G(); o.main(); o.flush(); } static final int INF = 0x3f3f3f3f; ArrayList[] aa_; int n_, m_; int[] pi, dd, bb; int[] uu, vv, uv, cost, cost_; int[] cc; void init() { aa_ = new ArrayList[n_]; for (int u = 0; u < n_; u++) aa_[u] = new ArrayList<Integer>(); pi = new int[n_]; dd = new int[n_]; bb = new int[n_]; uu = new int[m_]; vv = new int[m_]; uv = new int[m_]; cost = new int[m_]; cost_ = new int[m_]; cc = new int[m_ * 2]; m_ = 0; } void link(int u, int v, int cap, int cos) { int h = m_++; uu[h] = u; vv[h] = v; uv[h] = u ^ v; cost[h] = cos; cc[h << 1 ^ 0] = cap; aa_[u].add(h << 1 ^ 0); aa_[v].add(h << 1 ^ 1); } boolean dijkstra(int s, int t) { Arrays.fill(pi, INF); pi[s] = 0; TreeSet<Integer> pq = new TreeSet<>((u, v) -> pi[u] != pi[v] ? pi[u] - pi[v] : dd[u] != dd[v] ? dd[u] - dd[v] : u - v); pq.add(s); Integer first; while ((first = pq.pollFirst()) != null) { int u = first; int d = dd[u] + 1; ArrayList<Integer> adj = aa_[u]; for (int h_ : adj) if (cc[h_] > 0) { int h = h_ >> 1; int p = pi[u] + ((h_ & 1) == 0 ? cost_[h] : -cost_[h]); int v = u ^ uv[h]; if (pi[v] > p || pi[v] == p && dd[v] > d) { if (pi[v] != INF) pq.remove(v); pi[v] = p; dd[v] = d; bb[v] = h_; pq.add(v); } } } return pi[t] != INF; } void push(int s, int t) { int c = INF; for (int u = t, h_, h; u != s; u ^= uv[h]) { h = (h_ = bb[u]) >> 1; c = Math.min(c, cc[h_]); } for (int u = t, h_, h; u != s; u ^= uv[h]) { h = (h_ = bb[u]) >> 1; cc[h_] -= c; cc[h_ ^ 1] += c; } } void push1(int s, int t) { for (int u = t, h_, h; u != s; u ^= uv[h]) { h = (h_ = bb[u]) >> 1; cc[h_]--; cc[h_ ^ 1]++; } } int edmonds_karp(int s, int t) { cost_ = Arrays.copyOf(cost, m_); while (dijkstra(s, t)) { push1(s, t); for (int h = 0; h < m_; h++) { int u = uu[h], v = vv[h]; if (pi[u] != INF && pi[v] != INF) cost_[h] += pi[u] - pi[v]; } } int c = 0; for (int h = 0; h < m_; h++) c += cost[h] * cc[h << 1 ^ 1]; return c; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); int[] ii = new int[k]; for (int h = 0; h < k; h++) ii[h] = sc.nextInt() - 1; ArrayList[] aa = new ArrayList[n]; for (int i = 0; i < n; i++) aa[i] = new ArrayList<Integer>(); for (int h = 0; h < m; h++) { int i = sc.nextInt() - 1; int j = sc.nextInt() - 1; aa[i].add(j); aa[j].add(i); } int t = n + k + 1; n_ = n * t + 1; m_ = k + (m * 2 * k + n) * (t - 1); init(); for (int i = 0; i < n; i++) { ArrayList<Integer> adj = aa[i]; for (int s = 0; s < t - 1; s++) { int u = i * t + s; for (int j : adj) { int v = j * t + s + 1; for (int x = 1; x <= k; x++) link(u, v, 1, c + (x * 2 - 1) * d); } } } for (int i = 0; i < n; i++) for (int s = 0; s < t - 1; s++) { int u = i * t + s, v = u + 1; link(u, v, k, i == 0 ? 0 : c); } for (int h = 0; h < k; h++) link(n_ - 1, ii[h] * t + 0, 1, 0); println(edmonds_karp(n_ - 1, 0 * t + t - 1)); } }
cubic
1187_G. Gang Up
CODEFORCES
import java.io.*; import java.util.*; public class B { public static void main(String[] args) { InputReader in = new InputReader(); int n = in.nextInt(); int k = in.nextInt(); long numCandies = 1; int turns = 1, add = 2; while (numCandies < k) { ++turns; numCandies += add++; } int res = 0; if (numCandies > k) { turns += (numCandies-k); res += (numCandies-k); numCandies = k; } if (turns == n) { System.out.println(res); } else { while (turns != n) { res += add; turns += add++ + 1; } System.out.println(res); } } static class InputReader { public BufferedReader br; public StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.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 int nextInt() { return Integer.parseInt(next()); } } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Main { private FastScanner in; private PrintWriter out; public void solve() throws IOException { int N = in.nextInt(); int M = in.nextInt(); int[][] edges = new int[N][N]; for (int i = 0; i < M; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; edges[a][b] = 1; edges[b][a] = 1; } int globalCountMasks = 1 << N; int[][] masks = new int[N + 1][]; int[] countMasks = new int[N + 1]; for (int i = 0; i <= N; i++) { masks[i] = new int[combinations(N, i)]; } for (int i = 0; i < globalCountMasks; i++) { int c = countBit1(i); masks[c][countMasks[c]] = i; countMasks[c]++; } long globalCountCycles = 0; long[][] count = new long[globalCountMasks][N]; for (int a = 0; a < N - 2; a++) { int aBit = 1 << a; count[aBit][a] = 1; long countCycles = 0; for (int i = 2; i <= N; i++) { for (int m = 0; m < countMasks[i]; m++) { int mask = masks[i][m]; if ((mask & aBit) == 0) continue; if ((mask & (aBit - 1)) > 0) continue; count[mask][a] = 0; for (int v = a + 1; v < N; v++) { int vBit = 1 << v; if ((mask & vBit) == 0) continue; count[mask][v] = 0; for (int t = a; t < N; t++) { if ((mask & (1 << t)) == 0 || t == v || edges[v][t] == 0) continue; count[mask][v] += count[mask ^ vBit][t]; } if (edges[a][v] == 1 && mask != (aBit | vBit)) { countCycles += count[mask][v]; } } } } globalCountCycles += countCycles / 2; } out.println(globalCountCycles); } private int countBit1(int k) { int c = 0; while (k > 0) { c += k & 1; k >>= 1; } return c; } private int combinations(int n, int k) { if (k > n || k < 0) { throw new IllegalArgumentException(); } int r = 1; for (int i = 1; i <= k; i++) { r = r * (n + 1 - i) / i; } return r; } public void run() { try { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } } public static void main(String[] arg) { new Main().run(); } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Scanner; import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class main implements Runnable{ static ArrayList <Integer> adj[]; static int co=0,f=0; static void Check2(int n){ adj=new ArrayList[n+1]; for(int i=0;i<=n;i++){ adj[i]=new ArrayList<>(); } } static void add(int i,int j){ adj[i].add(j); adj[j].add(i); } public static void main(String[] args) { new Thread(null, new main(), "Check2", 1<<26).start();// to increse stack size in java } static long mod=(long)(1e9+7); public void run() { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ //Scanner in=new Scanner(System.in); InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); long n=in.nextLong(); long s=in.nextLong(); long l=1; long r=(long)(n); long ans=-1; while(l<=r){ long mid=(l+r)/2; if(ch(mid,s)){ ans=mid; r=mid-1; } else { l=mid+1; } } if(ans==-1)w.println(0); else w.println(n-ans+1); w.close(); } public boolean ch(long a,long s){ long p=0; long val=a; while(val>0){ p=p+val%10; val=val/10; } if(a-p>=s)return true; return false; } public boolean rec(int a,int b,int x,int y,int c,int d,int co){ if(a>x|b>y)return false; if(a<-100000||b<-100000||co>100000)return false; if(a==x&&b==y)return true; return (rec(a+c,b+d,x,y,c,d,co+1)||rec(a+c,b-d,x,y,c,d,co+1)||rec(a-c,b+d,x,y,c,d,co+1)||rec(a-c,b-d,x,y,c,d,co+1)); } static int gcd(int a,int b){ if(b==0)return a; return gcd(b,a%b); } static void dfs(int i,int v[],int val,int b[]){ if(v[i]==1)return ; v[i]=1; b[i]=val; Iterator <Integer> it=adj[i].iterator(); while(it.hasNext()){ int q=it.next(); dfs(q,v,val,b); } } static void sev(int a[],int n){ for(int i=2;i<=n;i++)a[i]=i; for(int i=2;i<=n;i++){ if(a[i]!=0){ for(int j=2*i;j<=n;){ a[j]=0; j=j+i; } } } } static class pair implements Comparable<pair> { int x,y; pair(int c,int d){ x=c; y=d; } public int compareTo(pair o){ return (this.x-o.x); //sort in incrementing order w.r.t to c } } static class node{ int y; int val; node(int a,int b){ y=a; val=b; } } static void rec(String s,int a,int b,int n){ if(b==n){ System.out.println(s); return ; } String p=s; if(a>b){ s=p+")" ; rec(s,a,b+1,n); } if(a<n){ s=p+"("; rec(s,a+1,b,n); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.util.*; import java.io.*; public class virtual1{ static InputReader in = new InputReader(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { long x = in.nextLong(); long k = in.nextLong(); long mod = (long)1e9+7l; //out.println(mod); long mul1 = 1; long mul2 = 2*x-1; mul2 = mul2%mod; long pow = k; long to = 2; while(pow>0l){ if(pow%2l==1l){ mul1 = mul1*to; mul1%=mod; } to=to*to; to%=mod; pow = pow/2l; } mul1 = mul1*mul2; mul1%=mod; mul1+=1; if(x!=0) out.println(mul1%mod); else out.println(0); out.close(); } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner in = new Scanner(System.in); long l = in.nextLong(); long r = in.nextLong(); long a = 0; long b = 0; long c = 0; if (r - l < 2) System.out.println(-1); else if (r - l < 3 && l % 2 == 1) System.out.println(-1); else { if (l % 2 == 0) { a = l; b = l + 1; c = l + 2; } else { if (l == 1) { a = 2; b = 3; c = 4; } else { a = l + 1; b = l + 2; c = l + 3; } } System.out.println(a + " " + b + " " + c); } } }
constant
483_A. Counterexample
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main { public static void main(String[] args) { new Main().run(); } void run() { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(), k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = in.nextInt(); Arrays.sort(a); int ret = 0, it = 0; for (int i = 0; i < n; ++i) { int val = a[i] % k == 0 ? a[i] / k : -1; while (it < i && a[it] < val) ++it; if (it == i || a[it] != val) { ++ret; } else { a[i] = 0; } } out.println(ret); out.close(); } } class InputReader { BufferedReader buff; StringTokenizer tokenizer; InputReader(InputStream stream) { buff = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(buff.readLine()); } catch (Exception e) { return false; } return true; } String next() { if (!hasNext()) throw new RuntimeException(); return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main implements Runnable { //public static final String FileName = "test"; StreamTokenizer ST; PrintWriter out; BufferedReader br; Scanner in; static final int inf = 1000000000; int nextInt() throws IOException{ ST.nextToken(); return (int)ST.nval; } long nextLong() throws IOException{ ST.nextToken(); return (long)ST.nval; } String next() throws IOException{ ST.nextToken(); return ST.sval; } double nextD() throws IOException{ ST.nextToken(); return ST.nval; } public static void main(String[] args) throws IOException { new Thread(new Main()).start(); // new Main().run(); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //br = new BufferedReader(new FileReader(new File(FileName+".in"))); //out = new PrintWriter(new BufferedWriter(new FileWriter(FileName+".out"))); in = new Scanner(br); ST = new StreamTokenizer(br); solve(); out.close(); //in.close(); br.close(); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException(e); } } public void solve() throws IOException { int n = nextInt(); int K = nextInt(); boolean[] f = new boolean[n+1]; Arrays.fill(f, true); Vector<Integer> P = new Vector<Integer>(); for (int i=2; i<=n; i++) if (f[i]) { for (int j=2*i; j<=n; j+=i) f[j] = false; P.add(i); } for (int i=0; i<P.size()-1; i++) { int x = P.elementAt(i)+P.elementAt(i+1)+1; if (x<=n && f[x]) K--; } if (K<=0) out.println("YES"); else out.println("NO"); //for (int x:P) out.print(x+" "); } }
linear
17_A. Noldbach problem
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class thing { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); String s = in.next(); int[][] count = new int[m][m]; int[] dp = new int[1 << m]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for(int i = 1; i < n; i++) { int a = s.charAt(i)-'a'; int b = s.charAt(i-1)-'a'; count[a][b]++; count[b][a]++; } for(int i = 1; i < (1 << m); i++) { int pos = set_bits(i); for(int j = 0; (i >> j) != 0; j++) { if(((i >> j) & 1) == 0) continue; int sum = 0; for(int mask = i, y = 0; y < m; mask >>= 1, y++) { if(y == j) continue; if((mask & 1) == 1) sum += count[j][y]; else sum -= count[j][y]; } int calc = dp[i-(1<<j)] + pos*sum; dp[i] = Math.min(dp[i], calc); } } System.out.println(dp[(1 << m)-1]); } public static int set_bits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } }
np
1238_E. Keyboard Purchase
CODEFORCES
//package round136; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = new int[n]; int[] b = new int[n]; for(int i = 0;i < n;i++)b[i] = a[i] = ni(); Arrays.sort(b); int ct = 0; for(int i = 0;i < n;i++){ if(a[i] != b[i])ct++; } if(ct <= 2){ out.println("YES"); }else{ out.println("NO"); } } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } public int ni() { try { int num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public long nl() { try { long num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public String ns() { try{ int b = 0; StringBuilder sb = new StringBuilder(); while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' ')); if(b == -1)return ""; sb.append((char)b); while(true){ b = is.read(); if(b == -1)return sb.toString(); if(b == '\r' || b == '\n' || b == ' ')return sb.toString(); sb.append((char)b); } } catch (IOException e) { } return ""; } public char[] ns(int n) { char[] buf = new char[n]; try{ int b = 0, p = 0; while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n')); if(b == -1)return null; buf[p++] = (char)b; while(p < n){ b = is.read(); if(b == -1 || b == ' ' || b == '\r' || b == '\n')break; buf[p++] = (char)b; } return Arrays.copyOf(buf, p); } catch (IOException e) { } return null; } double nd() { return Double.parseDouble(ns()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.*; import java.io.*; public class D { static final boolean stdin = true; static final String filename = ""; static FastScanner br; static PrintWriter pw; public static void main(String[] args) throws IOException { if (stdin) { br = new FastScanner(); pw = new PrintWriter(new OutputStreamWriter(System.out)); } else { br = new FastScanner(filename + ".in"); pw = new PrintWriter(new FileWriter(filename + ".out")); } Solver solver = new Solver(); solver.solve(br, pw); } static class Solver { static long mod = (long) (1e10); public void solve(FastScanner br, PrintWriter pw) throws IOException { int n = br.ni(); Integer[] in = br.nIa(n); TreeSet<Integer> ts = new TreeSet<Integer>(); for (int i = 0; i < n; i++) { ts.add(in[i]); } String twoSol = ""; for (int i = 0; i <= 30; i++) { for (int j : in) { if (ts.contains(j + (int) Math.pow(2, i))) { if (ts.contains(j - (int) Math.pow(2, i))) { pw.println(3); pw.println(j + " " + (j + (int) Math.pow(2, i)) + " " + (j - (int) Math.pow(2, i))); pw.close(); System.exit(0); }else{ twoSol = (j + " " + (j + (int) Math.pow(2, i))); } } } } if (twoSol.isEmpty()) { pw.println(1); pw.println(in[0]); } else { pw.println(2); pw.println(twoSol); } pw.close(); } static long gcd(long a, long b) { if (a > b) return gcd(b, a); if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return a * (b / gcd(a, b)); } static long pow(long a, long b) { if (b == 0) return 1L; long val = pow(a, b / 2); if (b % 2 == 0) return val * val % mod; else return val * val % mod * a % mod; } } static class Point implements Comparable<Point> { int a; int b; Point(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Point o) { return this.a - o.a; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } ArrayList<Integer>[] ng(int n, int e) { ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<Integer>(); } for (int i = 0; i < e; i++) { int a = ni() - 1; int b = ni() - 1; adj[a].add(b); adj[b].add(a); } return adj; } Integer[] nIa(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } int[] nia(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } Long[] nLa(int n) { Long[] arr = new Long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } long[] nla(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } String[] nsa(int n) { String[] arr = new String[n]; for (int i = 0; i < n; i++) { arr[i] = nt(); } return arr; } String nt() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(nt()); } long nl() { return Long.parseLong(nt()); } double nd() { return Double.parseDouble(nt()); } } }
nlogn
988_D. Points and Powers of Two
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class DivRound584ProblemA { static FastReader sc=new FastReader(); public static void main(String args[]) throws IOException { int n = sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); Arrays.sort(a); int c=0; for(int i=0;i<n;i++) { if(a[i]<0) continue; c=c-1; for(int j=i+1;j<n;j++) { if(a[j]<0) continue; if(a[j]%a[i]==0) { //System.out.println(a[i]+" : "+a[j]); a[j]=c; } } //System.out.println(c); } System.out.println(Math.abs(c)); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();} public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;} public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;} public double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;} } // |----| /\ | | ----- | // | / / \ | | | | // |--/ /----\ |----| | | // | \ / \ | | | | // | \ / \ | | ----- ------- public static void main(String[] args)throws IOException { Reader sc=new Reader(); PrintWriter out=new PrintWriter(System.out); int n=sc.i(); int arr[]=sc.arr(n); int count=0; for(int i=0;i<n;i++)for(int j=i+1;j<n;j++)if(arr[j]<arr[i])count++; count%=2; int q=sc.i(); while(q-->0) { int a=sc.i(); int b=sc.i(); long len=((long)(b-a+1)*(b-a))/2; if(len%2==1)count^=1; if(count==0)out.println("even"); else out.println("odd"); } out.flush(); } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.*; import static java.util.Arrays.deepToString; public class A { private static int[] prime = new int[] { 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 }; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); for (int i=0;i<prime.length-1;i++) { if ((prime[i]+prime[i+1]+1) > n || k == 0) break; if (isPrime(prime[i]+prime[i+1]+1)) k--; } if (k == 0) outnl("YES"); else outnl("NO"); } public static boolean isPrime(int x) { int i=0; while (i<prime.length) if (prime[i++] == x) return true; return false; } private static void debug(Object... os) { System.out.println(deepToString(os)); } private static void outnl(String out) { System.out.println(out); } }
linear
17_A. Noldbach problem
CODEFORCES
import static java.lang.Math.max; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class GivenString implements Runnable { public static void main(String[] args) throws Exception { new GivenString().run(); } private void solve() throws Exception { String s = nextToken(); int len = s.length(); KMP kmp = new KMP(); int r = 0; for (int i = 0; i < len; i++) { for (int j = i + 1; j <= len; j++) { String cur = s.substring(i, j); int count = kmp.search(s, cur); if (count >= 2) r = max(r, cur.length()); } } out.println(r); } class KMP { public int search(String text, String pattern) { int count = 0; int n = text.length(), m = pattern.length(), matchPoint = -1; char pat[] = pattern.toCharArray(), t[] = text.toCharArray(); int p[] = prefixTable(pattern); int j = 0; for (int i = 0; i < n; i++) { while (j > 0 && pat[j] != t[i]) j = p[j - 1]; if (pat[j] == t[i]) j++; if (j == m) { matchPoint = i - m + 1; j = p[j - 1]; count++; } } return count; } private int[] prefixTable(String pat) { int m = pat.length(), p[] = new int[m]; char s[] = pat.toCharArray(); int j = 0; for (int i = 1; i < m; i++) { while (j > 0 && s[j] != s[i]) j = p[j - 1]; if (s[j] == s[i]) j++; p[i] = j; } return p; } } // -------------- Input/Output routines below ---------------// private BufferedReader in; PrintWriter out; StringTokenizer tokenizer; public void run() { // String problem = this.getClass().getName(); try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedOutputStream(System.out)); solve(); out.flush(); in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); // System.exit(1); } } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.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()); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; public class Waw{ public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long[] a = new long[n]; for(int i=0;i<n;i++) a[i] = sc.nextLong(); long[] p = new long[n]; p[n-1] = a[n-1]; for(int i=n-2;i>=0;i--){ if(a[i]<p[i+1]) p[i] = p[i+1]-1; else p[i] = a[i]; } long max = p[0]; long res = p[0] - a[0]; for(int i=1;i<n;i++){ if(max < p[i]) max = p[i]; res += max - a[i]; } System.out.println(res); } }
linear
924_C. Riverside Curio
CODEFORCES
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); TreeSet<Integer> set = new TreeSet<Integer>(); for(int i=0;i<n;i++){ set.add(sc.nextInt()); } if(set.size() >= 2) System.out.println(set.toArray()[1]); else System.out.println("NO"); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.util.InputMismatchException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author emotionalBlind */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { int N = in.readInt(); long K = in.readLong(); long[] a = new long[N]; for (int i = 0; i < N; ++i) { a[i] = in.readLong(); } ArrayShuffler s = new ArrayShuffler(); s.shuffle(a); Arrays.sort(a); boolean[] taken = new boolean[N]; Arrays.fill(taken, true); int i = 0; int j = i + 1; int res = N; while (i < a.length) { if (taken[i] == false) { i++; if (j <= i) j = i + 1; continue; } while (j < a.length && a[j] < a[i] * K) { j++; } if (j < a.length) { if (a[j] == a[i] * K) { taken[j] = false; res--; } } i++; if (j <= i) j = i + 1; } out.printLine(res); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { // InputMismatchException -> UnknownError if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } 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(); } else if (c == '+') { 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class ArrayShuffler { static Random random = new Random(7428429L); public void shuffle(long[] p) { for (int i = 0; i < p.length; ++i) { int j = i + random.nextInt(p.length - i); long temp = p[i]; p[i] = p[j]; p[j] = temp; } } }
nlogn
274_A. k-Multiple Free Set
CODEFORCES
import static java.util.Arrays.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import java.util.*; import java.math.*; import java.io.*; public class A implements Runnable { String file = "input"; boolean TEST = System.getProperty("ONLINE_JUDGE") == null; void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); int[] b = a.clone(); qsort(b); //sortInt(b); int count = 0; for(int i = 0; i < a.length; i++) if(a[i] != b[i]) count++; if(count == 0 || count == 2) out.println("YES"); else out.println("NO"); } void qsort(int[] a) { List<Integer> as = new ArrayList<Integer>(); for(int x : a) as.add(x); Collections.shuffle(as); int j = 0; for(int x : as) a[j++] = x; sort(a); } Random rnd = new Random(); void sortInt(int[] a) { sortInt(a, 0, a.length - 1); } void sortInt(int[] a, int from, int to) { if(from >= to) return; int i = from - 1; int p = rnd.nextInt(to - from + 1) + from; int t = a[p]; a[p] = a[to]; a[to] = t; for(int j = from; j < to; j++) if(a[j] <= a[to]) { i++; t = a[i]; a[i] = a[j]; a[j] = t; } t = a[i + 1]; a[i + 1] = a[to]; a[to] = t; sortInt(a, i + 2, to); while(i >= 0 && a[i] == a[i + 1]) i--; sortInt(a, from, i); } String next() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(input.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } void print(Object... o) { System.out.println(deepToString(o)); } void gcj(Object o) { String s = String.valueOf(o); out.println("Case #" + test + ": " + s); System.out.println("Case #" + test + ": " + s); } BufferedReader input; PrintWriter out; StringTokenizer st; int test; void init() throws IOException { if(TEST) input = new BufferedReader(new FileReader(file + ".in")); else input = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedOutputStream(System.out)); } public static void main(String[] args) throws IOException { new Thread(null, new A(), "", 1 << 22).start(); } public void run() { try { init(); if(TEST) { int runs = nextInt(); for(int i = 0; i < runs; i++) solve(); } else solve(); out.close(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }
nlogn
220_A. Little Elephant and Problem
CODEFORCES
import java.util.*; import java.math.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { Scanner c=new Scanner(System.in); int n=c.nextInt(); int a=c.nextInt(); //higher int b=c.nextInt(); //lower int C[]=new int[n]; for(int i=0;i<n;i++) C[i]=c.nextInt(); Arrays.sort(C); //System.out.println(Arrays.toString(C)); int petya=C[n-a]; System.out.println((C[n-a]-C[n-a-1])); } } //must declare new classes here
nlogn
169_A. Chores
CODEFORCES
import java.awt.*; import java.io.*; import java.sql.Array; import java.util.*; import java.util.List; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static final int N=405; static final int mod=1000000007; static final int INF=1000000009; static final int numBit=17; static FastReader r=new FastReader(); static PrintWriter pw = new PrintWriter(System.out); // call dp[i][j] is number ways can turn on i computer but we just turn on j computer manually. static int [][]dp=new int[N][N]; static int []p2=new int[N]; static int []fac=new int[N]; static int []ifac=new int[N]; static int M; public static int mul(int a,int b){ return (int)(1l*a*b%M); } public static int poww(int a,int b){ int r=1; while(b>0){ if(b%2==1) r=mul(r,a); a=mul(a,a); b>>=1; } return r; } public static int inv(int x){ return poww(x,M-2); } public static int add(int a,int b){ a+=b; if(a>=M) a-=M; return a; } public static int bino(int n,int k){ return mul(fac[n],mul(ifac[n-k],ifac[k])); } public static void main(String[] args) throws IOException { int n=r.nextInt(); M=r.nextInt(); fac[0]=1; ifac[0]=1; p2[0]=1; for(int i=1;i<=n;++i){ fac[i]=mul(fac[i-1],i); ifac[i]=inv(fac[i]); p2[i]=mul(p2[i-1],2); } int ans=0; dp[0][0]=1; for(int i=0;i<=n;++i){ for(int k=0;k<=i;++k){ for(int j=1;j<=n-i+1;++j){ dp[i+j+1][k+j]=add(dp[i+j+1][k+j],mul(dp[i][k],mul(p2[j-1],bino(j+k,j)))); } } } for(int i=0;i<=n+1;++i){ ans=add(ans,dp[n+1][i]); } pw.print(ans); pw.close(); } }
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.util.Arrays; import java.util.Random; import java.io.IOException; import java.io.Reader; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author tanzaku */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyInput in = new MyInput(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { int n; int k; long[] neigibor; Random random = new Random(); long maxClique; public void solve(int testNumber, MyInput in, PrintWriter out) { n = in.nextInt(); k = in.nextInt(); neigibor = new long[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { neigibor[i] |= in.nextLong() << j; } } long maxClique = bronKerbosch(); long a = Long.bitCount(maxClique); dump(a); out.printf("%.12f\n", a * (a - 1.0) / 2 * k / a * k / a); } static void dump(Object... o) { System.err.println(Arrays.deepToString(o)); } long bronKerbosch() { maxClique = 0; bronKerbosch2(0, (1L << n) - 1, 0); return maxClique; } void bronKerbosch2(long r, long p, long x) { if (Long.bitCount(maxClique) >= Long.bitCount(r | p | x)) return; long px = p | x; if (px == 0) { if (Long.bitCount(maxClique) < Long.bitCount(r)) { maxClique = r; } return; } int cnt = Long.bitCount(px); int choice = random.nextInt(cnt); int u; for (int i = 0; ; i++) { if ((px >>> i & 1) != 0 && choice-- == 0) { u = i; break; } } // dump(r, p, x, u, neigibor); long ne = p & ~neigibor[u]; for (int v = 0; v < n; v++) if ((ne >>> v & 1) != 0) { bronKerbosch2(r | 1L << v, p & neigibor[v], x & neigibor[v]); p &= ~(1L << v); x |= 1L << v; } } } static class MyInput { private final BufferedReader in; private static int pos; private static int readLen; private static final char[] buffer = new char[1024 * 8]; private static char[] str = new char[500 * 8 * 2]; private static boolean[] isDigit = new boolean[256]; private static boolean[] isSpace = new boolean[256]; private static boolean[] isLineSep = new boolean[256]; static { for (int i = 0; i < 10; i++) { isDigit['0' + i] = true; } isDigit['-'] = true; isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true; isLineSep['\r'] = isLineSep['\n'] = true; } public MyInput(InputStream is) { in = new BufferedReader(new InputStreamReader(is)); } public int read() { if (pos >= readLen) { pos = 0; try { readLen = in.read(buffer); } catch (IOException e) { throw new RuntimeException(); } if (readLen <= 0) { throw new MyInput.EndOfFileRuntimeException(); } } return buffer[pos++]; } public int nextInt() { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); int i = 0; int ret = 0; if (str[0] == '-') { i = 1; } for (; i < len; i++) ret = ret * 10 + str[i] - '0'; if (str[0] == '-') { ret = -ret; } return ret; } public long nextLong() { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); int i = 0; long ret = 0; if (str[0] == '-') { i = 1; } for (; i < len; i++) ret = ret * 10 + str[i] - '0'; if (str[0] == '-') { ret = -ret; } return ret; } public char nextChar() { while (true) { final int c = read(); if (!isSpace[c]) { return (char) c; } } } int reads(int len, boolean[] accept) { try { while (true) { final int c = read(); if (accept[c]) { break; } if (str.length == len) { char[] rep = new char[str.length * 3 / 2]; System.arraycopy(str, 0, rep, 0, str.length); str = rep; } str[len++] = (char) c; } } catch (MyInput.EndOfFileRuntimeException e) { } return len; } static class EndOfFileRuntimeException extends RuntimeException { } } }
np
839_E. Mother of Dragons
CODEFORCES
import java.io.*; import java.util.*; public class C { static int n, m, a[][]; static int[][] memo; static Integer[] indices; static int[] getCol(int col, int shift) { int[] ans = new int[n]; for (int i = 0, j = shift; i < n; i++, j = (j + 1) % n) { ans[i] = a[j][col]; } return ans; } static int dp(int col, int msk) { if (col == n||col==m) return 0; if (memo[msk][col] != -1) return memo[msk][col]; int ans = 0; for (int shift = 0; shift < n; shift++) { int[] currCol = getCol(indices[col], shift); for (int nxtMsk = 0; nxtMsk < 1 << n; nxtMsk++) { if ((nxtMsk & msk) != msk) continue; int curr = 0; int diff = msk ^ nxtMsk; for (int i = 0; i < n; i++) if ((diff & 1 << i) != 0) curr += currCol[i]; ans = Math.max(ans, dp(col + 1, nxtMsk) + curr); } } return memo[msk][col] = ans; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int tc = sc.nextInt(); while (tc-- > 0) { n = sc.nextInt(); m = sc.nextInt(); indices = new Integer[m]; memo = new int[1 << n][m]; for (int[] x : memo) Arrays.fill(x, -1); a = new int[n][m]; int[] max = new int[m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { a[i][j] = sc.nextInt(); max[j] = Math.max(max[j], a[i][j]); } for (int j = 0; j < m; j++) { indices[j] = j; } Arrays.sort(indices, Comparator.comparingInt(i -> -max[i])); out.println(dp(0, 0)); } out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
//package codeforces; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Scanner; public class CodeForces { //private static MyScanner sc; private static MyPrinter out; public static void solve() throws IOException { Scanner sc = new Scanner(System.in); long l = sc.nextLong(); long r = sc.nextLong(); String ls = Long.toBinaryString(l); String rs = Long.toBinaryString(r); while (ls.length() < rs.length()) { ls = "0" + ls; } String res = ""; boolean ok = false; for (int i = 0; i < ls.length(); i++) { if (ok) { res += "1"; } else { if (ls.charAt(i) != rs.charAt(i)) { res += "1"; ok = true; } } } long all = 0; for (int i = 0; i < res.length(); i++) { all += (long) Math.pow((long) 2, (long) res.length() - 1 - i); } System.out.println(all); } public static void main(String[] args) throws IOException { //sc = new MyScanner(System.in); out = new MyPrinter(System.out); solve(); out.close(); } } class MyScanner { private StreamTokenizer st; public MyScanner(InputStream is) { st = new StreamTokenizer(new BufferedReader(new InputStreamReader(is))); } public MyScanner(File f) throws FileNotFoundException { st = new StreamTokenizer(new BufferedReader(new FileReader(f))); } public int nextInt() throws IOException { st.nextToken(); return ((int) st.nval); } public double nextDouble() throws IOException { st.nextToken(); return (st.nval); } public String nextString() throws IOException { st.nextToken(); if (st.ttype == StreamTokenizer.TT_WORD) { return (st.sval); } else { return ("not found"); } } } class MyPrinter { private BufferedWriter out; public MyPrinter(OutputStream os) { out = new BufferedWriter(new PrintWriter(os)); } public MyPrinter(File f) throws IOException { out = new BufferedWriter(new FileWriter(f)); } public void println(int i) throws IOException { out.write(Integer.toString(i)); out.newLine(); } public void println(double d) throws IOException { out.write(Double.toString(d)); out.newLine(); } public void println(long l) throws IOException { out.write(Long.toString(l)); out.newLine(); } public void println(String s) throws IOException { out.write(s); out.newLine(); } public void println(char c) throws IOException { out.write(Character.toString(c)); out.newLine(); } public void print(int i) throws IOException { out.write(Integer.toString(i)); } public void print(double d) throws IOException { out.write(Double.toString(d)); } public void print(long l) throws IOException { out.write(Long.toString(l)); } public void print(String s) throws IOException { out.write(s); } public void print(char c) throws IOException { out.write(Character.toString(c)); } public void close() throws IOException { out.flush(); out.close(); } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
import java.io.*; import java.math.BigDecimal; import java.math.MathContext; import java.util.*; public class Main { static int len(long n) { int res = 0; while (n > 0) { n /= 10; res++; } return res; } static long big(int len) { long p = 1; while (len-- > 0) p *= 10; return p - 1; } static long small(int len) { return big(len - 1) + 1; } static long cnt(long n) { int len = len(n); long cnt = 0; for (int l = 1; l < len; l++) cnt += 1l * l * (big(l) - small(l) + 1); cnt += 1l * len * (n - small(len)); return cnt; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); long k = sc.nextLong(); if (k == 1) { System.out.println(1); return; } long lo = 1, hi = k, res = 1; while(lo <= hi) { long mid = lo + hi >> 1L; if(cnt(mid) < k) { res = mid; lo = mid + 1; } else { hi = mid - 1; } } ArrayList<Integer> digits = new ArrayList<>(); long tmp = res; while (tmp > 0) { digits.add((int)(tmp % 10)); tmp /= 10; } // System.err.println("RES " + res); // System.err.println("DIGITS " + digits); // System.err.println("Cnt Res " + cnt(res)); Collections.reverse(digits); out.println(digits.get((int)(k - cnt(res) - 1))); out.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import sun.rmi.transport.DGCImpl_Stub; import java.io.*; import java.nio.file.ClosedWatchServiceException; import java.util.*; public class Main { public static void main(String[] args) throws FileNotFoundException { ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out)); // String fileName = "C-large"; // ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".out"))); new Main(io).solve(); // new Main(io).solveLocal(); io.close(); } ConsoleIO io; Main(ConsoleIO io) { this.io = io; } ConsoleIO opt; Main(ConsoleIO io, ConsoleIO opt) { this.io = io; this.opt = opt; } List<List<Integer>> gr = new ArrayList<>(); long MOD = 1_000_000_007; public void solve() { long x = io.readLong(), k = io.readLong(); if(x==0){ io.writeLine("0"); return; } long res = ((pow(2, k+1, MOD) * (x % MOD)) % MOD - pow(2, k, MOD) % MOD + 1 + MOD) % MOD; io.writeLine(res+""); } long pow(long a, long p, long mod) { long res = 1; while (p > 0) { if (p % 2 == 1) res = (res * a) % mod; a = (a * a) % mod; p /= 2; } return res; } } class ConsoleIO { BufferedReader br; PrintWriter out; public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;} public void flush(){this.out.flush();} public void close(){this.out.close();} public void writeLine(String s) {this.out.println(s);} public void writeInt(int a) {this.out.print(a);this.out.print(' ');} public void writeWord(String s){ this.out.print(s); } public void writeIntArray(int[] a, int k, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { if (i > 0) sb.append(separator); sb.append(a[i]); } this.writeLine(sb.toString()); } public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }} public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}} public long[] readLongArray() { String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length]; for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]); return r; } public int[] readIntArray() { String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length]; for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]); return r; } public int[] readIntArray(int n) { int[] res = new int[n]; char[] all = this.readLine().toCharArray(); int cur = 0;boolean have = false; int k = 0; boolean neg = false; for(int i = 0;i<all.length;i++){ if(all[i]>='0' && all[i]<='9'){ cur = cur*10+all[i]-'0'; have = true; }else if(all[i]=='-') { neg = true; } else if(have){ res[k++] = neg?-cur:cur; cur = 0; have = false; neg = false; } } if(have)res[k++] = neg?-cur:cur; return res; } public int ri() { try { int r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public long readLong() { try { long r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public String readWord() { try { boolean start = false; StringBuilder sb = new StringBuilder(); while (true) { int c = br.read(); if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') { sb.append((char)c); start = true; } else if (start || c == -1) return sb.toString(); } } catch (Exception ex) { return ""; } } public char readSymbol() { try { while (true) { int c = br.read(); if (c != ' ' && c != '\r' && c != '\n' && c != '\t') { return (char) c; } } } catch (Exception ex) { return 0; } } //public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }} } class Pair { public Pair(int a, int b) {this.a = a;this.b = b;} public int a; public int b; } class PairLL { public PairLL(long a, long b) {this.a = a;this.b = b;} public long a; public long b; } class Triple { public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;} public int a; public int b; public int c; }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.StringTokenizer; /** * 9:50 ~ * */ public class Main { public static int n, x, y; public static int[] a,b; public static int dp[], before[]; public static int dx[]; public static int d[][]; public static final int INF = 24 * 201 * 201; public static void main(String[] argv) { FastScanner scan = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); x = scan.nextInt(); y = scan.nextInt(); n = scan.nextInt(); a = new int[n+1]; b = new int[n+1]; dx = new int[n+1]; d = new int[n+1][n+1]; for(int i = 0; i < n; ++i){ a[i] = scan.nextInt(); b[i] = scan.nextInt(); } for(int i = 0; i < n; ++i){ dx[i] = dist(i); } for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j){ d[i][j] = dist(i,j); } } dp = new int[1 << n]; before = new int[1 << n]; Arrays.fill(dp, INF); dp[0] = 0; for(int state = 0; state < (1<<n); state++){ //if(dp[state] == INF) continue; for(int i = 0; i < n; ++i){ int ii = (1 << i); if((state & ii) > 0){ if(dp[state - ii] == INF) continue; int newdist = dp[state - ii] + dx[i] + dx[i]; if(dp[state] > newdist){ dp[state] = newdist; before[state] = state - ii; } } else continue; for(int j = i + 1; j < n; ++j){ if(i == j) continue; int jj = (1 << j); if((state & jj) > 0){ if(dp[state - ii - jj] == INF) continue; int newdist = dp[state - ii - jj] + dx[i] + d[i][j] + dx[j]; if(dp[state] > newdist){ dp[state] = newdist; before[state] = state - ii - jj; } } } break; } } System.out.println(dp[(1<<n)-1]); int state = (1<<n) - 1; StringBuffer ret = new StringBuffer(); while(state > 0){ int nstate = before[state]; boolean find = false; String made = ""; for(int i = 0; i < n; ++i){ if(((state & (1<<i)) > 0) && ((nstate & (1<<i)) == 0)){ find = true; made = made + " " + (i + 1); } } if(find){ made = made + " 0"; ret.append(made, 0, made.length()); } state = nstate; } out.println("0" + ret.toString()); out.close(); } public static int dist(int to){ return Math.abs(a[to] - x) * Math.abs(a[to] - x) + Math.abs(b[to] - y) * Math.abs(b[to] - y); } public static int dist(int from, int to){ return Math.abs(a[from]-a[to]) * Math.abs(a[from]-a[to]) + Math.abs(b[from]-b[to]) * Math.abs(b[from]-b[to]); } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream is) { try { br = new BufferedReader(new InputStreamReader(is)); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { return null; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.valueOf(next()); } } }
np
8_C. Looking for Order
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class LogicalExpression { int N = 256; void solve() { Expression[] E = new Expression[N]; for (int i = 0; i < N; i++) E[i] = new Expression(); E[Integer.parseInt("00001111", 2)].update_f("x"); E[Integer.parseInt("00110011", 2)].update_f("y"); E[Integer.parseInt("01010101", 2)].update_f("z"); for (int l = 2; l < 40; l++) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (E[i].e != null && E[j].t != null && E[i].e.length() + E[j].t.length() + 1 == l) { E[i | j].update_e(E[i].e + '|' + E[j].t); } if (E[i].t != null && E[j].f != null && E[i].t.length() + E[j].f.length() + 1 == l) { E[i & j].update_t(E[i].t + '&' + E[j].f); } } if (E[i].f != null) E[i ^ (N - 1)].update_f('!' + E[i].f); } } String[] res = new String[N]; for (int i = 0; i < N; i++) res[i] = E[i].calc_best(); int n = in.nextInt(); for (int i = 0; i < n; i++) { int x = Integer.parseInt(in.nextToken(), 2); out.println(res[x]); } } static class Expression { String e, t, f; Expression() { } public Expression(String e, String t, String f) { this.e = e; this.t = t; this.f = f; } String calc_best() { String best = e; if (compare(best, t) > 0) best = t; if (compare(best, f) > 0) best = f; return best; } void update_e(String ne) { if (e == null || compare(e, ne) > 0) { e = ne; update_f('(' + e + ')'); } } void update_t(String nt) { if (t == null || compare(t, nt) > 0) { t = nt; update_e(t); } } void update_f(String nf) { if (f == null || compare(f, nf) > 0) { f = nf; update_t(f); } } int compare(String a, String b) { if (a.length() != b.length()) return Integer.compare(a.length(), b.length()); return a.compareTo(b); } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new LogicalExpression().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
quadratic
913_E. Logical Expression
CODEFORCES
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; public class C { static StringBuilder st = new StringBuilder(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); Point [] square = new Point [4] ; Point [] rotSquare = new Point[4] ; for(int i = 0 ; i < 4 ;i++) square[i] = new Point(sc.nextInt() , sc.nextInt()); for(int i = 0 ; i < 4 ;i++) rotSquare[i] = new Point(sc.nextInt() , sc.nextInt()); boolean can = false ; for(int x = -100 ; x <= 100 ; x++) for(int y = -100 ; y <= 100 ; y++) can |= inside(new Point(x , y), square) & inside(new Point (x , y), rotSquare); out.println(can ? "YES" : "NO"); out.flush(); out.close(); } static int crossProduct(Point a , Point b) { int ans = a.x * b.y - a.y * b.x ; if(ans < 0)return -1 ; if(ans == 0) return 0 ; return 1 ; } static boolean inside(Point a , Point [] points) { boolean allPos = true ; boolean allNeg = true ; for(int i = 0 ; i < 4 ; i++) { Point v1 = new Point (points[i].x - a.x , points[i].y - a.y) ; Point v2 = new Point (points[(i + 1) % 4].x - a.x , points[(i + 1) % 4].y - a.y) ; allPos &= crossProduct(v1, v2) >= 0; allNeg &= crossProduct(v1, v2) <= 0; } return allPos | allNeg ; } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } } static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
constant
994_C. Two Squares
CODEFORCES
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; public class C { private static final String REGEX = " "; private static final Boolean DEBUG = false; private static final String FILE_NAME = "input.txt"; public static void main(String[] args) throws IOException { if (DEBUG) { generate(); } Solver solver = new Solver(); solver.readData(); solver.solveAndPrint(); } private static void generate() throws IOException { // FileWriter writer = new FileWriter("input.txt"); // writer.close(); } private static class Solver { long n, s; void readData() throws IOException { InputStream in = DEBUG ? new FileInputStream(FILE_NAME) : System.in; Scanner scanner = new Scanner(in); n = scanner.nextLong(); s = scanner.nextLong(); scanner.close(); } void solveAndPrint() { long cur = s + 1; long sum = getSum(cur); long res = 0; while (cur <= n) { if (cur - sum >= s) { System.out.println(n - cur + 1); return; } cur++; if (cur % 10 != 0) { sum++; } else { sum = getSum(cur); } } System.out.println(0); } long getSum(long cur) { long res = 0; while (cur > 0) { res += cur % 10; cur /= 10; } return res; } @SuppressWarnings("SameParameterValue") int[] splitInteger(String string, int n) { final String[] split = string.split(REGEX, n); int[] result = new int[split.length]; for (int i = 0; i < n; ++i) { result[i] = Integer.parseInt(split[i]); } return result; } public int[] splitInteger(String string) { return splitInteger(string, 0); } @SuppressWarnings("SameParameterValue") long[] splitLong(String string, int n) { final String[] split = string.split(REGEX, n); long[] result = new long[split.length]; for (int i = 0; i < n; ++i) { result[i] = Long.parseLong(split[i]); } return result; } public long[] splitLong(String string) { return splitLong(string, 0); } @SuppressWarnings("SameParameterValue") double[] splitDouble(String string, int n) { final String[] split = string.split(REGEX, n); double[] result = new double[split.length]; for (int i = 0; i < n; ++i) { result[i] = Double.parseDouble(split[i]); } return result; } public double[] splitDouble(String string) { return splitDouble(string, 0); } @SuppressWarnings("SameParameterValue") String[] splitString(String string, int n) { return string.split(REGEX, n); } public String[] splitString(String string) { return splitString(string, 0); } public int max(int a, int b) { return Math.max(a, b); } public long max(long a, long b) { return Math.max(a, b); } public int min(int a, int b) { return Math.min(a, b); } public long min(long a, long b) { return Math.min(a, b); } public double max(double a, double b) { return Math.max(a, b); } public double min(double a, double b) { return Math.min(a, b); } private final static int MOD = 1000000009; int multMod(int a, int b) { return ((a % MOD) * (b % MOD)) % MOD; } int sumMod(int a, int b) { return ((a % MOD) + (b % MOD)) % MOD; } long multMod(long a, long b) { return ((a % MOD) * (b % MOD)) % MOD; } long sumMod(long a, long b) { return ((a % MOD) + (b % MOD)) % MOD; } } }
logn
817_C. Really Big Numbers
CODEFORCES
import java.util.Scanner; public class Subtractions { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t--!=0){ int a=s.nextInt(); int b=s.nextInt(); int min=Math.min(a, b); int max=Math.max(a, b); int ops=0; while(true){ int quo=max/min; ops+=quo; int rem=max%min; max=Math.max(rem, min); min=Math.min(min, rem); if(rem==0) break; } System.out.println(ops); } } }
constant
267_A. Subtractions
CODEFORCES
import java.util.*; public class E { public static void main(String[] args) { new E(new Scanner(System.in)); } int N, M; int[][][] memo; int go(int i, int j, int mask) { if (i == N) return go(0, j+1, mask); if (j == M) { int mm = mask%(1<<N); //System.out.println(Integer.toBinaryString(mm)+" "+Integer.toBinaryString(mask)); if (mm != ((1<<N)-1)) return N*M; return 0; } if (memo[i][j][mask] != -1) return memo[i][j][mask]; // Now place a spider cluster here int nMask = mask; int prevMask = 0; if (i > 0) prevMask = 1 << (N-1); int nextMask = 0; if (i < (N-1)) nextMask = 1 << (N+1); int curMask = 1 << N; int nextRowMask = 1 << (N+N); nMask = nMask|prevMask|nextMask|curMask|nextRowMask; nMask = nMask/2; int res = 1+go(i+1, j, nMask); int pr = mask%2; if (pr == 1) { // We have the option to skip here int rr = go(i+1, j, mask/2); if (rr < res) res = rr; } //System.out.printf("%d %d %s = %d%n", i, j, Integer.toBinaryString(mask), res); memo[i][j][mask] = res; return res; } public E(Scanner in) { int[] vals = new int[2]; vals[0] = in.nextInt(); vals[1] = in.nextInt(); Arrays.sort(vals); N = vals[0]; M = vals[1]; memo = new int[N][M][1<<(N+N+1)]; fill3(memo, -1); int r1 = go(0, 0, (1<<N)-1); int res = N*M-r1; System.out.printf("%d%n", res); } void fill3(int[][][] vvv, int val) { for (int[][] vv : vvv) for (int[] v : vv) Arrays.fill(v, val); } }
np
112_E. Petya and Spiders
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 { 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) {} new Main().run(); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); int N; int[] a; int[] b; int[] c; int T, H; void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); N = nextInt(); char[] s = nextToken().toCharArray(); a = new int [N]; H = 0; T = 0; for (int i = 0; i < s.length; i++) { a[i] = s[i] == 'T' ? 1 : 0; if (s[i] == 'T') T++; else H++; } if (T == 1 || H == 1) { out.println(0); out.close(); return; } b = Arrays.copyOf(a, a.length); c = Arrays.copyOf(a, a.length); sort(c); int ans = 100000000; for (int o = 0; o < N; o++) { for (int i = 0; i < N; i++) b[(i + o) % N] = a[i]; int cur = 0; for (int i = 0; i < N; i++) if (b[i] != c[i]) cur++; ans = min(ans, cur / 2); } out.println(ans); out.close(); } 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; } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { new Main().go(); } PrintWriter out; Reader in; BufferedReader br; Main() throws IOException { try { //br = new BufferedReader( new FileReader("input.txt") ); //in = new Reader("input.txt"); in = new Reader("input.txt"); out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); } catch (Exception e) { //br = new BufferedReader( new InputStreamReader( System.in ) ); in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); } } void go() throws Exception { //int t = in.nextInt(); int t = 1; while (t > 0) { solve(); t--; } out.flush(); out.close(); } int inf = 2000000000; int mod = 1000000007; double eps = 0.000000001; int n; int m; ArrayList<Integer>[] g; int[] a; void solve() throws IOException { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); HashMap<Integer, ArrayList<Pair>> segs = new HashMap<>(); for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { sum += a[j]; if (!segs.containsKey(sum)) segs.put(sum, new ArrayList<>()); segs.get(sum).add(new Pair(i, j)); } } int max = 0; ArrayList<Pair> ans = new ArrayList<>(); for (Integer k : segs.keySet()) { ArrayList<Pair> list = segs.get(k); ArrayList<Pair> blocks = new ArrayList<>(); Collections.reverse(list); int prev = inf; for (Pair p : list) { int l = p.a; int r = p.b; if (r < prev) { blocks.add(p); prev = l; } } if (blocks.size() > max) { ans = blocks; max = blocks.size(); } } out.println(ans.size()); for (Pair p : ans) out.println((p.a+1)+" "+(p.b+1)); } class Pair implements Comparable<Pair>{ int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (a != p.a) return Integer.compare(a, p.a); else return Integer.compare(b, p.b); } } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } } static class InputReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public InputReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public InputReader(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(); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(); int r = in.readInt(); int[] x = in.readIntArray(n); double[] y = new double[n]; y[0] = r; for (int i = 1; i < n; i++) { double max = r; for (int j = 0; j < i; j++) { double pow = Math.pow(x[i] - x[j], 2); if (pow <= 4 * r * r) { double ty = y[j] + Math.sqrt(4 * r * r - pow); max = Math.max(max, ty); } } y[i] = max; } for (double i : y) out.print(i + " "); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] readIntArray(int size) { int[] ans = new int[size]; for (int i = 0; i < size; i++) ans[i] = readInt(); return ans; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.System.in; public class Main { public static void main(String[] args)throws IOException{ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] point = new int[n][]; for(int i=0;i<n;i++) point[i] = new int[]{sc.nextInt(),sc.nextInt()}; Arrays.sort(point,(a,b)->((a[0]-a[1])-(b[0]-b[1]))); TreeMap<Integer,Integer> tm = new TreeMap<>(); int ans = 0; for(int i=n-1;i>=0;i--){ int x = point[i][0], w = point[i][1]; Map.Entry<Integer,Integer> cur = tm.ceilingEntry(x+w); int curRes; if(cur==null) curRes = 1; else curRes = cur.getValue()+1; ans = Math.max(ans,curRes); Map.Entry<Integer,Integer> upper = tm.ceilingEntry(x-w); if(upper==null||upper.getValue()<curRes) tm.put(x-w,curRes); //Integer key = tm. } System.out.println(ans); } }
nlogn
528_B. Clique Problem
CODEFORCES
import java.io.*; public class coins { public static void main(String args[])throws IOException { InputStreamReader read=new InputStreamReader(System.in); BufferedReader in=new BufferedReader(read); int i,k,n,v; String a; a=in.readLine(); for(i=0;i<a.length();i++) { if(a.charAt(i)==' ') break; } n=Integer.parseInt(a.substring(0,i)); v=Integer.parseInt(a.substring(i+1)); k=v%n; v=v/n; if(k>0) v++; System.out.println(v); } }
constant
1061_A. Coins
CODEFORCES
import java.io.*; import java.util.*; public class Solution { private BufferedReader in; private PrintWriter out; private StringTokenizer st; void solve() throws IOException { int n = nextInt(); int k = nextInt(); ArrayList<Integer> ps = new ArrayList<Integer>(); boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); prime[0] = prime[1] = false; for (int i = 2; i <= n; ++i) { if (prime[i]) { ps.add(i); for (int j = 2 * i; j <= n; j += i) { prime[j] = false; } } } for (int i = 0; i < ps.size() - 1; ++i) { int t = ps.get(i) + ps.get(i + 1) + 1; if (t <= n && prime[t]) { --k; } } // System.out.println(k); out.println(k <= 0 ? "YES" : "NO"); } Solution() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); solve(); in.close(); out.close(); } private void eat(String str) { st = new StringTokenizer(str); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { new Solution(); } }
linear
17_A. Noldbach problem
CODEFORCES
import java.util.*; public class Main { public static class node implements Comparable<node>{ int l,r; node(){} node(int l,int r) { this.l=l; this.r=r; } @Override public int compareTo(node rhs) { return r-rhs.r; } } public static void main(String args[]){ Scanner in = new Scanner(System.in); int a = in.nextInt(); int x[] = new int[a]; for(int n=0;n<a;n++){ x[n] = in.nextInt(); } int max = 1; int t = 0; HashMap<Integer, ArrayList<node>> map = new HashMap<Integer, ArrayList<node>>(); for(int n=0;n<a;n++){ int num = 0; for(int m=n;m<a;m++){ num += x[m]; node node = new node(n, m); if(!map.containsKey(num)){ ArrayList<node> list = new ArrayList<node>(); list.add(node); map.put(num, list); if(max == 1)t = num; } else{ ArrayList<node> list = map.get(num); int left = 0; int right = list.size()-1; int res = list.size(); while(left <= right){ int mid = (left + right) >> 1; //System.out.println(mid +" "+ left +" " +right); if(list.get(mid).r >= n){ res = mid; right = mid - 1; } else{ left = mid + 1; } } if(res == list.size()){ list.add(node); if(max < res+1){ max = res+1; t = num; } } else if(list.get(res).r>m){ list.set(res, node); if(max < res){ max = list.size(); t = num; } } } } } System.out.println(max); for(int n=0;n<max;n++){ System.out.println((map.get(t).get(n).l+1)+" "+(map.get(t).get(n).r+1)); } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.awt.Point; import java.io.*; import java.text.*; import java.util.*; import java.util.regex.*; public class Main{ static class Run implements Runnable{ //TODO parameters final boolean consoleIO = true; final String inFile = "input.txt"; final String outFile = "output.txt"; Pair<Double,Double>[] p; int n, t; int find() { int count = 2; for(int i = 0; i < n-1; ++i) { double dif = p[i+1].a-p[i].b; int comp = Double.compare(dif,t); if(comp==0) count+=1; else if(comp>0) count+=2; } return count; } @Override public void run() { n = nextInt(); t = nextInt(); p = new Pair[n]; for(int i = 0; i < n; ++i) { int x = nextInt()+1000; int a = nextInt(); double h = a/(double)2; p[i] = new Pair<Double,Double>(x-h,x+h); } Arrays.sort(p, new PComparator()); print(find()); close(); } class PComparator implements Comparator<Pair<Double,Double>> { @Override public int compare(Pair<Double, Double> o1, Pair<Double, Double> o2) { return Double.compare(o1.a, o2.a); } } //========================================================================================================================= BufferedReader in; PrintWriter out; StringTokenizer strTok; Run() { if (consoleIO) { initConsoleIO(); } else { initFileIO(); } } void initConsoleIO() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } void initFileIO() { try { in = new BufferedReader(new FileReader(inFile)); out = new PrintWriter(new FileWriter(outFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } void close() { try { in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } int nextInt() { return Integer.parseInt(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } float nextFloat() { return Float.parseFloat(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } String nextLine() { try { return in.readLine(); } catch (IOException e) { return "__NULL"; } } boolean hasMoreTokens() { return (strTok == null) || (strTok.hasMoreTokens()); } String nextToken() { while (strTok == null || !strTok.hasMoreTokens()) { String line; try { line = in.readLine(); strTok = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return strTok.nextToken(); } void cout(Object o){ System.out.println(o); } void print(Object o) { out.write(o.toString()); } void println(Object o) { out.write(o.toString() + '\n'); } void printf(String format, Object... args) { out.printf(format, args); } String sprintf(String format, Object... args) { return MessageFormat.format(format, args); } } static class Pair<A, B> { A a; B b; A f() { return a; } B s() { return b; } Pair(A a, B b) { this.a = a; this.b = b; } Pair(Pair<A, B> p) { a = p.f(); b = p.s(); } @Override public String toString() { return a+" "+b; } } public static void main(String[] args) throws IOException { Run run = new Run(); Thread thread = new Thread(run); thread.run(); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.*; import java.io.*; public class Contest176B { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); long n = sc.nextLong(); int k = sc.nextInt(); if( ((long)k * (long)(k + 1))/2 - 1 - (k - 2) < n){ System.out.println(-1); return; } if(n == 1) { System.out.println(0); return; } if(n <= k) { System.out.println(1); return; } int ans = rek(2, k, n, k); System.out.println(ans); } private static int rek(int s, int e, long n, int k){ //System.out.println(s + " " + e ); if(s == e){ return k - s + 1; } if(s + 1 == e){ if(sum(e, k) >= n) return k - e + 1; return k - s + 1; } int m = (s + e)/2; long ans = sum(m, k); if(ans == n) return k - m + 1; if(ans < n) return rek(s, m - 1, n, k); else return rek(m , e, n, k); } private static long sum(int a, int b ){ long sum1 = ((long)a * (long)(a - 1))/2; long sum2 = ((long)b * (long)(b + 1))/2; int numelement = b - a + 1; return sum2 - sum1 - (numelement - 1); } }
logn
287_B. Pipeline
CODEFORCES
import java.util.Scanner; public class A235 { public static void main(String[] args) { Scanner in = new Scanner(System.in); long a = in.nextLong(); if (a % 2 == 0) { long result = cal(a); result = Math.max(result, cal(a + 1)); result = Math.max(result, cal2(a)); System.out.println(Math.max(result, a)); } else { long result = (a - 1) * (a - 2) * (a - 0); System.out.println(Math.max(result, a)); } } static long cal(long a) { long result = (a - 1) * (a - 2); result /= gcd(a - 1, a - 2); long gcd = gcd(result, a - 3); result *= (a - 3); result /= gcd; return result; } static long cal2(long a) { long result = (a) * (a - 1); result /= gcd(a - 1, a); long gcd = gcd(result, a - 3); result *= (a - 3); result /= gcd; return result; } private static long gcd(long l, long i) { if (l == 0 || i == 0) { return 1; } if (l % i == 0) { return i; } return gcd(i, l % i); } }
constant
235_A. LCM Challenge
CODEFORCES
import java.io.*; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; import javax.print.attribute.HashAttributeSet; public class CodeForces { public void solve() throws IOException { int n = nextInt(); int arr[]=new int[1000]; arr[0]=0; arr[1]=1; arr[2]=1; if(n==0){ out.print("0 0 0"); } else if(n==1){ out.print("0 0 1"); } else { int c=2; while(arr[c]!=n){ c++; arr[c]=arr[c-1]+arr[c-2]; } out.print(arr[c-2]+" "+arr[c-2]+" "+arr[c-3]); } } public static void main(String[] args) { new CodeForces().run(); } int NOD(int a, int b) { while (a != 0 && b != 0) { if (a >= b) a = a % b; else b = b % a; } return a + b; } BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; boolean isOuterFile = false; public void run() { try { if (isOuterFile) { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } tokenizer = null; // long t=new Date().getTime(); solve(); // writer.println(t-new Date().getTime()); reader.close(); out.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()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
constant
199_A. Hexadecimal's theorem
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 Liavontsi Brechka */ 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); DEhabIEsheOdnaOcherednayaZadachaNaXor solver = new DEhabIEsheOdnaOcherednayaZadachaNaXor(); solver.solve(1, in, out); out.close(); } static class DEhabIEsheOdnaOcherednayaZadachaNaXor { public void solve(int testNumber, InputReader in, PrintWriter out) { int c = 0; int d = 0; int prevSign = 0; int nextSign; boolean zeroOut = true; for (int i = 29; i >= 0; i--) { if (zeroOut) { print(c, d, out); prevSign = read(in); } print((1 << i) | c, (1 << i) | d, out); nextSign = read(in); if (prevSign == nextSign) { zeroOut = false; print((1 << i) | c, d, out); nextSign = read(in); if (nextSign < 0) { c = (1 << i) | c; d = (1 << i) | d; } } else { zeroOut = true; if (nextSign < 0) c = (1 << i) | c; else d = (1 << i) | d; } } out.printf("! %d %d", c, d); out.flush(); } private void print(int c, int d, PrintWriter out) { out.printf("? %d %d\n", c, d); out.flush(); } private int read(InputReader in) { return in.nextInt(); } } static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } public String readLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
logn
1088_D. Ehab and another another xor problem
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class C43 { static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter out = new PrintWriter(System.out); static int nextInt() throws IOException { in.nextToken(); return Integer.valueOf(in.sval); } static double nextDouble() throws IOException { in.nextToken(); return Double.valueOf(in.sval); } static String nextString() throws IOException { in.nextToken(); return in.sval; } static { in.ordinaryChars('0', '9'); in.wordChars('0', '9'); in.ordinaryChars('.', '.'); in.wordChars('.', '.'); in.ordinaryChars('-', '-'); in.wordChars('-', '-'); } public static void main(String[] args) throws IOException { int n = nextInt(); char[] s = nextString().toCharArray(); int h = 0; for (int i = 0; i < n; i++) if (s[i] == 'H') h++; int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int p = i, t = 0; for (int j = 0; j < h; j++, p = (p+1)%n) if (s[p] == 'T') t++; ans = Math.min(ans, t); } out.println(ans); out.flush(); } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; import javafx.util.Pair; public class FireAgain { static Queue q=new LinkedList<>(); static boolean[][] fired; static Pair index = null; public static void main(String[] args) throws IOException { // BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedReader in=new BufferedReader(new FileReader("input.txt")); BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt")); StringTokenizer s = new StringTokenizer(in.readLine()); int n=Integer.parseInt(s.nextToken()); int m=Integer.parseInt(s.nextToken()); fired=new boolean[n][m]; Pair result=null; s = new StringTokenizer(in.readLine()); int firenum=Integer.parseInt(s.nextToken()); s = new StringTokenizer(in.readLine()); int i; ArrayList<Integer> tree=new ArrayList<>(); for(i=0;i<firenum*2;i++){ tree.add(Integer.parseInt(s.nextToken())-1); } for(i=0;i<2*firenum-1;i+=2){ fired[tree.get(i)][tree.get(i+1)]=true; q.add(new Pair(tree.get(i),tree.get(i+1))); } index=(Pair) q.peek(); result=bfs((int)index.getKey(),(int)index.getValue(),n,m); int x1=(int)result.getKey()+1; int x2=(int)result.getValue()+1; String str = x1 + " " + x2; writer.write(str); writer.close(); } public static Pair bfs(int x,int y,int xmax,int ymax){ fired[x][y]=true; while(!q.isEmpty()){ index=(Pair) q.poll(); int i=(int) index.getKey(); int j=(int) index.getValue(); if(i-1>=0){ if(!fired[i-1][j]){ fired[i-1][j]=true; q.add(new Pair((i-1),j)); } }if(j-1>=0){ if(!fired[i][j-1]){ fired[i][j-1]=true; q.add(new Pair(i,(j-1))); } } if(i+1<xmax){ if(!fired[i+1][j]){ fired[i+1][j]=true; q.add(new Pair(i+1,j)); } } if(j+1<ymax){ if(!fired[i][j+1]){ fired[i][j+1]=true; q.add(new Pair(i,j+1)); } } } return index; } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class TaskB implements Runnable { boolean prime[] = new boolean[(int)1e6+10]; InputReader c; PrintWriter w; public void run() { c = new InputReader(System.in); w = new PrintWriter(System.out); char a[] = c.next().toCharArray(), b[] = c.next().toCharArray(); int n = a.length, m = b.length; int[][] prefix = new int[m][2]; for(int i=0;i<m;i++){ if(i!=0) { prefix[i][0] = prefix[i-1][0]; prefix[i][1] = prefix[i-1][1]; } prefix[i][b[i] - '0']++; //w.println(prefix[i][0]+" "+prefix[i][1]); } long res = 0; for(int i=0;i<n;i++){ int temp = a[i] - '0'; res += prefix[m - n + i][temp^1]; if(i!=0) res -= prefix[i-1][temp^1]; } w.println(res); w.close(); } void sieveOfEratosthenes(int n) { for(int i=0;i<n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p] == true) { for(int i = p*p; i <= n; i += p) prime[i] = false; } } } class pair implements Comparable<pair>{ char ch; int ind; @Override public String toString() { return "pair{" + "ch=" + ch + ", ind=" + ind + '}'; } public pair(char ch, int ind) { this.ch = ch; this.ind = ind; } public int compareTo(pair car) { if(this.ch==car.ch) return this.ind - car.ind; return this.ch - car.ch; } } public static void sortbyColumn(int arr[][], int col){ Arrays.sort(arr, new Comparator<int[]>() { public int compare(int[] o1, int[] o2){ return(Integer.valueOf(o1[col]).compareTo(o2[col])); } }); } static long gcd(long a, long b){ if (b == 0) return a; return gcd(b, a % b); } public static class DJSet { public int[] upper; public DJSet(int n) { upper = new int[n]; Arrays.fill(upper, -1); } public int root(int x) { return upper[x] < 0 ? x : (upper[x] = root(upper[x])); } public boolean equiv(int x, int y) { return root(x) == root(y); } public boolean union(int x, int y) { x = root(x); y = root(y); if (x != y) { if (upper[y] < upper[x]) { int d = x; x = y; y = d; } upper[x] += upper[y]; upper[y] = x; } return x == y; } } public static int[] radixSort(int[] f) { int[] to = new int[f.length]; { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i]; int[] d = f; f = to;to = d; } { int[] b = new int[65537]; for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to;to = d; } return f; } public void printArray(int[] a){ for(int i=0;i<a.length;i++) w.print(a[i]+" "); w.println(); } public int[] scanArrayI(int n){ int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = c.nextInt(); return a; } public long[] scanArrayL(int n){ long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = c.nextLong(); return a; } public void printArray(long[] a){ for(int i=0;i<a.length;i++) w.print(a[i]+" "); w.println(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new TaskB(),"TaskB",1<<26).start(); } }
linear
608_B. Hamming Distance Sum
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main implements Runnable { PrintWriter out; BufferedReader in; StringTokenizer st; void solve() throws Exception { int n = nextInt(); int[] a = new int[n]; int sum = 0; for(int i = 0; i < n; ++i) { a[i] = nextInt(); sum += a[i]; } Arrays.sort(a); int ans = 0, csum = 0; for(int i = n - 1; csum <= sum - csum && i >= 0; i--) { csum += a[i]; ans++; } out.println(ans); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // in = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter("output.txt"); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); } } static public void main(String args[]) throws Exception { (new Main()).run(); } int nextInt() { return Integer.parseInt(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } String nextToken() { while(st == null || !st.hasMoreTokens()) { try { String line = in.readLine(); st = new StringTokenizer(line); } catch(Exception e) { return null; } } return st.nextToken(); } }
nlogn
160_A. Twins
CODEFORCES
import java.io.*; import java.util.*; public class Array224B { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int[] array = new int[n]; int[] visited = new int[100002]; st = new StringTokenizer(f.readLine()); for(int i=0;i<n;i++){ array[i] = Integer.parseInt(st.nextToken()); } int count = 0; int begin = array[0]; while(count<n && array[count] == begin){ count++; } count--; int kcount = 1; visited[array[count]]++; int bindex = count; boolean good=true; count++; while(kcount<k){ if(count==n){ System.out.println("-1 -1"); good=false; break; } if(visited[array[count]]==0){ kcount++; } visited[array[count]]++; count++; } if(good&&k!=1){ for(int i=bindex;i<count;i++){ if(visited[array[i]]==1){ break; } bindex++; visited[array[i]]--; } for(int i=count-1;i>bindex;i--){ if(visited[array[i]]==1){ break; } count--; visited[array[i]]--; } } if(k==1){ System.out.println("1 1"); } else if(good){ System.out.println(bindex+1+" "+count); } } }
linear
224_B. Array
CODEFORCES
// Author: aman_robotics //package math_codet; import java.io.*; import java.util.*; public class lets_do { FastReader in; PrintWriter out; Helper_class h; final long mod = 1000000009; final int MAXN = 1000005; final int lgN = 20; final long INF = (long)1e18; final long MAX_Ai = (long)1e12; public static void main(String[] args) throws java.lang.Exception{ new lets_do().run(); } void run() throws Exception{ in=new FastReader(System.in); out = new PrintWriter(System.out); h = new Helper_class(); int t = 1; while(t--> 0) solve(); out.flush(); out.close(); } void solve(){ int n = h.ni(); long[] arr = new long[n]; int i = 0, j = 0; for(i = 0; i < n; i++) arr[i] = h.nl(); HashMap<Long, Integer> hmap = new HashMap<Long, Integer>(); int cnt = 0; for(i = 0; i < n; i++){ long sum = 0; for(j = i; j < n; j++){ sum += arr[j]; Integer x = hmap.get(sum); if(x == null) hmap.put(sum, cnt++); } } TreeSet<Pair>[] tset = new TreeSet[cnt]; for(i = 0; i < cnt; i++) tset[i] = new TreeSet<Pair>(com); for(i = 0; i < n; i++){ long sum = 0; for(j = i; j < n; j++){ sum += arr[j]; tset[hmap.get(sum)].add(new Pair(i, j)); } } int max = 0; int ind = -1; int max_x = 0, max_y = 0; for(i = 0; i < cnt; i++){ int curr_y = tset[i].first().y; int cnt1 = 1; for(Pair yo : tset[i]){ if(yo.x > curr_y) { cnt1++; curr_y = yo.y; } } if(max < cnt1) { max = cnt1; ind = i; } } h.pn(max); Pair hola_yee = new Pair(tset[ind].first().x, tset[ind].first().y); h.pn((tset[ind].first().x + 1) +" "+(tset[ind].first().y + 1)); int curr_y = tset[ind].first().y; for(Pair yo : tset[ind]){ if(yo.x > curr_y) { curr_y = yo.y; h.pn((yo.x + 1) +" "+(yo.y + 1)); } } } static final Comparator<Pair> com=new Comparator<Pair>(){ public int compare(Pair a, Pair b){ if(Integer.compare(a.y, b.y) != 0) return Integer.compare(a.y, b.y); else return Integer.compare(a.x, b.x); } }; class Pair{ int x; int y; Pair(int p, int q){ x = p; y = q; } } class Edge{ int u , v; long wt; Edge(int a, int b, long w){ u = a; v = b; wt = w; } int other(int x) { return u ^ v ^ x; } } class Helper_class{ long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bitcount(long n){return (n==0)?0:(1+bitcount(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n(){return in.next();} String nln(){return in.nextLine();} int ni(){return Integer.parseInt(in.next());} long nl(){return Long.parseLong(in.next());} double nd(){return Double.parseDouble(in.next());} long mul(long a,long b){ if(a>=mod)a%=mod; if(b>=mod)b%=mod; a*=b; if(a>=mod)a%=mod; return a; } long modPow(long a, long p){ long o = 1; while(p>0){ if((p&1)==1)o = mul(o,a); a = mul(a,a); p>>=1; } return o; } long add(long a, long b){ if(a>=mod)a%=mod; if(b>=mod)b%=mod; if(b<0)b+=mod; a+=b; if(a>=mod)a-=mod; return a; } } class FastReader{ private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public void skip(int x) { while (x-- > 0) read(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextString() { return next(); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean hasNext() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value != -1; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
quadratic
1141_F2. Same Sum Blocks (Hard)
CODEFORCES
import java.io.*; import java.util.*; public class E implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int t = scn.nextInt(); while(t-- > 0) { int n = scn.nextInt(), m = scn.nextInt(); int[][] arr = scn.next2DInt(n, m); int[][] col = new int[m][2]; for(int j = 0; j < m; j++) { int max = 0; for(int i = 0; i < n; i++) { max = Math.max(max, arr[i][j]); } col[j][0] = max; col[j][1] = j; } Arrays.parallelSort(col, (o1, o2) -> o2[0] - o1[0]); int take = Math.min(n, m); int[][] lol = new int[n][take]; for(int j = 0; j < take; j++) { for(int i = 0; i < n; i++) { lol[i][j] = arr[i][col[j][1]]; } } ans = 0; func(lol, 0); out.println(ans); } } int ans = 0; void func(int[][] arr, int col) { int n = arr.length, m = arr[0].length; if(col == m) { int rv = 0; for(int i = 0; i < n; i++) { int mx = 0; for(int j = 0; j < m; j++) { mx = Math.max(mx, arr[i][j]); } rv += mx; } ans = Math.max(ans, rv); return; } for(int rot = 0; rot < n; rot++) { int f = arr[0][col]; for(int j = 1; j < n; j++) { arr[j - 1][col] = arr[j][col]; } arr[n - 1][col] = f; func(arr, col + 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 E(), "Main", 1 << 26).start(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); int c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } long[] shuffle(long[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); long c = arr[i]; arr[i] = arr[j]; arr[j] = c; } return arr; } int[] uniq(int[] arr) { arr = scn.shuffle(arr); Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } long[] uniq(long[] arr) { arr = scn.shuffle(arr); Arrays.sort(arr); long[] rv = new long[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } int[] reverse(int[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } long[] reverse(long[] arr) { int l = 0, r = arr.length - 1; while (l < r) { arr[l] = arr[l] ^ arr[r]; arr[r] = arr[l] ^ arr[r]; arr[l] = arr[l] ^ arr[r]; l++; r--; } return arr; } int[] compress(int[] arr) { int n = arr.length; int[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } long[] compress(long[] arr) { int n = arr.length; long[] rv = Arrays.copyOf(arr, n); rv = uniq(rv); for (int i = 0; i < n; i++) { arr[i] = Arrays.binarySearch(rv, arr[i]); } return arr; } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.util.*; import java.io.*; public class F531 { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int m = sc.nextInt(); long [][] mn1 = new long[n][n]; long [][] mn2 = new long[n][n]; long [][] grid = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) grid[i][j] = sc.nextInt(); } if (n == 1) { long ans = Integer.MAX_VALUE; for (int i = 0; i < m - 1; i++) ans = Math.min(ans, Math.abs(grid[0][i] - grid[0][i + 1])); out.println(ans); out.close(); return; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; long min = Long.MAX_VALUE; for (int k = 0; k < m; k++) min = Math.min(min, Math.abs(grid[i][k] - grid[j][k])); mn1[i][j] = min; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; long min = Long.MAX_VALUE; for (int k = 0; k < m - 1; k++) min = Math.min(min, Math.abs(grid[i][k] - grid[j][k + 1])); mn2[i][j] = min; } } long [][] dp = new long[1 << n][n]; // start vertex long ans = 0; for (int i = 0; i < n; i++) { for (long [] a: dp) Arrays.fill(a, -1); for (int j = 0; j < n; j++) { if (j == i) dp[1 << j][j] = Long.MAX_VALUE; else dp[1 << j][j] = 0; } for (int mask = 1; mask < (1 << n); mask++) { for (int last = 0; last < n; last++) { if (dp[mask][last] != -1) continue; for (int prev = 0; prev < n; prev++) { if (prev == last) continue; if (((mask >> prev) & 1) == 1) { dp[mask][last] = Math.max(dp[mask][last], Math.min(mn1[prev][last], dp[mask ^ (1 << last)][prev])); } } } } // end vertex for (int j = 0; j < n; j++) { // step from the last vertex to the first long end = mn2[j][i]; ans = Math.max(ans, Math.min(dp[(1 << n) - 1][j], end)); } } out.println(ans); out.close(); } //-----------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
1102_F. Elongated Matrix
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { FastScanner in = new FastScanner(System.in); // FastScanner in = new FastScanner(new File("test.txt")); PrintWriter out = new PrintWriter(System.out); public static void main (String[]args) { Main task = new Main(); task.solve(); task.close(); } public void close () { in.close(); out.close(); } public void solve() { int n = in.nextInt(); int k = in.nextInt(); Team[]teams = new Team[n]; for (int i = 0; i < n; i++) { Team t = new Team(); t.tasks = in.nextInt(); t.penalty = in.nextInt(); teams[i] = t; } Arrays.sort(teams); Team t = teams[k - 1]; int ans = 0; for (int i = 0; i < teams.length; i++) { if (teams[i].equals(t)) ans++; } System.out.println(ans); } class Team implements Comparable<Team>{ int tasks; int penalty; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + penalty; result = prime * result + tasks; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Team other = (Team) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (penalty != other.penalty) return false; if (tasks != other.tasks) return false; return true; } @Override public int compareTo(Team o) { if (this.tasks > o.tasks) return -1; else if (this.tasks == o.tasks) { if (this.penalty <= o.penalty) return -1; else return 1; } else return 1; } private Main getOuterType() { return Main.this; } } public int max (int a, int b) { if (a > b) return a; else return b; } } class Algebra { /**** * Number of co-prime numbers on [1, n]. * Number a is Co-prime if gcd (a, n) == 1 * O (sqrt(n)) ****/ public static int phi(int n) { int result = n; for (int i = 2; i*i <= n; ++i) { if (n % i == 0) { while (n % i == 0) { n /= i; } result -= result / i; } } if (n > 1) { result -= result / n; } return result; } /**** * Raise number a to power of n. * O (log n) ****/ public static int binpow (int a, int n) { int res = 1; while (n != 0) { if ((n & 1) == 1) res *= a; a *= a; n >>= 1; } return res; } /**** * Finding the greatest common divisor of two numbers. * O (log min(a, b)) ****/ public static int gcd (int a, int b) { return (b != 0) ? gcd (b, a % b) : a; } /**** * Finding the lowest common multiple of two numbers. * O (log min(a, b)) ****/ public static int lcm (int a, int b) { return a / gcd (a, b) * b; } /**** * Eratosthenes Sieve of numbers - [0..n]. True - simple, False - not simple. * O (n log log n) ****/ public static boolean[] sieveOfEratosthenes (int n) { boolean [] prime = new boolean[n + 1]; Arrays.fill(prime, true); prime[0] = prime[1] = false; for (int i=2; i<=n; ++i) { if (prime[i]) { if (i * 1L * i <= n) { for (int j=i*i; j<=n; j+=i) { prime[j] = false; } } } } return prime; } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { System.err.println(e); return ""; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } BigInteger nextBigInt() { return new BigInteger(next()); } void close() { try { br.close(); } catch (IOException e) { } } }
nlogn
166_A. Rank List
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.StringTokenizer; public class Quiz { public static long pow(long base, long power) { if (power == 0) return 1; long half = pow(base, power / 2) % mod; half *= half; half %= mod; if (power % 2 == 1) half *= base; return half % mod; } static long mod = (long) (1e9 + 9); public static void main(String[] args) { InputReader r = new InputReader(System.in); int n = r.nextInt(); int m = r.nextInt(); int k = r.nextInt(); int buckets = n / k; int rem = n - buckets * k; long low = 0, high = buckets, itr = 30; while (itr-- > 0) { long mid = (low + high) / 2; long correct = mid * k + rem + (buckets - mid) * (k - 1); if (correct < m) low = mid; else high = mid; } long pow = (pow(2, high + 1) - 2 + mod) % mod; pow *= k; pow %= mod; long res = m - (high * k) + pow + 10 * mod; res %= mod; System.out.println(res); } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public InputReader(FileReader stream) { reader = new BufferedReader(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()); } } }
logn
338_A. Quiz
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author kessido */ 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); BTheHat solver = new BTheHat(); solver.solve(1, in, out); out.close(); } static class BTheHat { PrintWriter out; InputReader in; int n; public void solve(int testNumber, InputReader in, PrintWriter out) { this.out = out; this.in = in; n = in.NextInt(); int desiredPair = -1; int result = query(1); if (result != 0) { int l = 2, r = 1 + n / 2; while (l < r) { int m = (l + r) / 2; int mRes = query(m); if (mRes == 0) { desiredPair = m; break; } else if (mRes == result) { l = m + 1; } else { r = m; } } } else { desiredPair = 1; } out.println("! " + desiredPair); } private int query(int i) { int iV = queryValue(i); int iN2V = queryValue(i + n / 2); if (iV < iN2V) { return -1; } else if (iV > iN2V) { return 1; } return 0; } private int queryValue(int i) { out.println("? " + i); out.flush(); return in.NextInt(); } } static class InputReader { BufferedReader reader; 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(), " \t\n\r\f,"); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int NextInt() { return Integer.parseInt(next()); } } }
logn
1019_B. The hat
CODEFORCES
//package round22; import java.io.PrintWriter; import java.io.StringReader; import java.util.Arrays; import java.util.Scanner; public class A { private Scanner in; private PrintWriter out; // private String INPUT = "5 1 2 3 1 1"; private String INPUT = ""; public void solve() { int n = ni(); int[] a = new int[n]; for(int i = 0;i < n;i++){ a[i] = ni(); } Arrays.sort(a); for(int i = 1;i < n;i++){ if(a[i] > a[i - 1]){ out.println(a[i]); return; } } out.println("NO"); } public void run() throws Exception { in = INPUT.isEmpty() ? new Scanner(System.in) : new Scanner(new StringReader(INPUT)); out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new A().run(); } private int ni() { return Integer.parseInt(in.next()); } private static void tr(Object... o) { System.out.println(o.length == 1 ? o[0] : Arrays.toString(o)); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.io.*; import java.util.*; import java.lang.*; public class Main{ static InputReader sc; static PrintWriter pw; public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; sc = new InputReader(inputStream); pw = new PrintWriter(outputStream); solve(); pw.close(); } // static int L,R,top,bottom; // static int cnt,edge; // static long ans; public static void solve() { // int t=sc.nextInt(); int t=1; u:while(t-->0){ int n=s(0); int m=s(0); int k=s(0); long [][][]arr=new long [n][m][4]; for(int i=0;i<n;i++){ for(int j=0;j<m-1;j++){ long v=s(0l); arr[i][j][0]=v; arr[i][j+1][2]=v; } } for(int i=0;i<n-1;i++){ for(int j=0;j<m;j++){ long v=s(0l); arr[i][j][1]=v; arr[i+1][j][3]=v; } } Long [][][]dp=new Long [n][m][k+1]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++) for(int p=1;p<=k;p++) helper(i,j,p,dp,arr,n,m); } for(int i=0;i<n;i++){ for(int j=0;j<m;j++) p(dp[i][j][k]+" "); pln(""); } } } static int [][]dir=new int [][]{{0,1},{1,0},{0,-1},{-1,0}}; public static long helper(int i, int j, int k, Long [][][]dp, long [][][]arr, int n, int m){ if(k<0) return -1; if(k==0) return 0; if(dp[i][j][k]!=null) return dp[i][j][k]; int x, y; long ans=Long.MAX_VALUE,val; for(int d=0;d<4;d++){ x=i+dir[d][0]; y=j+dir[d][1]; if(x<0||x>=n||y<0||y>=m) continue; val=helper(x,y,k-2,dp,arr,n,m); if(val!=-1) ans=Math.min(ans,val+2*arr[i][j][d]); } return dp[i][j][k]=(ans==Long.MAX_VALUE?-1:ans); } public static int find(List<Integer> list, int x){ int l=0,r=list.size()-1,m; while(l<=r){ m=(r-l)/2+l; if(list.get(m)<=x) l=m+1; else r=m-1; } return r; } static class Node{ int val; long cost; Node next; Node(int v,long c){ val=v; next=null; cost=c; } } public static long sum(long n){ long val=0l; while(n>0){ val+=n%10; n/=10; } return val; } // static class Node{ // int left,right; // Node prev,next; // Node(int i, int v){ // left=i; // right=v; // prev=next=null; // } // void remove(){ // this.prev.next=this.next; // this.next.prev=this.prev; // } // void insert(Node node){ // node.next=this; // node.prev=this.prev; // node.prev.next=node; // this.prev=node; // } // } public static int findDiameter(int r, List<List<Integer>>list){ return findFarthest(findFarthest(r,list)[0],list)[1]; } public static int[] findFarthest(int u, List<List<Integer>>list){ int n=list.size(); boolean []vis=new boolean[n+1]; Queue<Integer>q=new LinkedList<>(); q.offer(u); vis[u]=true; int s,pr,cnt=0; int []ar=new int[]{u,0}; while(q.size()>0){ s=q.size(); while(s-->0){ pr=q.poll(); if(ar[1]<cnt){ ar[1]=cnt; ar[0]=pr; } for(int i:list.get(pr)){ if(!vis[i]){ vis[i]=true; q.offer(i); } } } cnt++; } return ar; } public static long atMostK(char []chrr, int k){ if(k<0) return 0; int l=0,cnt=0; long ans=0l; for(int i=0;i<chrr.length;i++){ if(chrr[i]=='1') cnt++; while(cnt>k){ if(chrr[l++]=='1') cnt--; } ans+=(long)(i-l)+1l; } return ans; } public static int ask(int l){ System.out.println(l); System.out.flush(); return sc.nextInt(); } public static void sort(long []arr){ ArrayList<Long> list=new ArrayList<>(); for(int i=0;i<arr.length;i++) list.add(arr[i]); Collections.sort(list); for(int i=0;i<arr.length;i++) arr[i]=list.get(i); } public static void swap(char []chrr, int i, int j){ char temp=chrr[i]; chrr[i]=chrr[j]; chrr[j]=temp; } public static int countSetBits(long n){ int a=0; while(n>0){ a+=(n&1); n>>=1; } return a; } static class Pair{ int v,w; Pair(int V, int W){ v=V; w=W; } //* } /*/ public int compareTo(Pair p){ return (b-p.b); } public int hashCode(){ int hashcode = (a+" "+b).hashCode(); return hashcode; } public boolean equals(Object obj){ if (obj instanceof Pair) { Pair p = (Pair) obj; return (p.a==this.a && p.b == this.b); } return false; } } //*/ static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (b == 0) return a; return a>b?gcd(b, a % b):gcd(a, b % a); } static long fast_pow(long base,long n,long M){ if(n==0) return 1; if(n==1) return base; long halfn=fast_pow(base,n/2,M); if(n%2==0) return ( halfn * halfn ) % M; else return ( ( ( halfn * halfn ) % M ) * base ) % M; } static long modInverse(long n,long M){ return fast_pow(n,M-2,M); } public static int s(int n){ return sc.nextInt(); } public static long s(long n){ return sc.nextLong(); } public static String s(String n){ return sc.next(); } public static double s(double n){ return sc.nextDouble(); } public static void p(int n){ pw.print(n); } public static void p(long n){ pw.print(n); } public static void p(String n){ pw.print(n); } public static void p(double n){ pw.print(n); } public static void pln(int n){ pw.println(n); } public static void pln(long n){ pw.println(n); } public static void pln(String n){ pw.println(n); } public static void pln(double n){ pw.println(n); } public static void feedArr(long []arr){ for(int i=0;i<arr.length;i++) arr[i]=sc.nextLong(); } public static void feedArr(double []arr){ for(int i=0;i<arr.length;i++) arr[i]=sc.nextDouble(); } public static void feedArr(int []arr){ for(int i=0;i<arr.length;i++) arr[i]=sc.nextInt(); } public static void feedArr(String []arr){ for(int i=0;i<arr.length;i++) arr[i]=sc.next(); } public static String printArr(int []arr){ StringBuilder sbr=new StringBuilder(); for(int i:arr) sbr.append(i+" "); return sbr.toString(); } public static String printArr(long []arr){ StringBuilder sbr=new StringBuilder(); for(long i:arr) sbr.append(i+" "); return sbr.toString(); } public static String printArr(String []arr){ StringBuilder sbr=new StringBuilder(); for(String i:arr) sbr.append(i+" "); return sbr.toString(); } public static String printArr(double []arr){ StringBuilder sbr=new StringBuilder(); for(double i:arr) sbr.append(i+" "); return sbr.toString(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long k = in.nextLong(); long[] a = new long[n]; for (int i=0; i<n; i++) a[i] = in.nextInt(); Arrays.sort( a ); boolean[] ok = new boolean[ n ]; Arrays.fill( ok, true ); if (k > 1) for (int i=0; i<n; i++) { if ( ok[i] == false ) continue; int pos = Arrays.binarySearch( a, a[i]*k ); if ( pos >= 0 ) { //out.println( a[i]+" "+a[pos] ); ok[ pos ] = false; } } int ans = 0; for (boolean x : ok) if ( x ) ans++; 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 int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
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.Arrays; 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; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); boolean[] dead = new boolean[n]; int ans = 0; for (int i = 0; i < n; i++) { if (dead[i]) { continue; } ++ans; for (int j = i; j < n; j++) { if (a[j] % a[i] == 0) { dead[j] = true; } } } out.println(ans); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.math.BigInteger; public class C { private static Solver solver = new Solver(); private static long m = 1000000000L + 7L; public static void main(String[] args) throws IOException { solver.withProcedure(() -> { String[] input = solver.readString().split(" "); BigInteger x = new BigInteger(input[0]); BigInteger k = new BigInteger(input[1]); if (x.compareTo(BigInteger.ZERO) == 0) { solver.println("" + 0); return; } BigInteger two = BigInteger.valueOf(2); BigInteger mm = BigInteger.valueOf(m); BigInteger binpowedK = two.modPow(k, mm); BigInteger binpowedKPlusOne = two.modPow(k.add(BigInteger.ONE), mm); BigInteger res = binpowedKPlusOne.multiply(x).subtract(binpowedK.subtract(BigInteger.ONE)).mod(mm); if (res.compareTo(BigInteger.ZERO) < 0) { res = BigInteger.ZERO; } solver.println("" + res); }).solve(); } private static long binpow(long a, long n) { a = a % m; long res = 1L; while (n > 0) { if ((n & 1L) != 0) res = (res * a) % m; a = (a * a) % m; n >>= 1L; } return res; } @FunctionalInterface private interface Procedure { void run() throws IOException; } private static class Solver { private Procedure procedure; private StreamTokenizer in; private PrintWriter out; private BufferedReader bufferedReader; Solver() { try { boolean oj = System.getProperty("ONLINE_JUDGE") != null; Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt"); Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt"); bufferedReader = new BufferedReader(reader); in = new StreamTokenizer(bufferedReader); out = new PrintWriter(writer); } catch (Exception e) { throw new RuntimeException("Initialization has failed"); } } void solve() throws IOException { procedure.run(); } int readInt() throws IOException { in.nextToken(); return (int) in.nval; } long readLong() throws IOException { in.nextToken(); return (long) in.nval; } String readString() throws IOException { return bufferedReader.readLine(); } char readChar() throws IOException { in.nextToken(); return in.sval.charAt(0); } void println(String str) { out.println(str); out.flush(); } void print(String str) { out.print(str); out.flush(); } Solver withProcedure(Procedure procedure) { this.procedure = procedure; return this; } } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public int mod = 1000000007; public int MAXN = 333; public int[][] w1; public long[] fact; public long[] ifact; public void solve(int testNumber, InputReader in, OutputWriter out) { long[][] e = Factorials.getFIF(MAXN, mod); fact = e[0]; ifact = e[1]; w1 = new int[MAXN][MAXN]; w1[0][0] = 1; for (int i = 1; i < MAXN; i++) { for (int j = 1; j < MAXN; j++) { for (int k = 1; k <= i; k++) { w1[i][j] += w1[i - k][j - 1]; if (w1[i][j] >= mod) w1[i][j] -= mod; } } } int n = in.nextInt(); int[] arr = in.readIntArray(n); boolean[] marked = new boolean[n]; int[] fs = new int[n]; int fidx = 0; for (int i = 0; i < n; i++) { if (marked[i]) continue; int count = 0; for (int j = 0; j < n; j++) { if (isSquare(1L * arr[i] * arr[j])) { if (marked[j]) System.exit(1); marked[j] = true; count++; } } fs[fidx++] = count; } fs = Arrays.copyOf(fs, fidx); long x = 1; for (int j : fs) x = x * fact[j] % mod; x = x * solve(fs) % mod; out.println(x); } public boolean isSquare(long x) { long d = (long) (Math.sqrt(x)); while (d * d < x) d++; while (d * d > x) d--; return d * d == x; } public int solve(int[] freq) { int d = AUtils.sum(freq); int b = AUtils.max(freq); if (d == 0) return 1; if (b + b - 1 > d) return 0; int[] dp = new int[1]; dp[0] = 1; for (int j = 0; j < freq.length; j++) { if (freq[j] == 0) continue; int[] nxt = new int[dp.length + freq[j]]; for (int pgr = 0; pgr < dp.length; pgr++) { for (int cgr = 1; cgr <= freq[j]; cgr++) { nxt[pgr + cgr] += 1L * dp[pgr] * w1[freq[j]][cgr] % mod * ifact[cgr] % mod; if (nxt[pgr + cgr] >= mod) nxt[pgr + cgr] -= mod; } } dp = nxt; } int res = 0; for (int i = 0; i < dp.length; i++) { long x = 1L * dp[i] * fact[i] % mod; if ((d - i) % 2 == 0) res += x; else res -= x; if (res >= mod) res -= mod; if (res < 0) res += mod; } return res; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int tokens) { int[] ret = new int[tokens]; for (int i = 0; i < tokens; i++) { ret[i] = nextInt(); } return ret; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class AUtils { public static int max(int[] arr) { int res = arr[0]; for (int x : arr) res = Math.max(res, x); return res; } public static int sum(int[] arr) { int sum = 0; for (int x : arr) { sum += x; } return sum; } } static class Factorials { public static long[][] getFIF(int max, int mod) { long[] fact = new long[max]; long[] ifact = new long[max]; long[] inv = new long[max]; inv[1] = 1; for (int i = 2; i < max; i++) { inv[i] = (mod - mod / i) * inv[mod % i] % mod; } fact[0] = 1; ifact[0] = 1; for (int i = 1; i < max; i++) { fact[i] = fact[i - 1] * i % mod; ifact[i] = ifact[i - 1] * inv[i] % mod; } return new long[][]{fact, ifact, inv}; } } 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); } } }
cubic
840_C. On the Bench
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class D { private void solve() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(), m = nextInt(); boolean[][] used = new boolean[n + 1][m + 1]; for (int j = 1; j <= (m + 1) / 2; j++) { int x1 = 1, x2 = n; for (int i = 1; i <= n; i++) { if (x1 <= n && !used[x1][j]) { out.println(x1 + " " + j); used[x1++][j] = true; } if (x2 > 0 && !used[x2][m - j + 1]) { out.println(x2 + " " + (m - j + 1)); used[x2--][m - j + 1] = true; } } } out.close(); } public static void main(String[] args) { new D().solve(); } private BufferedReader br; private StringTokenizer st; private PrintWriter out; private String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } return st.nextToken(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } }
quadratic
1179_B. Tolik and His Uncle
CODEFORCES
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.util.Scanner; /** * * @author 111 */ public class JavaApplication4 { /** * @param args the command line arguments */ static long k, n, ans; static private long binsearch(long l, long r) { if(l==r) return l; long m=(l+r)/2; long res=(m*(k+k-m+1)/2); if(res>=n) return binsearch(l, m); else return binsearch(m+1, r); } public static void main(String[] args) { Scanner in=new Scanner(System.in); n=in.nextLong(); k=in.nextLong(); n--; k--; if(k*(k+1)/2<n) ans=-1; else ans=binsearch(0, k); System.out.println(ans); } }
logn
287_B. Pipeline
CODEFORCES
import java.util.*; import java.io.*; public class Main implements Runnable { private void solution() throws IOException { int n = in.nextInt(); int m = in.nextInt(); boolean[][] adj = new boolean[n][n]; long res = 0; for (int i = 0; i < m; ++i) { int x = in.nextInt(); int y = in.nextInt(); adj[x - 1][y - 1] = true; adj[y - 1][x - 1] = true; } for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (adj[i][j]) { --res; } } } for (int i = 0; i < n; ++i) { long[][] dp = new long[n - i][1 << (n - i)]; dp[0][0] = 1; for (int mask = 0; mask < (1 << (n - i)); ++mask) { for (int j = 0; j < n - i; ++j) { if (dp[j][mask] != 0) { for (int k = 0; k < n - i; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) { dp[k][mask | (1 << k)] += dp[j][mask]; } } } } if (((mask >> 0) & 1) != 0) { res += dp[0][mask]; } } } out.println(res / 2); } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private class Scanner { BufferedReader reader; StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""); } public boolean hasNext() throws IOException { while (!tokenizer.hasMoreTokens()) { String next = reader.readLine(); if (next == null) { return false; } tokenizer = new StringTokenizer(next); } return true; } public String next() throws IOException { hasNext(); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""); return reader.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static void main(String[] args) throws IOException { new Thread(null, new Main(), "", 1 << 28).start(); } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Scanner in = new Scanner(new InputStreamReader(System.in)); }
np
11_D. A Simple Task
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main{ public static void main(String[] Args) throws Exception { Scanner sc = new Scanner(new FileReader("input.txt")); int n,m,k; Integer lx,ly; boolean d[][]; n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt(); d = new boolean [n+1][m+1]; for(int i=0;i<=n;++i) for(int j=0;j<=m;++j) d[i][j]=false; Queue< pair > q = new LinkedList< pair >(); lx = ly = -1; for(int i=0;i<k;++i){ int x,y; x = sc.nextInt(); y = sc.nextInt(); q.add(new pair(x,y)); lx = x; ly = y; d[x][y]=true; } int dx [] = {0,0,1,-1}; int dy [] = {-1,1,0,0}; while(!q.isEmpty()){ pair tp = q.remove(); int x = tp.x; int y = tp.y; for(int i=0;i<4;++i){ int nx = x+dx[i]; int ny = y+dy[i]; if(nx<1 || nx>n || ny<1 || ny>m || d[nx][ny] ) continue; d[nx][ny]=true; q.add(new pair(nx,ny)); lx = nx; ly = ny; } } FileWriter fw = new FileWriter("output.txt"); fw.write(lx.toString()); fw.write(" "); fw.write(ly.toString());; fw.flush(); } } class pair { public int x,y; public pair(int _x,int _y){ x = _x; y = _y; } }
cubic
35_C. Fire Again
CODEFORCES
// practice with kaiboy, coached by rainboy import java.io.*; import java.util.*; public class CF1515E extends PrintWriter { CF1515E() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1515E o = new CF1515E(); o.main(); o.flush(); } void main() { int n = sc.nextInt(); int md = sc.nextInt(); int k = (n + 1) / 2; int[][] dp = new int[k + 1][n + 1]; dp[0][0] = 1; for (int h = 1; h <= k; h++) for (int l = h; l <= n - h + 1; l++) dp[h][l] = (int) ((dp[h][l - 1] * 2L + dp[h - 1][l - 1]) * h % md); int ans = 0; for (int h = 1; h <= k; h++) ans = (ans + dp[h][n - h + 1]) % md; println(ans); } }
cubic
1515_E. Phoenix and Computers
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 Rustam Musin (PloadyFree@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { int n; double k; boolean[][] g; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.readInt(); k = in.readInt(); g = new boolean[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { g[i][j] = in.readInt() == 1; } } double answer = solve(); out.printFormat("%.20f", answer); } private double solve() { int firstPartSize = g.length / 2; int secondPartSize = g.length - firstPartSize; int[] firstPart = findMaxCliqueSize(firstPartSize); int m1Full = (1 << firstPartSize) - 1; int maxCliqueSize = 1; for (int m = 0; m < 1 << secondPartSize; m++) { if (isClique(secondPartSize, m, firstPartSize)) { int m1 = m1Full; for (int j = 0; j < secondPartSize; j++) { if (bit(m, j)) { for (int i = 0; i < firstPartSize; i++) { if (bit(m1, i) && !g[i][j + firstPartSize]) { m1 ^= 1 << i; } } } } int firstCliqueSize = firstPart[m1]; int secondCliqueSize = Integer.bitCount(m); int curCliqueSize = firstCliqueSize + secondCliqueSize; if (curCliqueSize > maxCliqueSize) { maxCliqueSize = curCliqueSize; } } } return k * k * (maxCliqueSize - 1) / (2 * maxCliqueSize); } private int[] findMaxCliqueSize(int size) { int[] dp = new int[1 << size]; for (int m = 1; m < 1 << size; m++) { if (isClique(size, m, 0)) { dp[m] = Integer.bitCount(m); } } for (int m = 1; m < 1 << size; m++) { for (int i = 0; i < size; i++) { if ((m >> i & 1) == 0) { dp[m | (1 << i)] = Math.max(dp[m | (1 << i)], dp[m]); } } } return dp; } private boolean isClique(int size, int m, int offset) { for (int i = 0; i < size; i++) { if (bit(m, i)) { for (int j = i + 1; j < size; j++) { if (bit(m, j) && !g[i + offset][j + offset]) { return false; } } } } return true; } private boolean bit(int m, int b) { return (m >> b & 1) != 0; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void printFormat(String format, Object... objects) { writer.printf(format, objects); } public void close() { writer.close(); } } }
np
839_E. Mother of Dragons
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static MyScanner scan; static PrintWriter pw; public static void main(String[] args) { new Thread(null,null,"_",1<<25) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws IOException { scan = new MyScanner(); pw = new PrintWriter(System.out, true); StringBuilder sb = new StringBuilder(); Map<String,Integer> map = new HashMap<>(); map.put("M",0); map.put("L",1); map.put("S",2); map.put("XL",3); map.put("XS",4); map.put("XXL",5); map.put("XXS",6); map.put("XXXL",7); map.put("XXXS",8); int freqa[] = new int[9]; int freqb[] = new int[9]; int n = ni(); for(int i=0;i<n;++i) ++freqa[map.get(ne())]; for(int i=0;i<n;++i) ++freqb[map.get(ne())]; for(int i=0;i<9;++i) { int xx = min(freqa[i],freqb[i]); freqa[i]-=xx; freqb[i]-=xx; } long res = 0; for(int i=0;i<9;++i) res+=freqa[i]+freqb[i]; pl(res/2); pw.flush(); pw.close(); } static long MMI(long A,long MOD) { return modpow(A,MOD-2,MOD); } static long modpow(long x,long y,long MOD) { if(y==0) return 1; if((y&1)==0) return modpow((x*x)%MOD,y>>1,MOD); else return (x*modpow(x,y-1,MOD))%MOD; } static class Pair implements Comparable<Pair> { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(Pair other) { if(this.x!=other.x) return this.x-other.x; return this.y-other.y; } public String toString() { return "{"+x+","+y+"}"; } } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static String ne() throws IOException { return scan.next(); } static String nel() throws IOException { return scan.nextLine(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextLine()throws IOException { return br.readLine(); } String next() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
// Change Of Plans BABY.... Change Of Plans // import java.io.*; import java.util.*; import java.util.Queue; import static java.lang.Math.*; public class digitSequence { static void MainSolution() { long k = nl() - 1; for (int i = 1; ; i++) { long temp=9L*i*fastPow(10,i-1); if(k<temp){ long x=k/i; long y=k%i; long ans=(x+fastPow(10,i-1))/fastPow(10,i-y-1); pl(ans%10); break; } k-=temp; } } static long fastPow(long b, long e) { if (e == 0) return 1; if ((e & 1) == 1) return b * fastPow(b, e >> 1) * fastPow(b, e >> 1); return fastPow(b, e >> 1) * fastPow(b, e >> 1); } /*----------------------------------------------------------------------------------------------------------------*/ //THE DON'T CARE ZONE BEGINS HERE...\\ static int mod9 = 1_000_000_007; static int n, m, l, k, t; static AwesomeInput input = new AwesomeInput(System.in); static PrintWriter pw = new PrintWriter(System.out, true); // The Awesome Input Code is a fast IO method // static class AwesomeInput { private InputStream letsDoIT; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private AwesomeInput(InputStream incoming) { this.letsDoIT = incoming; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = letsDoIT.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } private long ForLong() { 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; } private String ForString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } // functions to take input// static int ni() { return (int) input.ForLong(); } static String ns() { return input.ForString(); } static long nl() { return input.ForLong(); } static double nd() throws IOException { return Double.parseDouble(new BufferedReader(new InputStreamReader(System.in)).readLine()); } //functions to give output static void pl() { pw.println(); } static void p(Object o) { pw.print(o + " "); } static void pws(Object o) { pw.print(o + ""); } static void pl(Object o) { pw.println(o); } // Fast Sort is Radix Sort public static int[] fastSort(int[] f) { int n = f.length; int[] to = new int[n]; { int[] b = new int[65537]; for (int i = 0; i < n; i++) b[1 + (f[i] & 0xffff)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < n; i++) to[b[f[i] & 0xffff]++] = f[i]; int[] d = f; f = to; to = d; } { int[] b = new int[65537]; for (int i = 0; i < n; i++) b[1 + (f[i] >>> 16)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < n; i++) to[b[f[i] >>> 16]++] = f[i]; int[] d = f; f = to; to = d; } return f; } public static void main(String[] args) { //threading has been used to increase the stack size. new Thread(null, null, "Vengeance", 1 << 25) //the last parameter is stack size desired. { public void run() { try { double s = System.currentTimeMillis(); MainSolution(); //pl(("\nExecution Time : " + ((double) System.currentTimeMillis() - s) / 1000) + " s"); pw.flush(); pw.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
/* * * @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya) * Dhirubhai Ambani Institute of Information And Communication Technology * */ import java.util.*; import java.io.*; import java.lang.*; public class Code3 { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(); double r = (double)in.nextInt(); double [] a = new double[n]; for(int i=0;i<n;i++) a[i] = (double)in.nextInt(); double[] ans = new double[n]; ans[0] = r; for(int i=1;i<n;i++) { double max = Double.MIN_VALUE; for(int j=0;j<i;j++) { if(Math.abs(a[i]-a[j])<=2*r) { //System.out.println(j); double cur = 4*r*r; cur -= ((a[i]-a[j])*(a[i]-a[j])); cur = Math.sqrt(cur); cur += ans[j]; //System.out.println(r); max = Math.max(max, cur); } } if(max == Double.MIN_VALUE) ans[i] = r; else ans[i] = max; } for(int i=0;i<n;i++) pw.print(ans[i] + " "); pw.flush(); pw.close(); } 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 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); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ static ArrayList a[]=new ArrayList[200001]; static int Count(int a[][],int n) { dsu d=new dsu(n); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(a[i][j]==0) { d.union(i, j); } } } int cnt=0; boolean chk[]=new boolean [n]; for(int i=0;i<n;i++) { int p=d.root(i); if(!chk[p]) { chk[p]=true; cnt++; } } return cnt; } public void solve () { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n=in.nextInt(); int a=in.nextInt(); int b=in.nextInt(); if(a==1 || b==1) { int ans[][]=new int [n][n]; int temp=(a==1)?b:a; for(int i=1;i<=n-temp;i++) { ans[i][i-1]=1; ans[i-1][i]=1; } int freq=Count(ans,n); if(freq!=1) { pw.println("NO"); } else { pw.println("YES"); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) { pw.print(0); } else pw.print((ans[i][j]+((temp==b)?1:0))%2); } pw.println(); } } } else { pw.print("NO"); } pw.flush(); pw.close(); } public static void main(String[] args) throws Exception { new Thread(null,new Runnable() { public void run() { new Main().solve(); } },"1",1<<26).start(); } 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 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); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public void extended(int a,int b) { if(b==0) { d=a; p=1; q=0; } else { extended(b,a%b); int temp=p; p=q; q=temp-(a/b)*q; } } public static long[] shuffle(long[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; long temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } static class pair implements Comparable<pair> { Integer x; Long y; pair(int x,long y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } } class pair implements Comparable<pair> { Integer x; Long y; pair(int x,long y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } class dsu{ int parent[]; dsu(int n){ parent=new int[n+1]; for(int i=0;i<=n;i++) { parent[i]=i; } } int root(int n) { while(parent[n]!=n) { parent[n]=parent[parent[n]]; n=parent[n]; } return n; } void union(int _a,int _b) { int p_a=root(_a); int p_b=root(_b); parent[p_a]=p_b; } boolean find(int a,int b) { if(root(a)==root(b)) return true; else return false; } }
quadratic
990_D. Graph And Its Complement
CODEFORCES
import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.TreeSet; public class r568p8{ private static InputReader sc; private static PrintWriter pw; private static long mod; static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; InputReader(InputStream stream) { this.stream = stream; } 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++]; } 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; } 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; } 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(); } 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(); } 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 { boolean isSpaceChar(int ch); } } public static void main(String args[]) { sc = new InputReader(System.in); pw = new PrintWriter(System.out); int t = 1; while(t-->0) solve(); pw.flush(); pw.close(); } private static void fill_matrix(long dp[][][][], int a, int b, int c, int end){ if((a == 0 && b == 0 && c == 0) || (a == 0 && end == 0) || (b == 0 && end == 1) || (c == 0 && end == 2)){ dp[a][b][c][end] = 0; return; } if(a > 1 && b == 0 && c == 0){ dp[a][b][c][end] = 0; return; } if(b > 1 && a == 0 && c == 0){ dp[a][b][c][end] = 0; return; } if(c > 1 && a == 0 && b == 0){ dp[a][b][c][end] = 0; return; } if(a == 1 && end == 0 && b == 0 && c == 0){ dp[a][b][c][end] = 1; return; } if(b == 1 && end == 1 && a == 0 && c == 0){ dp[a][b][c][end] = 1; return; } if(c == 1 && end == 2 && b == 0 && a == 0){ dp[a][b][c][end] = 1; return; } if(end == 0){ fill_matrix(dp, a-1, b, c, 1); fill_matrix(dp, a-1, b, c, 2); dp[a][b][c][0] = (dp[a-1][b][c][1]%mod + dp[a-1][b][c][2]%mod)%mod; } else if(end == 1){ fill_matrix(dp, a, b-1, c, 0); fill_matrix(dp, a, b-1, c, 2); dp[a][b][c][1] = (dp[a][b-1][c][0]%mod + dp[a][b-1][c][2]%mod)%mod; } else{ fill_matrix(dp, a, b, c-1, 0); fill_matrix(dp, a, b, c-1, 1); dp[a][b][c][2] = (dp[a][b][c-1][0]%mod + dp[a][b][c-1][1]%mod)%mod; } } private static long cal(int count[]){ int a = count[0], b = count[1], c = count[2]; long dp[][][][] = new long[a+1][b+1][c+1][3]; long factorial[] = new long[20]; factorial[0] = 1; factorial[1] = 1; for(int i=2; i<20; i++) factorial[i] = (factorial[i-1]%mod*i%mod)%mod; fill_matrix(dp, a, b, c, 0); fill_matrix(dp, a, b, c, 1); fill_matrix(dp, a, b, c, 2); long p = (dp[a][b][c][0]%mod + dp[a][b][c][1]%mod + dp[a][b][c][2]%mod)%mod; long ans = (((p%mod * factorial[a]%mod)%mod * factorial[b]%mod)%mod * factorial[c]%mod)%mod; return ans; } private static void solve(){ int n = sc.nextInt(), T = sc.nextInt(); int len[] = new int[n], genre[] = new int[n]; for(int i=0; i<n; i++){ len[i] = sc.nextInt(); genre[i] = sc.nextInt(); } int sum[] = new int[(1<<n)]; mod = (long)1e9 + 7; long ans = 0; for(int i=1; i<(1<<n); i++){ for(int j=0; j<15; j++){ if((i&(1<<j)) != 0){ sum[i] = sum[i^(1<<j)] + len[j]; break; } } if(sum[i] == T) { int count[] = {0, 0, 0}; for (int j = 0; j < 15; j++) { if ((i & (1 << j)) != 0) count[genre[j] - 1]++; } ans = (ans % mod + cal(count) % mod) % mod; } } pw.println(+ans); } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
import java.math.BigInteger; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner sc=new Scanner(System.in); long s=0,mod=1000000009; int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt(),c=n/k; if(m<=c*(k-1)+(n%k))System.out.println(m); else { int a=m-c*(k-1)-(n%k); long l=0,pase=0; //System.out.println(a); long pot=BigInteger.valueOf(2).modPow(BigInteger.valueOf(a), BigInteger.valueOf(mod)).longValue(); pot=(2*(pot-1))%mod; /*System.out.println(pot); System.out.println(k);*/ System.out.println(((pot*k)%mod+(m-a*k))%mod); } } }
logn
338_A. Quiz
CODEFORCES
//package Educational35; //import FastScanner.Competitive; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class D { String INPUT = "4\n" + "1 2 4 3\n" + "4\n" + "1 1\n" + "1 4\n" + "1 4\n" + "2 3"; void solve() { final int n = i(); final int[] a = ia(n); int count = 0 ; for(int i = 0 ; i<n-1 ; i++) { for(int j = i+1; j<n ; j++) { if(a[j]<a[i]) { count++; } } } final int q = i(); for(int i = 0 ; i<q ; i++) { final int l = i(), r=i(); final int mid = (r-l+1)/2; if(mid%2==0) { out.println(count%2==0?"even":"odd"); } else { count++; out.println(count%2==0?"even":"odd"); } } } /////////////////////////////////////// void run() throws Exception{ is = oj ? System.in: new ByteArrayInputStream(INPUT.getBytes()); //is = System.in; out = new PrintWriter(System.out); int t = 1; while(t-->0) solve(); out.flush(); } public static void main(String[] args)throws Exception { new D().run(); } InputStream is; PrintWriter out; 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 d() { return Double.parseDouble(s()); } private char c() { return (char)skip(); } private String s() { 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[] sa(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] = sa(m); return map; } private int[] ia(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = i(); return a; } private int i() { 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 l() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class BOOL { static char [][]ch; static int n,m; private static FastReader in =new FastReader(); public static void main(String[] args) { int n=in.nextInt(); int a[]=new int[1000002]; int dp[]=new int[1000002],ans=0; for(int i=0;i<n;i++){a[in.nextInt()]=in.nextInt();} dp[0]=a[0]==0?0:1; for(int i=1;i<1000002;i++){ if(a[i]==0){dp[i]=dp[i-1];} else{ if(a[i]>=i){dp[i]=1;} else{ dp[i]=dp[i-a[i]-1]+1; }} if(dp[i]>=ans)ans=dp[i]; } System.out.println(n-ans); }} class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
linear
608_C. Chain Reaction
CODEFORCES
//package codeforces; import java.util.*; import java.math.BigInteger; public class test_round_B { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); BigInteger k=sc.nextBigInteger(); BigInteger i=new BigInteger("0"); int d=0; BigInteger a=new BigInteger("0"); while(i.compareTo(k)!=1) { if(i.compareTo(k)==0) { break; } else { d++; BigInteger temp=new BigInteger("0"); for(int j=0;j<d;j++) { temp=temp.multiply(new BigInteger("10")).add(new BigInteger("9")); } i=i.add(new BigInteger(Integer.toString(d)).multiply(temp.subtract(a))); //i=i+d*(temp-a); a=temp; } } //System.out.println(a) ; BigInteger b=a.divide(new BigInteger("10")); BigInteger t=b; BigInteger l=t; //System.out.println(b); int dig=0; if(b.equals(new BigInteger("0"))) { dig=0; } else { while(b.compareTo(new BigInteger("0"))==1) { dig++; b=b.divide(new BigInteger("10")); } } //System.out.println(dig); int flag=dig+1; BigInteger num=new BigInteger("0"); b=t; while(b.compareTo(new BigInteger("0"))==1) { //System.out.println("sun"); BigInteger rev=b.divide(new BigInteger("10")); num=num.add(new BigInteger(Integer.toString(dig)).multiply(b.subtract(rev))); //num+=(b-rev)*dig; b=b.divide(new BigInteger("10")); dig--; } //System.out.println(num); //System.out.println(t); BigInteger net=k.subtract(num); BigInteger div=net.divide(new BigInteger(Integer.toString(flag))); int q; if(net.mod(new BigInteger(Integer.toString(flag))).equals(new BigInteger("0"))) { //System.out.println("s"); //System.out.println(); q=0; t=t.add(div); System.out.println(t.mod(new BigInteger("10"))); } else { //System.out.println(div); //System.out.println(flag); //System.out.println(net); BigInteger r=div.multiply(new BigInteger(Integer.toString(flag))); r=net.subtract(r); //q=Integer.toString(net%flag).length(); //System.out.println(q); //System.out.println(t); //System.out.println(pig); //System.out.println(w); t=t.add(div.add(new BigInteger("1"))); //System.out.println(r); l=t; int pig=0; while(t.compareTo(new BigInteger("0"))==1) { pig++; t=t.divide(new BigInteger("10")); } //System.out.println(pig); BigInteger p=new BigInteger(Integer.toString(pig)); BigInteger rem=p.subtract(r); //System.out.println(l); while(rem.compareTo(new BigInteger("0"))==1) { l=l.divide(new BigInteger("10")); rem=rem.subtract(new BigInteger("1")); } //System.out.println(l); //System.out.println(r); //System.out.println(c); //int f=t/w; //System.out.println(f); System.out.println(l.mod(new BigInteger("10"))); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Arrays; import java.util.Scanner; /** * @author vstepanov on 3/29/2017. */ public class Main { public static void main(String[] args) { try(Scanner in = new Scanner(System.in)) { int bx = in.nextInt(); int by = in.nextInt(); int n = in.nextInt(); int[][] xy = new int[n][2]; int[] res = new int[1 << n]; int[] last = new int[1 << n]; for (int i = 0; i < n; i++) { xy[i] = new int[]{in.nextInt(), in.nextInt()}; } int[] ds = new int[n]; for (int i = 0; i < ds.length; i++) { ds[i] = time(xy[i][0], xy[i][1], bx, by); } int[][] d = new int[n][n]; for (int i = 0; i < d.length; i++) { for (int j = 0; j < d.length; j++) { d[i][j] = time(xy[i][0], xy[i][1], xy[j][0], xy[j][1]); } } Arrays.fill(res, Integer.MAX_VALUE); res[0] = 0; for (int i = 0; i < (1 << n); i++) { for (int j = 0; j < n; j++) { if ((i & mask(j)) != 0) { if (res[i - mask(j)] + 2*ds[j] < res[i]) { res[i] = res[i - mask(j)] + 2*ds[j]; last[i] = i - mask(j); } for (int k = j + 1; k < n; k++) { if ((i & mask(k)) != 0) { if (res[i - mask(k) - mask(j)] + ds[j] + ds[k] + d[j][k] < res[i]) { res[i] = res[i - mask(k) - mask(j)] + ds[j] + ds[k] + d[j][k]; last[i] = i - mask(j) - mask(k); } } } break; } } } int cur = (1 << n) - 1; System.out.println(res[cur]); int k = cur; while (k != 0) { System.out.print("0 "); int diff = k - last[k]; for (int i = 0; i < n && diff != 0; i++) { if (((diff >> i) & 1) != 0) { System.out.print((i + 1) + " "); diff -= (1 << i); } } k = last[k]; } System.out.println("0"); } } static int mask(int i) { return 1 << i; } static int time(int x, int y, int x1, int y1) { return (x - x1)*(x - x1) + (y - y1)*(y - y1); } }
np
8_C. Looking for Order
CODEFORCES
/** * Author: Ridam Nagar * Date: 27 February 2019 * Time: 01:17:36 **/ /* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { static String reverse(String s){ String reverse=""; for(int i=s.length()-1;i>=0;i--){ reverse=reverse + s.charAt(i); } return reverse; } public static void main (String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int x=m%(int)Math.pow(2,n); System.out.println(x); } }
constant
913_A. Modular Exponentiation
CODEFORCES
import java.io.*; import java.util.*; public class icpc { public static void main(String[] args) throws IOException { Reader in = new Reader(); // BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); long n = in.nextLong(); long k = in.nextLong(); long val = 2 * n + 2 * k; long D = 9 + 4 * val; long sqrtD = (long)Math.sqrt((double)D); double r1 = (-3 + sqrtD) / 2; long r1DAsh = (long)r1; System.out.println(n - r1DAsh); } } class NumberTheory { public boolean isPrime(long n) { if(n < 2) return false; for(long x = 2;x * x <= n;x++) { if(n % x == 0) return false; } return true; } public ArrayList<Integer> primeFactorisation(int n) { ArrayList<Integer> f = new ArrayList<>(); for(int x=2;x * x <= n;x++) { while(n % x == 0) { f.add(x); n /= x; } } if(n > 1) f.add(n); return f; } public int[] sieveOfEratosthenes(int n) { int[] sieve = new int[n + 1]; for(int x=2;x<=n;x++) { if(sieve[x] != 0) continue; sieve[x] = x; for(int u=2*x;u<=n;u+=x) if(sieve[u] == 0) sieve[u] = x; } return sieve; } public long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a % b); } public long phi(long n) { double result = n; for(long p=2;p*p<=n;p++) { if(n % p == 0) { while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (double)p)); } } if(n > 1) result *= (1.0 - (1.0 / (double)n)); return (long)result; } public Name extendedEuclid(long a, long b) { if(b == 0) return new Name(a, 1, 0); Name n1 = extendedEuclid(b, a % b); Name n2 = new Name(n1.d, n1.y, n1.x - (long)Math.floor((double)a / b) * n1.y); return n2; } public long modularExponentiation(long a, long b, long n) { long d = 1L; String bString = Long.toBinaryString(b); for(int i=0;i<bString.length();i++) { d = (d * d) % n; if(bString.charAt(i) == '1') d = (d * a) % n; } return d; } } class Name { long d; long x; long y; public Name(long d, long x, long y) { this.d = d; this.x = x; this.y = y; } } class SuffixArray { int ALPHABET_SZ = 256, N; int[] T, lcp, sa, sa2, rank, tmp, c; public SuffixArray(String str) { this(toIntArray(str)); } private static int[] toIntArray(String s) { int[] text = new int[s.length()]; for (int i = 0; i < s.length(); i++) text[i] = s.charAt(i); return text; } public SuffixArray(int[] text) { T = text; N = text.length; sa = new int[N]; sa2 = new int[N]; rank = new int[N]; c = new int[Math.max(ALPHABET_SZ, N)]; construct(); kasai(); } private void construct() { int i, p, r; for (i = 0; i < N; ++i) c[rank[i] = T[i]]++; for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1]; for (i = N - 1; i >= 0; --i) sa[--c[T[i]]] = i; for (p = 1; p < N; p <<= 1) { for (r = 0, i = N - p; i < N; ++i) sa2[r++] = i; for (i = 0; i < N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p; Arrays.fill(c, 0, ALPHABET_SZ, 0); for (i = 0; i < N; ++i) c[rank[i]]++; for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1]; for (i = N - 1; i >= 0; --i) sa[--c[rank[sa2[i]]]] = sa2[i]; for (sa2[sa[0]] = r = 0, i = 1; i < N; ++i) { if (!(rank[sa[i - 1]] == rank[sa[i]] && sa[i - 1] + p < N && sa[i] + p < N && rank[sa[i - 1] + p] == rank[sa[i] + p])) r++; sa2[sa[i]] = r; } tmp = rank; rank = sa2; sa2 = tmp; if (r == N - 1) break; ALPHABET_SZ = r + 1; } } private void kasai() { lcp = new int[N]; int[] inv = new int[N]; for (int i = 0; i < N; i++) inv[sa[i]] = i; for (int i = 0, len = 0; i < N; i++) { if (inv[i] > 0) { int k = sa[inv[i] - 1]; while ((i + len < N) && (k + len < N) && T[i + len] == T[k + len]) len++; lcp[inv[i] - 1] = len; if (len > 0) len--; } } } } class ZAlgorithm { public int[] calculateZ(char input[]) { int Z[] = new int[input.length]; int left = 0; int right = 0; for(int k = 1; k < input.length; k++) { if(k > right) { left = right = k; while(right < input.length && input[right] == input[right - left]) { right++; } Z[k] = right - left; right--; } else { //we are operating inside box int k1 = k - left; //if value does not stretches till right bound then just copy it. if(Z[k1] < right - k + 1) { Z[k] = Z[k1]; } else { //otherwise try to see if there are more matches. left = k; while(right < input.length && input[right] == input[right - left]) { right++; } Z[k] = right - left; right--; } } } return Z; } public ArrayList<Integer> matchPattern(char text[], char pattern[]) { char newString[] = new char[text.length + pattern.length + 1]; int i = 0; for(char ch : pattern) { newString[i] = ch; i++; } newString[i] = '$'; i++; for(char ch : text) { newString[i] = ch; i++; } ArrayList<Integer> result = new ArrayList<>(); int Z[] = calculateZ(newString); for(i = 0; i < Z.length ; i++) { if(Z[i] == pattern.length) { result.add(i - pattern.length - 1); } } return result; } } class KMPAlgorithm { public int[] computeTemporalArray(char[] pattern) { int[] lps = new int[pattern.length]; int index = 0; for(int i=1;i<pattern.length;) { if(pattern[i] == pattern[index]) { lps[i] = index + 1; index++; i++; } else { if(index != 0) { index = lps[index - 1]; } else { lps[i] = 0; i++; } } } return lps; } public ArrayList<Integer> KMPMatcher(char[] text, char[] pattern) { int[] lps = computeTemporalArray(pattern); int j = 0; int i = 0; int n = text.length; int m = pattern.length; ArrayList<Integer> indices = new ArrayList<>(); while(i < n) { if(pattern[j] == text[i]) { i++; j++; } if(j == m) { indices.add(i - j); j = lps[j - 1]; } else if(i < n && pattern[j] != text[i]) { if(j != 0) j = lps[j - 1]; else i = i + 1; } } return indices; } } class Hashing { public long[] computePowers(long p, int n, long m) { long[] powers = new long[n]; powers[0] = 1; for(int i=1;i<n;i++) { powers[i] = (powers[i - 1] * p) % m; } return powers; } public long computeHash(String s) { long p = 31; long m = 1_000_000_009; long hashValue = 0L; long[] powers = computePowers(p, s.length(), m); for(int i=0;i<s.length();i++) { char ch = s.charAt(i); hashValue = (hashValue + (ch - 'a' + 1) * powers[i]) % m; } return hashValue; } } class BasicFunctions { public long min(long[] A) { long min = Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min = Math.min(min, A[i]); } return min; } public long max(long[] A) { long max = Long.MAX_VALUE; for(int i=0;i<A.length;i++) { max = Math.max(max, A[i]); } return max; } } class Matrix { long a; long b; long c; long d; public Matrix(long a, long b, long c, long d) { this.a = a; this.b = b; this.c = c; this.d = d; } } class MergeSortInt { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class MergeSortLong { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class Node { String a; String b; Node(String s1,String s2) { this.a = s1; this.b = s2; } @Override public boolean equals(Object ob) { if(ob == null) return false; if(!(ob instanceof Node)) return false; if(ob == this) return true; Node obj = (Node)ob; if(this.a.equals(obj.a) && this.b.equals(obj.b)) return true; return false; } @Override public int hashCode() { return (int)this.a.length(); } } 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(); } } class FenwickTree { public void update(long[] fenwickTree,long delta,int index) { index += 1; while(index < fenwickTree.length) { fenwickTree[index] += delta; index = index + (index & (-index)); } } public long prefixSum(long[] fenwickTree,int index) { long sum = 0L; index += 1; while(index > 0) { sum += fenwickTree[index]; index -= (index & (-index)); } return sum; } } class SegmentTree { public int nextPowerOfTwo(int num) { if(num == 0) return 1; if(num > 0 && (num & (num - 1)) == 0) return num; while((num &(num - 1)) > 0) { num = num & (num - 1); } return num << 1; } public int[] createSegmentTree(int[] input) { int np2 = nextPowerOfTwo(input.length); int[] segmentTree = new int[np2 * 2 - 1]; for(int i=0;i<segmentTree.length;i++) segmentTree[i] = Integer.MIN_VALUE; constructSegmentTree(segmentTree,input,0,input.length-1,0); return segmentTree; } private void constructSegmentTree(int[] segmentTree,int[] input,int low,int high,int pos) { if(low == high) { segmentTree[pos] = input[low]; return; } int mid = (low + high)/ 2; constructSegmentTree(segmentTree,input,low,mid,2*pos + 1); constructSegmentTree(segmentTree,input,mid+1,high,2*pos + 2); segmentTree[pos] = Math.max(segmentTree[2*pos + 1],segmentTree[2*pos + 2]); } public int rangeMinimumQuery(int []segmentTree,int qlow,int qhigh,int len) { return rangeMinimumQuery(segmentTree,0,len-1,qlow,qhigh,0); } private int rangeMinimumQuery(int segmentTree[],int low,int high,int qlow,int qhigh,int pos) { if(qlow <= low && qhigh >= high){ return segmentTree[pos]; } if(qlow > high || qhigh < low){ return Integer.MIN_VALUE; } int mid = (low+high)/2; return Math.max(rangeMinimumQuery(segmentTree, low, mid, qlow, qhigh, 2 * pos + 1), rangeMinimumQuery(segmentTree, mid + 1, high, qlow, qhigh, 2 * pos + 2)); } }
logn
1195_B. Sport Mafia
CODEFORCES
import java.util.*; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Comp c1 = getComp(scanner); Comp c2 = getComp(scanner); c1.sortByPrice(); c2.sortByPrice(); int i = 0; int j = 0; while(i < c1.num || j < c2.num) { Elem xi = (i < c1.num) ? c1.elems.get(i) : null; Elem yj = (j < c2.num) ? c2.elems.get(j) : null; if(xi != null && yj != null) { if(xi.price >= yj.price) { if(!c2.resultSet.contains(xi)) { c1.resultSet.add(xi); } i++; } else { if(!c1.resultSet.contains(yj)) { c2.resultSet.add(yj); } j++; } } else if(xi != null) { if(!c2.resultSet.contains(xi)) { c1.resultSet.add(xi); } i++; } else { if(!c1.resultSet.contains(yj)) { c2.resultSet.add(yj); } j++; } } long result = c1.getResultPrice() + c2.getResultPrice(); System.out.println(result); } private static Comp getComp(Scanner scanner) { Comp c = new Comp(); c.num = scanner.nextInt(); for(int i = 0; i < c.num; i++) { c.addElem(scanner.nextLong(), scanner.nextLong()); } return c; } } class Comp { int num; List<Elem> elems = new ArrayList<>(); Set<Elem> resultSet = new HashSet<>(); void addElem(long el, long pr) { Elem elem = new Elem(el, pr); elems.add(elem); } void sortByPrice() { Collections.sort(elems); } long getResultPrice() { long sumPrice = 0; for(Elem elem : resultSet) { sumPrice += elem.price; } return sumPrice; } } class Elem implements Comparable<Elem> { long elem; long price; public Elem(long el, long pr) { this.elem = el; this.price = pr; } public int compareTo(Elem other) { return (int) (other.price - price); } public boolean equals(Object o) { if(!(o instanceof Elem)) { return false; } Elem other = (Elem) o; return (other.elem == elem); } public int hashCode() { return (int) elem; } public String toString() { return "(" + elem + ", " + price + ")"; } }
nlogn
981_B. Businessmen Problems
CODEFORCES
//>>>BaZ<<<// import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static int dx[] = {-1,1,0,0}; static int dy[] = {0,0,1,-1}; static long MOD = 1000000007; static int INF = Integer.MAX_VALUE/10; static PrintWriter pw; static InputReader scan; //static MyFileReader1 ss; //static MyFileReader scan; static int ni() throws IOException{return scan.nextInt();} static long nl() throws IOException{return scan.nextLong();} static double nd() throws IOException{return scan.nextDouble();} static String ne() throws IOException{return scan.next();} static void pl() throws IOException {pw.println();} static void pl(Object o) throws IOException {pw.println(o);} static void p(Object o) throws IOException {pw.print(o+" ");} static void psb(StringBuilder sb) throws IOException {pw.print(sb);} public static void main(String[] args) { new Thread(null,null,"BaZ",99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws IOException { Calendar CAL1 = Calendar.getInstance(); CAL1.setTime(new Date()); scan = new InputReader(System.in); pw = new PrintWriter(System.out,true); //pw = new PrintWriter(new File("C://Users/Aman deep/Desktop/output.txt")); //ss = new MyFileReader1(); //scan = new MyFileReader(); StringBuilder sb = new StringBuilder(); int n = ni(); double r = ni(); double x[] = new double[n]; for(int i=0;i<n;++i) x[i] = nd(); double y[] = new double[n]; y[0] = r; for(int i=1;i<n;++i) { double max = -1; for(int j=0;j<i;++j) { double xx = 4*r*r-(x[i]-x[j])*(x[i]-x[j]); if(xx>=0) max = max(max,sqrt(xx)+y[j]); } if(max==-1) max = r; y[i] = max; } for(int i=0;i<n;++i) p(y[i]); pl(); Calendar CAL2 = Calendar.getInstance(); CAL2.setTime(new Date()); double Execution_Time = (double)(CAL2.getTimeInMillis()-CAL1.getTimeInMillis())/1000.000; //System.out.println("Execution time : "+Execution_Time+" seconds"); pw.flush(); pw.close(); } static class InputReader //NoSuchElementException -> EOF { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class MyFileReader //File input template { StringTokenizer st; BufferedReader br; MyFileReader() throws IOException { br = new BufferedReader(new FileReader("C://Users/Aman deep/Desktop/input.txt")); } String nextLine() throws IOException { return br.readLine(); } String next() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(nextLine()); 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()); } } static class MyFileReader1 //File input template { StringTokenizer st; BufferedReader br; MyFileReader1() throws IOException { br = new BufferedReader(new FileReader("C://Users/Aman deep/Desktop/output.txt")); } String nextLine() throws IOException { return br.readLine(); } String next() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(nextLine()); 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()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; import java.util.stream.Collectors; public class P1177A { public static void main(String[] args) throws Exception { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); long n = Long.parseLong(r.readLine()); if (n < 10) { System.out.print(n); return; } int len = 1; long edge = 10; long prev = 0; long prepow = 0; while (edge - 1 < n) { prepow = (long)Math.pow(10, len); long pow = prepow * 10; prev = edge; edge = edge + (pow - prepow) * (len + 1); len += 1; } long b = n - prev; long c = b / len; int rem = (int)(b % len); String s = Long.toString(prepow + c).charAt(rem) + ""; System.out.print(s); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.util.*; public final class Subtractions { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Solver solver = new Solver(in, out); solver.solve(); in.close(); out.flush(); out.close(); } static class Solver { int n; InputReader in; PrintWriter out; void solve() { n = in.nextInt(); while (n-- > 0) { int a, b; a = in.nextInt(); b = in.nextInt(); int cnt = 0; while (a > 0 && b > 0) { if (a < b) a = swap(b, b = a); cnt += a / b; a -= b * (a / b); } out.println(cnt); } } int swap(int a, int b) { return a; } public Solver(InputReader in, PrintWriter out) { this.in = in; this.out = out; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
constant
267_A. Subtractions
CODEFORCES
import java.util.*; import java.io.*; public class C0008 { public static void main(String args[]) throws Exception { new C0008(); } int n; int target; int pow[]; int dp[]; int next[]; int dist[][]; C0008() throws Exception { PandaScanner sc = null; PrintWriter out = null; try { sc = new PandaScanner(System.in); out = new PrintWriter(System.out); } catch (Exception ignored) { } pow = new int[26]; for (int i = 0; i < 26; i++) { pow[i] = 1 << i; } dist = new int[26][26]; int[][] p = new int[26][]; p[25] = new int[] {sc.nextInt(), sc.nextInt()}; n = sc.nextInt(); target = (1 << n) - 1; for (int i = 0; i < n; i++) { p[i] = new int[] {sc.nextInt(), sc.nextInt()}; dist[i][25] = getDist(p[i], p[25]); for (int j = 0; j < i; j++) { dist[j][i] = getDist(p[j], p[i]); } } next = new int[1 << n]; dp = new int[1 << n]; Arrays.fill(dp, -1); out.println(go(0)); ArrayList<Integer> paths = new ArrayList<Integer>(); paths.add(0); int curr = 0; while (curr != target) { for (Integer i: getBits(next[curr], true)) { paths.add(i + 1); } paths.add(0); curr |= next[curr]; } out.println(paths.toString().replaceAll("[^ 0-9]", "")); out.close(); System.exit(0); } int go(int mask) { if (mask == target) { return 0; } if (dp[mask] != -1) { return dp[mask]; } ArrayList<Integer> notDone = getBits(mask, false); dp[mask] = Integer.MAX_VALUE; for (Integer i: notDone) { int oneD = (dist[i][25] << 1) + go(mask | pow[i]); if (dp[mask] > oneD) { dp[mask] = oneD; next[mask] = 1 << i; } for (Integer j: notDone) { if (j == i) continue; int d = (dist[j][25] + dist[i][j] + dist[i][25]) + go(mask | pow[i] | pow[j]); if (dp[mask] > d) { dp[mask] = d; next[mask] = (1 << i) | (1 << j); } } break; } return dp[mask]; } int getDist(int[] p1, int[] p2) { return sq(p1[0] - p2[0]) + sq(p1[1] - p2[1]); } int sq(int a) { return a * a; } ArrayList<Integer> getBits(int mask, boolean on) { ArrayList<Integer> res = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { if (((mask & (1 << i)) == 0) ^ on) { res.add(i); } } return res; } //The PandaScanner class, for Panda fast scanning! public class PandaScanner { BufferedReader br; StringTokenizer st; InputStream in; PandaScanner(InputStream in) throws Exception { br = new BufferedReader(new InputStreamReader(this.in = in)); } public String next() throws Exception { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine().trim()); return next(); } return st.nextToken(); } public boolean hasNext() throws Exception { return (st != null && st.hasMoreTokens()) || in.available() > 0; } public long nextLong() throws Exception { return Long.parseLong(next()); } public int nextInt() throws Exception { return Integer.parseInt(next()); } } }
np
8_C. Looking for Order
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.Random; public class ProblemC { public static void main(String[] args) throws IOException { init(); new ProblemC().run(); out.flush(); out.close(); } static void init() throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(new OutputStreamWriter(System.out)); in.ordinaryChars(0, 65535); in.wordChars(0, 65535); in.whitespaceChars(' ', ' '); in.whitespaceChars('\n', '\n'); in.whitespaceChars('\r', '\r'); } // класс для пар class Pair<L, R> { private final L X; private final R Y; public Pair(L X, R Y) { this.X = X; this.Y = Y; } public L getX() { return X; } public R getY() { return Y; } @Override public int hashCode() { return X.hashCode() ^ Y.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair pairo = (Pair) o; return X.equals(pairo.getX()) && Y.equals(pairo.getY()); } } static final long INFL = 200000000000000000L; static final int INF = 2000000000; static final boolean DEBUG = true; static StreamTokenizer in; static PrintWriter out; static void print(String s) { print(s, 0); } static void print(String s, int debug) { if (debug == 0 || DEBUG) { out.print(s); } } static void println(String s) { println(s, 0); } static void println(String s, int debug) { if (debug == 0 || DEBUG) { out.println(s); } } static void printArray(int[] arr) { println(Arrays.toString(arr)); } static void printArray(char[] arr) { println(Arrays.toString(arr)); } static void printArray(String[] arr) { println(Arrays.toString(arr)); } static void sort(int[] a) { Random rnd = new Random(); for (int i = a.length - 1; i > 0; i--) { int index = rnd.nextInt(i); a[i] ^= a[index]; a[index] ^= a[i]; a[i] ^= a[index]; } Arrays.sort(a); } static char[] inChars; static int inCharsInd; static String next() throws IOException { in.nextToken(); return in.sval; } static char nextChar() throws IOException { while (inChars == null || inCharsInd >= inChars.length) { inChars = next().toCharArray(); inCharsInd = 0; } return inChars[inCharsInd++]; } static int nextInt() throws IOException { return Integer.valueOf(next()); } static double nextDouble() throws IOException { return Double.valueOf(next()); } static long nextLong() throws IOException { return Long.valueOf(next()); } private void run() throws IOException { solve(); } int K, L, M, N, P; private void solve() throws IOException { int[] countChars = new int['z' + 1]; boolean[] gotIt = new boolean['z' + 1]; int N = nextInt(); int fullCount = 0; char[] chars = next().toCharArray(); for (int i = 0; i < N; i++) { if (countChars[chars[i]] == 0) fullCount++; countChars[chars[i]]++; } // out.println(fullCount); countChars = new int['z' + 1]; int answer = N; int start = 0, finish = 0; countChars[chars[start]]++; fullCount--; while (finish+1 < N){ finish++; if (countChars[chars[finish]] == 0) { fullCount--; } countChars[chars[finish]]++; while (countChars[chars[start]] > 1){ countChars[chars[start]]--; start++; } while (fullCount == 0){ // out.println("start = " + (start+1)); // out.println("finish = " + (finish+1)); answer = Math.min(answer, finish-start+1); countChars[chars[start]]--; if (countChars[chars[start]] == 0) fullCount++; start++; } } out.println(answer); } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.util.*; public class B { public void solve() throws IOException { long n = nextInt(), k = nextInt(); long c = 2 * (n + k); long l = -1, r = 200000; while (r - l > 1) { long m = l + (r - l) / 2; if (m * m + 3 * m >= c) { r = m; } else { l = m; } } out.print(n - r); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public int[] nextArr(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new B().run(); } }
logn
1195_B. Sport Mafia
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 MaxHeap */ 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); CBanhMi solver = new CBanhMi(); solver.solve(1, in, out); out.close(); } static class CBanhMi { long mod = (long) (1e9 + 7); public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int q = in.nextInt(); long[] two = new long[n + 1]; two[0] = 1; for (int i = 1; i <= n; ++i) { two[i] = (two[i - 1] * 2L); two[i] %= mod; } char[] s = in.nextCharArray(); int[] acc = new int[n + 1]; for (int i = 1; i <= n; ++i) { acc[i] = s[i - 1] == '0' ? 0 : 1; acc[i] += acc[i - 1]; } // 0 0 1 1 | 1: 1 1 2| 2: 2 3| 4: 5| 9 // 0 1 1 1| 1: 1 2 2| 2: 3 3| 5: 6| 11 // 0 1 1 wwqwq| 1: 1 2 2| 3: 5 3| 8: 8| 16 // 0 0 1 1| 1: 1 1 2| 3: 3 3| 6: 6| 12 // 0 0 0 1| 1: 1 1 1| 2: 2 2| 4: 4| 8 while (q-- > 0) { int f = in.nextInt(); int t = in.nextInt(); int ones = acc[t] - acc[f - 1]; int zeros = (t - f + 1) - ones; if (ones == 0) { out.println(0); } else { long ans = two[t - f + 1] - (zeros > 0 ? two[zeros] : 0); if (zeros == 0) { --ans; } ans = (ans + mod) % mod; out.println(ans); } } } } static class InputReader implements FastIO { private InputStream stream; private static final int DEFAULT_BUFFER_SIZE = 1 << 16; private static final int EOF = -1; private byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (this.numChars == EOF) { throw new UnknownError(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException ex) { throw new InputMismatchException(); } if (this.numChars <= 0) { return EOF; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public String next() { int c; while (isSpaceChar(c = this.read())) { } StringBuilder result = new StringBuilder(); result.appendCodePoint(c); while (!isSpaceChar(c = this.read())) { result.appendCodePoint(c); } return result.toString(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == EOF; } public char[] nextCharArray() { return next().toCharArray(); } } static interface FastIO { } }
linear
1062_C. Banh-mi
CODEFORCES
import java.util.*; public class main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int houses = sc.nextInt(); int size = sc.nextInt(); hizzy[] array = new hizzy[houses]; long total =2; for(int a=0;a<houses;a++)array[a]=new hizzy(sc.nextInt(),sc.nextInt()); Arrays.sort(array); for(int a=0;a<houses-1;a++){ double L = array[a].loc+array[a].size/2; double R = array[a+1].loc-array[a+1].size/2; if(R-L>size)total+=2; else if((R-L)==size)total++; } System.out.println(total); } } class hizzy implements Comparable{ double loc; double size; hizzy(double l, double s){ this.loc=l; this.size=s; } public int compareTo(Object o) { hizzy other = (hizzy) o; return (int) (this.loc-other.loc); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; import static java.lang.Long.bitCount; public class Main { public static void main(String[] args) { FastScanner in = new FastScanner(); long []a = new long[16]; a[0] = 0; for(int i=1; i<16; ++i) a[i] = a[i-1]+((9*(long)Math.pow(10, i-1))*i); long N = in.nextLong(); int pos = 0; for(int i=0; i<16; ++i){ if(N<=a[i]){ pos = i; break; } } if(pos==1){ System.out.println(N); System.exit(0); } long prev = a[pos-1]; long curr = N; long rem = curr - prev; long ans = 0; for(int i=1; i<pos; ++i){ ans = ans*10 + 9; } long g = (rem+(pos-1))/pos; long take = (rem+(pos-1))%pos; long number = ans + g; String str = Long.toString(number); System.out.println(str.charAt((int)take)); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class GivenString { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s = input.nextLine(); int max = 0; for(int i = 0; i < s.length(); i++) { for(int j = i + 1; j <= s.length(); j++) { String tmp = s.substring(i, j); int match = 0; for(int k = 0; k + tmp.length() <= s.length(); k++) { if(tmp.equals(s.substring(k, k + tmp.length()))) { match++; } } if(match >= 2) { max = Math.max(max, tmp.length()); } } } System.out.println(max); System.exit(0); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.util.*; import java.io.*; import static java.lang.Math.*; public class A{ public static void main(String[] args) throws Exception{ new A().run(); } void run() throws Exception{ //Scanner sc = new Scanner(System.in); BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(sc.readLine()); ArrayList<Integer> a = new ArrayList<Integer>(); //a.add(1); StringTokenizer st = new StringTokenizer(sc.readLine(), " "); boolean allOne = true; for(int i = 0; i < n; i++){ int val = Integer.parseInt(st.nextToken()); if(val!=1)allOne = false; a.add(val); } if(allOne){a.remove(n-1); a.add(2);} else a.add(1); Collections.sort(a); System.out.print(a.get(0)); for(int i = 1; i < n; i++) System.out.print(" " + a.get(i)); System.out.println(); } }
nlogn
135_A. Replacement
CODEFORCES
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.System.exit; import static java.util.Arrays.fill; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class E { static void solve() throws Exception { int tests = scanInt(); // int tests = 40; for (int test = 0; test < tests; test++) { int n = scanInt(), m = scanInt(), a[][] = new int[n][m]; // int n = 12, m = 2000, a[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = scanInt(); } } int bestCols[] = new int[min(m, n)]; for (int i = 0; i < bestCols.length; i++) { bestCols[i] = i; } if (m > n) { int bestColMax[] = new int[n]; for (int i = 0; i < n; i++) { int cmax = 0; for (int j = 0; j < n; j++) { cmax = max(cmax, a[j][i]); } bestColMax[i] = cmax; } for (int i = n; i < m; i++) { int cmax = 0; for (int j = 0; j < n; j++) { cmax = max(cmax, a[j][i]); } int minBC = 0, minBCM = Integer.MAX_VALUE; for (int j = 0; j < n; j++) { if (bestColMax[j] < minBCM) { minBC = j; minBCM = bestColMax[j]; } } if (cmax > minBCM) { bestCols[minBC] = i; bestColMax[minBC] = cmax; } } } int dyn[] = new int[1 << n], dynNext[] = new int[1 << n], sums[] = new int[1 << n], csums[] = new int[1 << n]; for (int i: bestCols) { fill(dynNext, 0); fill(sums, 0); for (int j = 0; j < n; j++) { for (int k = 1, bit = 0; k < 1 << n; k++) { if (k == 1 << (bit + 1)) { ++bit; } sums[k] = max(sums[k], csums[k] = csums[k ^ (1 << bit)] + a[(bit + j) % n][i]); } } for (int mask1 = 0; mask1 < 1 << n; mask1++) { int cdyn = dynNext[mask1]; for (int mask2 = mask1;; mask2 = (mask2 - 1) & mask1) { cdyn = max(cdyn, dyn[mask2] + sums[mask1 ^ mask2]); if (mask2 == 0) { break; } } dynNext[mask1] = cdyn; } int t[] = dyn; dyn = dynNext; dynNext = t; } out.println(dyn[(1 << n) - 1]); } } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
np
1209_E2. Rotate Columns (hard version)
CODEFORCES
import java.util.Scanner; public class B { /** * @param args */ public static void main(String[] args) { Pipes pipes = new Pipes(); pipes.solve(); pipes.print(); } } class Pipes { Pipes() { Scanner scr = new Scanner(System.in); n = scr.nextLong(); k = scr.nextLong(); } long bs(long nb, long nk) { long left = 2; long ls = (nk - left + 1) * (nk + left) / 2 - (nk - left); long right = nk; long rs = nk; if (nb > ls) { return -1; } long mid = left; while (rs < ls){ mid = (left + right)/2; long ms = (nk - mid + 1) * (nk + mid) / 2 - (nk - mid); if (nb > ms) { right = mid; rs = ms; } else if (nb < ms){ left = mid+1; ls = (nk - left + 1) * (nk + left) / 2 - (nk - left); } else { left = mid; break; } } return left; } void solve() { long nn = n; long kk = k; ans = 0; long ps = 1; long add; if (n == 1) { ans = 0; return; } nn = n - (ps - 1); while (nn > kk){ add = bs(nn, kk); if (add == -1) { ans = -1; return; } else { ans = ans + (kk - add + 1); } long addn = (kk - add + 1) * (kk + add) / 2 - (kk - add); ps = ps - 1 + addn; if (ps == n) return; nn = nn - (ps - 1); kk = add - 1; } if (nn > 0) { ans++; } } void print() { System.out.println(ans); } long ans; long n; long k; }
logn
287_B. Pipeline
CODEFORCES
import java.io.*; import java.util.*; public class D { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; double f(int dist, double initSp, int a, int maxSp) { double distToReachMaxSpeed = 0.5 * (maxSp * maxSp - initSp * initSp) / a; if (dist > distToReachMaxSpeed) return 1d * (maxSp - initSp) / a + (dist - distToReachMaxSpeed) / maxSp; return (Math.sqrt(initSp * initSp + 2 * a * dist) - initSp) / a; } void solve() throws IOException { int a = nextInt(); int maxSp = nextInt(); int len = nextInt(); int signX = nextInt(); int signSp = nextInt(); if (maxSp <= signSp) { out.printf("%.9f\n", f(len, 0, a, maxSp)); return; } double distToReachSignSp = 0.5 * signSp * signSp / a; if (distToReachSignSp >= signX) { double t = Math.sqrt(2d * signX / a); out.printf("%.9f\n", t + f(len - signX, t * a, a, maxSp)); return; } double distToReachMaxThenSign = 0.5 * (maxSp * maxSp + maxSp * maxSp - signSp * signSp) / a; if (distToReachMaxThenSign <= signX) { double t = 1d * (2 * maxSp - signSp) / a + (signX - distToReachMaxThenSign) / maxSp + f(len - signX, signSp, a, maxSp); out.printf("%.9f\n", t); return; } double xSp = Math.sqrt(a * signX + signSp * signSp * 0.5); double xTime = (2 * xSp - signSp) / a; out.printf("%.9f\n", xTime + f(len - signX, signSp, a, maxSp)); } void inp() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new D().inp(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
constant
5_D. Follow Traffic Rules
CODEFORCES
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class A483 implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new A483(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(System.out); } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } // solution int choose(int total, int choose){ if(total < choose) return 0; if(choose == 0 || choose == total) return 1; return choose(total-1,choose-1)+choose(total-1,choose); } void solve() throws IOException { long l = readLong(); long r = readLong(); if(r-l>=3){ long c = l%2==0?l:l+1; out.println(c+" "+(c+1)+" "+ (c+2)); }else if(r-l==2&&r%2==0){ out.println(l+" "+(l+1)+" "+(l+2)); }else{ out.println(-1); } } }
constant
483_A. Counterexample
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.LinkedList; public class LuckyNumbers { public static void main(String[] args)throws IOException { BufferedReader scan=new BufferedReader(new InputStreamReader(System.in)); short num=Short.parseShort(scan.readLine()); if(funcion(num)) { System.out.println("YES"); } else System.out.println("NO"); } public static boolean funcion(short num) { LinkedList<Short>queue=new LinkedList<Short>(); queue.offer((short) 4); queue.offer((short) 44); queue.offer((short) 444); queue.offer((short) 47); queue.offer((short) 477); queue.offer((short) 7); queue.offer((short) 77); queue.offer((short) 777); queue.offer((short) 74); queue.offer((short) 744); while(queue.peek()!=null) { if(num%queue.poll()==0) { return true; } } return false; } }
constant
122_A. Lucky Division
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.List; import java.util.StringTokenizer; public class B { final int INF = 1_000_000_000; void solve() { int n = readInt(); int k = readInt(); long l = 0; long r = INF; while(r - l > 1){ long m = (r + l) >> 1; if(m * (m + 1) / 2 + m >= k + n) r = m; else l = m; } out.print(n - r); } public static void main(String[] args) { new B().run(); } private void run() { try { init(); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } private BufferedReader in; private StringTokenizer tok = new StringTokenizer(""); private PrintWriter out; private void init() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // try { // in = new BufferedReader(new FileReader("absum.in")); // out = new PrintWriter(new File("absum.out")); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } } private String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } private String readString() { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (nextLine == null) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(); } private int readInt() { return Integer.parseInt(readString()); } private long readLong() { return Long.parseLong(readString()); } int[] readIntArray(int n){ int[] res = new int[n]; for(int i = 0;i<n;i++){ res[i] = readInt(); } return res; } long[] readLongArray(int n){ long[] res = new long[n]; for(int i = 0;i<n;i++){ res[i] = readLong(); } return res; } int[] castInt(List<Integer> list){ int[] res = new int[list.size()]; for(int i = 0;i<list.size();i++){ res[i] = list.get(i); } return res; } }
logn
1195_B. Sport Mafia
CODEFORCES