src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringclasses
256 values
from
stringclasses
1 value
import java.util.*; public class Main { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int n=scan.nextInt(); int m=scan.nextInt(); int[] game=new int[n]; int[] bill=new int[m]; for (int i = 0; i <n ; i++) { game[i]=scan.nextInt(); } for (int i = 0; i <m ; i++) { bill[i]=scan.nextInt(); } int i=0; int j=0; int ans=0; while (i<m){ boolean f=true; for (int k = j; k <n ; k++) { if (bill[i]>=game[k]){ ans++; i++; j=k+1; f=false; break; } } if (f){ break; } } System.out.println(ans); } }
linear
1009_A. Game Shopping
CODEFORCES
import java.io.*; import java.util.*; public class Solution { static class Data{ int x,i; Data(int x,int i){ this.x = x; this.i = i; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] s = br.readLine().split("\\s"); int N = Integer.parseInt(s[0]); int K = Integer.parseInt(s[1]); s = br.readLine().split("\\s"); int[] arr = new int[N]; for(int i=0;i<N;++i) arr[i] = Integer.parseInt(s[i]); solve(N,K,arr); } private static void solve(int N,int K,int[] arr){ PriorityQueue<Data> pq = new PriorityQueue<Data>(2000,(a,b) -> a.x - b.x == 0 ? b.i - a.i : b.x - a.x); for(int i=0;i<arr.length;++i){ pq.offer(new Data(arr[i],i)); } int tot_sum = 0; List<Integer> ls = new ArrayList<>(); Set<Integer> set = new HashSet<>(); for(int i=1;i<=K;++i){ Data t = pq.poll(); tot_sum += t.x; set.add(t.i); } int last = -1; for(int i =0;i<arr.length;++i){ if(set.contains(i)){ K--; //System.out.println(i); if(K == 0) ls.add(arr.length-last-1); else ls.add(i-last); last = i; } } System.out.println(tot_sum); int size = ls.size(); for(int i=0;i<size;++i){ System.out.print(ls.get(i) + " "); } } }
nlogn
1006_B. Polycarp's Practice
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int min; int count = 0; int c = 0; while (count != n) { min = 1000; for (int i = 0; i < n; i++) { if (a[i] < min) { min = a[i]; } } for (int i = 0; i < n; i++) { if (a[i] != 1000 && a[i] % min == 0) { count++; a[i] = 1000; } } c++; } System.out.println(c); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.HashMap; import java.util.Scanner; import javax.swing.text.html.HTMLDocument.Iterator; public class Main { public static double p[]; static double s[]; static double m[]; static int n; public static double a[][]; public static int index=0; public static boolean vis[]; public static HashMap<Integer, Integer> permMap; public static void main(String g[]) { Scanner sc = new Scanner(System.in); n=sc.nextInt(); m = new double[(1<<n) +1]; vis = new boolean[(1<<n) +1]; a = new double[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { //System.out.println("read"+(c++)); a[i][j] = sc.nextDouble(); } } s = new double[1<<n]; // 2^n int perm=0; m[0]=1; p(); // System.out.println("answers : "); int c=((1<<n)-1); for(int i=0;i<n;i++) { perm = c-(1<<i); // System.out.printf("permutation = %x, prob = %f\n",perm,m[perm]); System.out.printf("%.6f ",m[perm]); } // getPerms(0); // p(perm); // double res[] = new double[n]; // for(int i=0;i<n;i++) { // for(int j=0;j<n;j++) // if((i&(i-1))!=0) // continue; // res[i] = // p(perm,n); // System.out.println(m[i][j]); } // int cur=(1<<n)-1; // //int i=0; // for(i=0;i<n;i++) // { // int val=(cur-(1<<i)); // int L = n-1; // System.out.printf("running for %x .... P = %f\n",val,getProb(val,L)); // // } //getP((1<<n)-1)); // for(int i=0;i<m.length;i++) // { // System.out.println(m[perm]); // } } public static void p() { for(int k=0;k<(1<<n);k++) { int perm=k; for(int j=0;j<n;j++) { if(bitTest(perm, j)) { continue; } int newPerm=perm|(1<<j); // j got eaten for(int i=0;i<n;i++) { if( (i==j) || bitTest(newPerm,i)) { continue; } // i eats j int L=n-countO(perm); if(L<2) { continue; } //System.out.println("L="+L); double pm = 2.0/(L*(L-1)); // System.out.printf("Left with %d,%d eats %d \n",L,i,j); m[newPerm]+=m[perm]*a[i][j]*pm; // System.out.printf("p(%x)= %f \n",newPerm,m[newPerm]); //System.out.printf("p(%x)= %f \n",newPerm2,m[newPerm2]); } // System.out.printf("p(%x)= %f \n",newPerm,m[newPerm]); // System.out.println("here-------------------->"); } } } private static int countO(int marked) { // TODO Auto-generated method stub int count=0; for(int i=0;i<n;i++) { int test = (1<<i); if((test&marked)==(test)) count++; } return count; } private static boolean bitTest(int perm, int i) { // TODO Auto-generated method stub int test = (1<<i); if((test&perm)==test) return true; return false; } private static int bitSet(int perm, int i) { // TODO Auto-generated method stub int np = (1<<i); return np; } }
np
16_E. Fish
CODEFORCES
import java.io.*; import java.util.*; public class MainG { static StdIn in = new StdIn(); static PrintWriter out = new PrintWriter(System.out); static long M=(long)1e9+7; public static void main(String[] args) { char[] cs = in.next().toCharArray(); int n=cs.length; int[] x = new int[n]; for(int i=0; i<n; ++i) x[i]=cs[i]-'0'; long[] dp1 = new long[n+1]; for(int i=0; i<n; ++i) dp1[i+1]=(x[i]+dp1[i]*10)%M; //out.println(Arrays.toString(dp1)); long ans=0; for(int d1=1; d1<=9; ++d1) { long[][] dp2 = new long[2][n+1]; for(int i=0; i<n; ++i) { dp2[0][i+1]=x[i]>=d1?(10*dp2[0][i]+1)%M:dp2[0][i]; dp2[1][i+1]=x[i]>=d1?(10*dp2[1][i]+dp1[i])%M:dp2[1][i]; for(int d2=0; d2<x[i]; ++d2) dp2[1][i+1]=((d2>=d1?10*(dp2[0][i]+dp2[1][i])+dp1[i]+1:dp2[0][i]+dp2[1][i])+dp2[1][i+1])%M; for(int d2=x[i]+1; d2<=9; ++d2) dp2[1][i+1]=((d2>=d1?10*dp2[1][i]+dp1[i]:dp2[1][i])+dp2[1][i+1])%M; } ans+=dp2[0][n]+dp2[1][n]; //out.println(dp2[0][n]+" "+dp2[1][n]); } out.println(ans%M); out.close(); } interface Input { public String next(); public String nextLine(); public int nextInt(); public long nextLong(); public double nextDouble(); } static class StdIn implements Input { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public StdIn() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public StdIn(InputStream in) { try{ din = new DataInputStream(in); } catch(Exception e) { throw new RuntimeException(); } buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == ' ' || c == '\n'||c=='\r') break; s.append((char)c); c=read(); } return s.toString(); } public String nextLine() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == '\n'||c=='\r') break; s.append((char)c); c = read(); } return s.toString(); } public int nextInt() { 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 int[] readIntArray(int n) { int[] ar = new int[n]; for(int i=0; i<n; ++i) ar[i]=nextInt(); return ar; } public long nextLong() { 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 long[] readLongArray(int n) { long[] ar = new long[n]; for(int i=0; i<n; ++i) ar[i]=nextLong(); return ar; } public double nextDouble() { 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() { try{ if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } catch(IOException e) { throw new RuntimeException(); } } public void close() throws IOException { if (din == null) return; din.close(); } } }
quadratic
908_G. New Year and Original Order
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Main { static double eps = 1e-8; public static void main(String[] args) { Scanner r = new Scanner(System.in); int n = r.nextInt(); int t = r.nextInt(); House[] a = new House[n]; for(int i = 0; i < n; i++){ double c = r.nextInt(); double l = r.nextInt(); a[i] = new House(c-l/2, l); } Arrays.sort(a); int res = 0; for(int i = 0; i < n-1; i++){ double dist = a[i+1].s - (a[i].s+a[i].l); if(Math.abs(dist - t) < eps)res++; else if(dist > t)res += 2; } System.out.println(res+2); } } class House implements Comparable<House>{ double s, l; public House(double si, double li){ s = si; l = li; } @Override public int compareTo(House b) { if(s < b.s)return -1; else return 1; } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author ffao */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Parser in = new Parser(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { int mod = 1000000009; public void solve(int testNumber, Parser in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int o = m; m -= n - (n/k); if (m < 0) m = 0; long temp = n/k; long ans; if (m == 0) ans = 0; else { ans = (MathUtils.modpow(2, m+1, mod) + mod - 2) % mod; ans = (ans * k) % mod; } out.println((ans + (o - m*k)) % mod); } } class Parser { private BufferedReader din; private StringTokenizer tokenizer; public Parser(InputStream in) { din = new BufferedReader(new InputStreamReader(in)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(din.readLine()); } catch (Exception e) { throw new UnknownError(); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class OutputWriter extends PrintWriter { public OutputWriter(Writer out) { super(out); } public OutputWriter(OutputStream out) { super(out); } } class MathUtils { public static long modpow(int b, int e, int m) { if (e == 0) return 1%m; else if (e == 1) return b%m; long temp = modpow(b, e/2, m); temp = (temp * temp) % m; if (e % 2 == 1) temp = (temp * b) % m; return temp; } }
logn
338_A. Quiz
CODEFORCES
import java.io.IOException; import java.util.Locale; import java.util.Scanner; public class A { public void processInput() throws IOException { Scanner in = new Scanner(System.in); long n = in.nextLong(); long res = go(n); System.out.printf(Locale.ENGLISH, "%d\n", res); in.close(); } public long go(long n) { long res = n; String str = String.valueOf(n); StringBuilder sb = new StringBuilder(str); sb.deleteCharAt(str.length() - 1); if (sb.length() > 0 && !sb.toString().equals("-")) { res = Math.max(res, Long.valueOf(sb.toString())); } if (str.length() > 1) { if (str.charAt(str.length() - 2) != '-') { sb = new StringBuilder(str); sb.deleteCharAt(str.length() - 2); res = Math.max(res, Long.valueOf(sb.toString())); } } return res; } public static void main(String[] args) throws Exception { A a = new A(); a.processInput(); } }
constant
313_A. Ilya and Bank Account
CODEFORCES
import java.io.*; import java.util.*; public class MainG { static StdIn in = new StdIn(); static PrintWriter out = new PrintWriter(System.out); static long M=(long)1e9+7; static int n, dig; static int[] x; static long[] p10, s; static long[][][] dp; public static void main(String[] args) { char[] cs = in.next().toCharArray(); n=cs.length; x = new int[n]; for(int i=0; i<n; ++i) x[i]=cs[i]-'0'; p10 = new long[n]; p10[0]=1; for(int i=1; i<n; ++i) p10[i]=p10[i-1]*10%M; s = new long[n+1]; s[n]=1; for(int i=n-1; i>=0; --i) s[i]=(s[i+1]+x[i]*p10[n-1-i])%M; long ans=0; dp = new long[2][n][n+1]; for(dig=1; dig<=9; ++dig) { for(int i=0; i<n; ++i) { Arrays.fill(dp[0][i], -1); Arrays.fill(dp[1][i], -1); } for(int i=1; i<=n; ++i) ans=(ans+p10[i-1]*dp(0, 0, i))%M; } out.println(ans); out.close(); } static long dp(int less, int ignore, int need) { if(need==0) return less==1?p10[n-ignore]:s[ignore]; if(ignore==n) return 0; if(dp[less][ignore][need]!=-1) return dp[less][ignore][need]; long res=0; int lim=less==1?9:x[ignore]; for(int i=0; i<=lim; ++i) res=(res+dp(less|(i<lim?1:0), ignore+1, need-(i>=dig?1:0)))%M; return dp[less][ignore][need]=res; } interface Input { public String next(); public String nextLine(); public int nextInt(); public long nextLong(); public double nextDouble(); } static class StdIn implements Input { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public StdIn() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public StdIn(InputStream in) { try{ din = new DataInputStream(in); } catch(Exception e) { throw new RuntimeException(); } buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String next() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == ' ' || c == '\n'||c=='\r') break; s.append((char)c); c=read(); } return s.toString(); } public String nextLine() { int c; while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r')); StringBuilder s = new StringBuilder(); while (c != -1) { if (c == '\n'||c=='\r') break; s.append((char)c); c = read(); } return s.toString(); } public int nextInt() { 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 int[] readIntArray(int n) { int[] ar = new int[n]; for(int i=0; i<n; ++i) ar[i]=nextInt(); return ar; } public long nextLong() { 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 long[] readLongArray(int n) { long[] ar = new long[n]; for(int i=0; i<n; ++i) ar[i]=nextLong(); return ar; } public double nextDouble() { 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() { try{ if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } catch(IOException e) { throw new RuntimeException(); } } public void close() throws IOException { if (din == null) return; din.close(); } } }
quadratic
908_G. New Year and Original Order
CODEFORCES
import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; 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 { ///////////////////////////////////////////////////////////// static nn[] B; static int n,a,b; public void solve(int testNumber, FastScanner in, FastPrinter out) { n=in.nextInt();a=in.nextInt();b=in.nextInt(); int ccc=0; if (a==b)ccc=1; int[] A=in.readIntArray(n); B=new nn[n]; for (int i = 0; i < n; i++) { B[i]=new nn(A[i],i); } ArrayUtils.shuffle(B); Arrays.sort(B); int chk=1; for (int i = 0; i < n; i++) { if (B[i].assign>=0)continue; int v=B[i].val; int cc=0; int pos1=Arrays.binarySearch(B,new nn(a-v,0)); if (pos1>=0&&B[pos1].assign==-1)cc++; if (a!=b){ int pos2=Arrays.binarySearch(B,new nn(b-v,0)); if (pos2>=0&&B[pos2].assign==-1)cc++; } if (cc==0){ chk=0; break; } if (cc==1){ go(i); } } if (chk==0){ out.println("NO"); return; } int[] ans= new int[n]; for (int i = 0; i < n; i++) { ans[B[i].pos]=B[i].assign; } out.println("YES"); for (int i = 0; i < n; i++) { out.print(ans[i] + " "); } out.println(); } static void go (int i){ int v=B[i].val; int pos1=Arrays.binarySearch(B,new nn(a-v,0)); if (pos1>=0&&B[pos1].assign==-1){ B[i].assign=0; B[pos1].assign=0; int vv=B[pos1].val; int np=Arrays.binarySearch(B,new nn(b-vv,0)); if (np>=0)go(np); } if (a!=b){ int pos2=Arrays.binarySearch(B,new nn(b-v,0)); if (pos2>=0&&B[pos2].assign==-1){ B[i].assign=1; B[pos2].assign=1; int vv=B[pos2].val; int np=Arrays.binarySearch(B,new nn(a-vv,0)); if (np>=0)go(np); } } } } class nn implements Comparable<nn> { int val,pos; public String toString() { return "nn{" + "val=" + val + ", pos=" + pos + ", assign=" + assign + ", ct=" + ct + '}'; } int assign=-1; int ct=0; nn(int val, int pos) { this.val = val; this.pos = pos; } public int compareTo(nn o) { return this.val-o.val; //To change body of implemented methods use File | Settings | File Templates. } } class FastScanner extends BufferedReader { public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); // if (isEOF && ret < 0) { // throw new InputMismatchException(); // } // isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } public int[] readIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } } class ArrayUtils { static final long seed = System.nanoTime(); static final Random rand = new Random(seed); public static <T> void shuffle(T[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); T t = a[i]; a[i] = a[j]; a[j] = t; } } }
linear
468_B. Two Sets
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; public class YouAreGivenAString { void run() { try { BufferedReader bfd = new BufferedReader(new InputStreamReader( System.in)); int i, j, k, mxLen = 0; String s= bfd.readLine(); for(i=0; i<s.length(); ++i){ for(j=i+1; j<s.length()+1; ++j){ String s2 = s.substring(i, j); if(s2.length()<=mxLen) continue; int cnt=0; for(k=0; k<s.length(); ++k){ if(s.length()>=k+s2.length()) if(s2.equals(s.substring(k,k+s2.length()))){ cnt++; if(cnt>1)mxLen = Math.max(mxLen, s2.length()); } } } } System.out.println(mxLen); } catch (Exception e) { } } public static void main(String[] args) { new YouAreGivenAString().run(); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.*; import java.lang.*; import java.math.*; public class USACO { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); StringTokenizer st = new StringTokenizer(reader.readLine()," "); int[] perm = new int[n]; int count=0; for (int i=0;i<n;i++) { perm[i]=Integer.parseInt(st.nextToken()); for (int j=0;j<i;j++) { if (perm[j]>perm[i]) { count++; } } } count=count%2; int m = Integer.parseInt(reader.readLine()); for (int i=0;i<m;i++) { StringTokenizer st2 = new StringTokenizer(reader.readLine()," "); int a = Integer.parseInt(st2.nextToken()); int b = Integer.parseInt(st2.nextToken()); if ((b-a+1)%4==2||(b-a+1)%4==3) { count++; count=count%2; } if(count%2==0) { System.out.println("even"); } else { System.out.println("odd"); } } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { FastScanner in; PrintWriter out; static final String FILE = ""; public void solve() { int n = in.nextInt(); TreeMap<Character, Integer> map = new TreeMap<>(); ArrayList<Integer> list = new ArrayList<>(); String s = in.next(); for (int i = 0; i < n; i++) { char ch = s.charAt(i); if (!map.containsKey(ch)) map.put(ch, map.size()); list.add(map.get(ch)); } int l = 0; int ans = Integer.MAX_VALUE; int nad = map.size(); int cnt[] = new int[n]; for (int i = 0; i < list.size(); i++) { if (cnt[list.get(i)] == 0) nad--; cnt[list.get(i)]++; if (nad == 0) { ans = min(ans, i - l + 1); while (true) { if (cnt[list.get(l)] == 1) { ans = min(ans, i - l + 1); cnt[list.get(l)]--; l++; nad++; break; } else { cnt[list.get(l)]--; l++; } } } } out.print(ans); } public void run() { if (FILE.equals("")) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { try { in = new FastScanner(new FileInputStream(FILE + ".in")); out = new PrintWriter(new FileOutputStream(FILE + ".out")); } catch (FileNotFoundException e) { e.printStackTrace(); } } solve(); out.close(); } public static void main(String[] args) { (new Main()).run(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } } class Pair<A extends Comparable<A>, B extends Comparable<B>> implements Comparable<Pair<A, B>> { public A a; public B b; public Pair(A a, B b) { this.a = a; this.b = b; } @Override public int compareTo(Pair<A, B> o) { if (o == null || o.getClass() != getClass()) return 1; int cmp = a.compareTo(o.a); if (cmp == 0) return b.compareTo(o.b); return cmp; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; if (a != null ? !a.equals(pair.a) : pair.a != null) return false; return !(b != null ? !b.equals(pair.b) : pair.b != null); } } class PairInt extends Pair<Integer, Integer> { public PairInt(Integer u, Integer v) { super(u, v); } } class PairLong extends Pair<Long, Long> { public PairLong(Long u, Long v) { super(u, v); } } }
linear
701_C. They Are Everywhere
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.TimeUnit; public class c1523 implements Runnable{ public static void main(String[] args) { try{ new Thread(null, new c1523(), "process", 1<<26).start(); } catch(Exception e){ System.out.println(e); } } public void run() { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); //PrintWriter out = new PrintWriter("file.out"); Task solver = new Task(); int t = scan.nextInt(); //int t = 1; for(int i = 1; i <= t; i++) solver.solve(i, scan, out); out.close(); } static class Task { static final int oo = Integer.MAX_VALUE; static final long OO = Long.MAX_VALUE; public void solve(int testNumber, FastReader sc, PrintWriter out) { int N = sc.nextInt(); int[] arr = sc.readArray(N); Stack<Integer> cur = new Stack<>(); StringBuilder sb = new StringBuilder(""); for(int i = 0; i < N; i++) { if(arr[i] == 1) { cur.add(1); } else { while(cur.peek() != arr[i] - 1) cur.pop(); cur.pop(); cur.add(arr[i]); } for(int each: cur) { sb.append(each + "."); } sb.deleteCharAt(sb.length()-1); sb.append("\n"); } out.println(sb); } } static long modInverse(long N, long MOD) { return binpow(N, MOD - 2, MOD); } static long modDivide(long a, long b, long MOD) { a %= MOD; return (binpow(b, MOD-2, MOD) * a) % MOD; } static long binpow(long a, long b, long m) { a %= m; long res = 1; while (b > 0) { if ((b & 1) == 1) res = res * a % m; a = a * a % m; b >>= 1; } return res; } static int[] reverse(int a[]) { int[] b = new int[a.length]; for (int i = 0, j = a.length; i < a.length; i++, j--) { b[j - 1] = a[i]; } return b; } static long[] reverse(long a[]) { long[] b = new long[a.length]; for (int i = 0, j = a.length; i < a.length; i++, j--) { b[j - 1] = a[i]; } return b; } static void shuffle(Object[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); Object temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class tup implements Comparable<tup>, Comparator<tup>{ int a, b; tup(int a,int b){ this.a=a; this.b=b; } public tup() { } @Override public int compareTo(tup o){ return Integer.compare(b,o.b); } @Override public int compare(tup o1, tup o2) { return Integer.compare(o1.b, o2.b); } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; tup other = (tup) obj; return a==other.a && b==other.b; } @Override public String toString() { return a + " " + b; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int size) { int[] a = new int[size]; for(int i = 0; i < size; i++) { a[i] = nextInt(); } return a; } long[] readLongArray(int size) { long[] a = new long[size]; for(int i = 0; i < size; i++) { a[i] = nextLong(); } return a; } } static void dbg(int[] arr) { System.out.println(Arrays.toString(arr)); } static void dbg(long[] arr) { System.out.println(Arrays.toString(arr)); } static void dbg(boolean[] arr) { System.out.println(Arrays.toString(arr)); } static void dbg(Object... args) { for (Object arg : args) System.out.print(arg + " "); System.out.println(); } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.Scanner; public class D2 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int array[] =new int[n]; for(int i=0; i<=n-1; i++) { array[i] = sc.nextInt(); } int m = sc.nextInt(); int result = count(array); for(int i=1; i<=m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); result += (b-a)*(b-a+1)/2; result=result%2; if(result%2==1) System.out.println("odd"); else System.out.println("even"); } } public static int count(int[] arr) { int[] array = arr.clone(); return sort(array,0,array.length-1); } public static int sort(int[] arr, int i, int j) { if(i>=j) return 0; int mid = (i+j)/2; int a = sort(arr,i,mid); int b = sort(arr,mid+1,j); int addition = 0; int r1 = mid+1; int[] tmp = new int[arr.length]; int tIndex = i; int cIndex=i; while(i<=mid&&r1<=j) { if (arr[i] <= arr[r1]) tmp[tIndex++] = arr[i++]; else { tmp[tIndex++] = arr[r1++]; addition+=mid+1-i; } } while (i <=mid) { tmp[tIndex++] = arr[i++]; } while ( r1 <= j ) { tmp[tIndex++] = arr[r1++]; } while(cIndex<=j){ arr[cIndex]=tmp[cIndex]; cIndex++; } return a+b+addition; } }
quadratic
911_D. Inversion Counting
CODEFORCES
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { static int check(int temp) { int count1 = 0; while (temp>0) { if(temp % 2 != 0) count1++; temp/= 2; } return count1; } public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc=new Scanner(System.in); String a=sc.next(); String b=sc.next(); int m=a.length(); int n=b.length(); int[] zero=new int[n]; int[] one=new int[n]; for(int i=0;i<n;i++) { if(i==0) { if(b.charAt(i)=='0') zero[i]++; else one[i]++; } else { zero[i]=zero[i-1]; one[i]=one[i-1]; if(b.charAt(i)=='0') zero[i]++; else one[i]++; } } long res=0; for(int i=0;i<m;i++) { int x=n-m+i; if(a.charAt(i)=='0') res+=one[x]; else res+=zero[x]; if(i>0) { if(a.charAt(i)=='0') res-=one[i-1]; else res-=zero[i-1]; } } System.out.println(res); } }
linear
608_B. Hamming Distance Sum
CODEFORCES
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; public class Main{ private static Parser in; private static PrintWriter out; public static void main(String[] args){ in = new Parser(System.in); out = new PrintWriter(System.out); // // char[] ccc = new char[1]; // String ddd = "abcdef"; // ddd.getChars(2, 3, ccc, 0); // // String sssss = new String(ccc); // // System.out.println(sssss); // String s = in.nextString(100); int len = 0; String ss = ""; l:for (int i = 1; i<=s.length(); i++){ for(int j = 0; j+i<=s.length();j++){ char[] c = new char[i]; char[] cc = new char[i]; s.getChars(j, j+i, c, 0); String sss = new String(c); //System.out.println(sss); for(int k = j+1; k+i<=s.length();k++){ s.getChars(k, k+i, cc, 0); String ssss = new String(cc); if(sss.equals(ssss)) {len = i; continue l;} } } } System.out.println(len); // out.flush(); } } class Parser { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parser(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString(int size) { byte[] ch = new byte[size]; int point = 0; try { byte c = read(); while (c == ' ' || c == '\n' || c=='\r') c = read(); while (c != ' ' && c != '\n' && c!='\r') { ch[point++] = c; c = read(); } } catch (Exception e) {} return new String(ch,0,point); } public int nextInt() { int ret = 0; boolean neg; try { byte c = read(); while (c <= ' ') c = read(); neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; } catch (Exception e) {} return ret; } public long nextLong() { long ret = 0; boolean neg; try { byte c = read(); while (c <= ' ') c = read(); neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; } catch (Exception e) {} return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); } catch (Exception e) {} if (bytesRead == -1) buffer[0] = -1; } private byte read() { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class C2 { String filename = null; InputReader sc; void solve() { int n = sc.nextInt(); int[] a = sc.nextArray(n); int[] ps = new int[n]; int[] q = new int[n]; int[] qs = new int[n]; int nq = 0; for (int i = 1; i < n; i++) { if (a[i] == 1) { qs[nq] = i - 1; q[nq++] = a[i - 1] + 1; ps[i] = i - 1; } else { if (a[i] == a[i - 1] + 1) { qs[nq] = i - 1; q[nq++] = 1; ps[i] = i - 1; } else { for (int j = nq - 1; j >= 0; j--) { if (a[i] == q[j]) { ps[i] = qs[j]; nq = j; break; } } } } } int[] parents = ps; String[] strs = new String[n]; strs[0] = "1"; System.out.println(strs[0]); for (int i = 1; i < n; i++) { String p = strs[parents[i]]; if (a[i] == 1) { strs[i] = p + ".1"; } else { int lastDot = p.lastIndexOf("."); if (lastDot == -1) { strs[i] = a[i] + ""; } else { strs[i] = p.substring(0, lastDot) + "." + a[i]; } } System.out.println(strs[i]); } } public void run() throws FileNotFoundException { if (filename == null) { sc = new InputReader(System.in); } else { sc = new InputReader(new FileInputStream(new File(filename))); } int nTests = sc.nextInt(); for (int test = 0; test < nTests; test++) { solve(); } } public static void main(String[] args) { C2 sol = new C2(); try { sol.run(); } catch (FileNotFoundException e) { e.printStackTrace(); } } 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 float nextFloat() { return Float.parseFloat(next()); } public double nextDouble() { return Float.parseFloat(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] nextArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } } }
cubic
1523_C. Compression and Expansion
CODEFORCES
import java.util.*; public class A23 { public static void main(String[] args){ Scanner sc = new Scanner(System.in); char[] input = sc.nextLine().toCharArray(); int[][] dyn = new int[input.length][input.length]; int max = 0; for(int a = 0; a < input.length; a++) { for(int b = a + 1; b < input.length; b++) { if(input[a] == input[b]) { int prev = (a == 0) ? 0 : dyn[a-1][b-1]; dyn[a][b] = prev + 1; max = (dyn[a][b] > max) ? dyn[a][b] : max; } } } System.out.println(max); } }
cubic
23_A. You're Given a String...
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import static java.lang.Math.*; public class Main2 { private FastScanner scanner = new FastScanner(); public static void main(String[] args) { new Main2().solve(); } private void solve() { int n = scanner.nextInt(); int a[][] = new int[n][3]; for (int i = 0; i < n; i++) { a[i][0] = scanner.nextInt(); a[i][1] = scanner.nextInt(); a[i][2] = i; } int l = -1, r = -1; Arrays.sort(a, (o1, o2) -> { if (o1[0] != o2[0]) { return o1[0] - o2[0]; } else { return o2[1] - o1[1]; } }); int maxr = -1, maxi = -1; for (int i = 0; i < n; i++) { if (a[i][1] <= maxr) { l = a[i][2] + 1; r = maxi + 1; break; } if (a[i][1] > maxr) { maxi = a[i][2]; maxr = a[i][1]; } } System.out.println(l + " " + r); } boolean check(int cnt[][], int[] tcnt, int mid) { boolean ok = true; for (int j = 0; j < 27; j++) { if (cnt[mid][j] < tcnt[j]) { ok = false; } } return ok; } class Pair { int c, f; } class FastScanner { BufferedReader reader; StringTokenizer tokenizer; FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } Integer[] nextA(int n) { Integer a[] = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } return a; } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } } }
nlogn
976_C. Nested Segments
CODEFORCES
import java.io.*; import java.util.*; public class TaskE { static int[][] transpose(int[][] a, int n, int m) { int[][] t = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { t[j][i] = a[i][j]; } } return t; } public static void main(String[] args) { FastReader in = new FastReader(System.in); // FastReader in = new FastReader(new FileInputStream("input.txt")); PrintWriter out = new PrintWriter(System.out); // PrintWriter out = new PrintWriter(new FileOutputStream("output.txt")); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[n + 1][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); a[n][j] = Math.max(a[n][j], a[i][j]); } } a = transpose(a, n, m); Arrays.sort(a, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { int max1 = 0; for (int i = 0; i < o1.length; i++) { max1 = Math.max(max1, o1[i]); } int max2 = 0; for (int i = 0; i < o2.length; i++) { max2 = Math.max(max2, o2[i]); } return max2 - max1; } }); a = transpose(a, m, n); int[] dp = new int[1 << n]; for (int i = 0; i < Math.min(n, m); i++) { int[] best = new int[1 << n]; for (int j = 1; j < (1 << n); j++) { for (int k = 0; k < n; k++) { int sum = 0; for (int l = 0; l < n; l++) { if ((j & (1 << l)) != 0) sum += a[(l + k) % n][i]; } best[j] = Math.max(best[j], sum); } } int[] dp1 = dp.clone(); for (int j = 0; j < (1 << n); j++) { for (int k = j; k > 0; k = (k - 1) & j) { dp[j] = Math.max(dp[j], dp1[k ^ j] + best[k]); } } } out.println(dp[(1 << n) - 1]); } out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } Integer nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } Double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
np
1209_E2. Rotate Columns (hard version)
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.PriorityQueue; import java.util.Set; //@Japanese /* PriorityQueueは拡張for文で出すとsortされてない順番で出てくる * longのbit演算は1L<<posに注意 * JOIはMLEが厳しい。最悪shortを使う。 * ArrayListはオートボクシングが遅いから、最悪自作listを使う */ /*略語 * 2-to, 4-for, 8-from * -L -long(型), -P -素数Pを法とした余り * a,b -任意の引数, n,m -自然数, p -素数 * pos -postition * abs -絶対値 * min -minimum, max -maximum, ave -average * div -divide * pow -power(累乗) * ceil -ceiling(天井関数) * dt -data * ln -length * sc -scanner * INF -INFINITY * e97 -10E9+7=1000000007(prime often used) */ public class Main { public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int h = sc.nexI(); int w = sc.nexI(); int k = sc.nexI(); Graph grid = new Graph(h*w); for(int i=0; i<h; i++) { for(int j=1; j<w; j++) { long w1 = sc.nexL(); grid.add2(getad(w, i, j-1), getad(w, i, j), w1); } } for(int i=1; i<h; i++) { for(int j=0; j<w; j++) { long w1 = sc.nexL(); grid.add2(getad(w, i-1, j), getad(w, i, j), w1); } } if(k%2 != 0) { int[][] anss = new int[h][w]; fill(anss,-1); for(int i=0; i<h; i++) { prtspas(anss[i]); } return; } if((h*w) == 1) { System.out.println(-1); return; } long[][] mincos = new long[(k/2)+1][h*w]; fill(mincos[0],0L); for(int t=1; t<=(k/2); t++) { fill(mincos[t], INFL); for(int i=0; i<h; i++) { for(int j=0; j<w; j++) { int ad = getad(w, i, j); for(Edge e: grid.get(ad)) { mincos[t][ad] = min(mincos[t][ad], mincos[t-1][e.v2]+e.w); } } } } for(int i=0; i<(h*w); i++) { mincos[k/2][i]*=2L; } for(int i=0; i<h; i++) { prtspas(Arrays.copyOfRange(mincos[k/2], i*w, i*w + w)); } out.flush(); return; } public static int getad(int w, int i, int j) { return (i*w + j); } static class Graph { // @Japanese 重み付きグラフ private ArrayList<Node> dt = new ArrayList<>(); Graph(int sz) { for (int i = 0; i < sz; i++) { Node node1 = new Node(); dt.add(node1); } } public void add(int v8, int cnct2, long w) { dt.get(v8).add(new Edge(v8, cnct2, w)); } public void add2(int v1, int v2, long w) { dt.get(v1).add(new Edge(v1, v2, w)); dt.get(v2).add(new Edge(v2, v1, w)); } public Set<Edge> get(int v) { return dt.get(v).getAll(); } public int size() { return dt.size(); } public int sizeOf(int v) { return dt.get(v).size(); } public void clear() { for (int i = 0; i < dt.size(); i++) dt.get(i).clear(); } public void clear(int v) { dt.get(v).clear(); } private void add_v(Node v_new) { dt.add(v_new); } public void show2() { for (int i = 0; i < dt.size(); i++) { System.out.print(i + ":"); for (Edge e : dt.get(i).getAll()) e.show2(); System.out.println(); } } public static Graph make_Graph(int vn, int en, FastScanner sc) { Graph g = new Graph(vn); for (int i = 0; i < en; i++) { int s1 = sc.nexI() - 1; int g1 = sc.nexI() - 1; long w = sc.nexL(); g.add2(s1, g1, w); } return g; } public static Graph make_tree(int vn, FastScanner sc) { Graph g = new Graph(vn); for (int i = 1; i < vn; i++) { int s1 = sc.nexI() - 1; int g1 = sc.nexI() - 1; long w = sc.nexL(); g.add2(s1, g1, w); } return g; } private long[] dijkstra(int from) { PriorityQueue<Edge> dijk = new PriorityQueue<>(new CompEdge_float()); long[] d8i = new long[this.dt.size()]; fill(d8i, INFL); dijk.add(new Edge(from, 0L)); while (!dijk.isEmpty()) { Edge dw = dijk.poll(); if (d8i[dw.v2] > dw.w) { d8i[dw.v2] = dw.w; for (Edge e : this.get(dw.v2)) { long w2 = dw.w + e.w; if (d8i[e.v2] > w2) dijk.add(new Edge(e.v2, w2)); } } } return d8i; } } static class Node { // 重みつきグラフの頂点 private Set<Edge> next_vs = new HashSet<>(); public void add(Edge cnct2) { next_vs.add(cnct2); } public Set<Edge> getAll() { return next_vs; } public int size() { return next_vs.size(); } public void clear() { next_vs.clear(); } public void addAll(Node list2add) { this.next_vs.addAll(list2add.next_vs); } } static class Edge { // @Japanese 重み着きのグラフの辺 int from = -1, v2 = -1; long w; public Edge(int going2, long weight_route) { this.v2 = going2; this.w = weight_route; } public Edge(int come8, int going2, long weight_route) { this.from = come8; this.v2 = going2; this.w = weight_route; } public void show2() { System.out.println(this.from + "->" + this.v2 + " :w=" + this.w); } } static class CompEdge_float implements Comparator<Edge> { // 今は小さいのが前に出てくる public int compare(Edge a, Edge b) { if (a.w > b.w) return 1; else if (a.w < b.w) return -1; else return a.v2 - b.v2; } } private static final int INF = (int) 3e8; private static final long INFL = (long) 1e17; private static final int INTMAX = Integer.MAX_VALUE; private static final long LONGMAX = Long.MAX_VALUE; private static final long e97 = 1000000007L; private static final long e99 = 998244353L; private static final double PI = Math.PI; private static void assertion(boolean should_true) { // throw Error if should_true is not true @Japanese「断言」 if (!should_true) throw new AssertionError(); } private static int abs(int a) { return (a >= 0) ? a : -a; } private static long abs(long a) { return (a >= 0L) ? a : -a; } private static double abs(double a) { return (a >= 0.0) ? a : -a; } private static int min(int a, int b) { return (a < b) ? a : b; } private static long min(long a, long b) { return (a < b) ? a : b; } private static double min(double a, double b) { return (a < b) ? a : b; } private static int max(int a, int b) { return (a > b) ? a : b; } private static long max(long a, long b) { return (a > b) ? a : b; } private static double max(double a, double b) { return (a > b) ? a : b; } private static int pow2(int num2pow) { if (num2pow > 4e4) throw new IllegalArgumentException("Input is to Large. Use Long."); return num2pow * num2pow; } private static long pow2(long num2pow) { if (num2pow > 1e8) throw new IllegalArgumentException("Input is to Large. Use PowP."); return num2pow * num2pow; } private static int pow(int num_powered, int index) { int ans = 1; for (int i = 0; i < index; i++) { if (ans >= (INTMAX / num_powered)) throw new IllegalArgumentException("Input is to Large. Use Long."); ans *= num_powered; } return ans; } private static long pow(long num_powered, int index) { long ans = 1L; for (int i = 0; i < index; i++) { if (ans >= (LONGMAX / num_powered)) throw new IllegalArgumentException("Input is to Large. Use PowP."); ans *= num_powered; } return ans; } private static long powP(long num_powered, long index, long p) { // O(log(index)) // @Japanese 繰り返し二乗法 if (num_powered == 0L) return 0L; if (index == 0L) return 1L; if (index == 2L) { return (pow2(num_powered) % p); } int d = getDigit2(index); long[] num_done_by2 = new long[d + 1]; num_done_by2[0] = num_powered; for (int i = 1; i <= d; i++) { num_done_by2[i] = num_done_by2[i - 1] * num_done_by2[i - 1]; num_done_by2[i] %= p; } long ans = 1L; for (int i = d; i >= 0; i--) { long cf = (1L << (long) i); if (index >= cf) { index -= cf; ans = ans * num_done_by2[i]; ans %= p; } } return ans; } private static double hypod(double a, double b) { return Math.sqrt(a * a + b * b); } private static int getDigit2(long num2know) { // O(log(n)) long compare4 = 1L; int digit = 0; while (num2know >= compare4) { digit++; compare4 = (1L << (long) digit); } return digit; // num < 2^digit } private static int getDigit10(long num2know) { // O(log10(n)) long compare4 = 1L; int digit = 0; while (num2know >= compare4) { digit++; compare4 *= 10L; } return digit; // @Japanese num は digit桁の数で、10^digit未満 } private static int divceil(int numerator, int denominator) { return (numerator + denominator - 1) / denominator; } private static long divceil(long numerator, long denominator) { return (numerator + denominator - 1L) / denominator; } private static long factorial(int n) { // O(n) long ans = 1L; for (long i = 2; i <= n; i++) { if (ans >= (LONGMAX / i)) throw new IllegalArgumentException("Input is to Large. Use facP."); ans *= i; } return ans; } private static long facP(int n, long p) { // O(n) see also PermulationCombination:O(max_sz)+Q long ans = 1L; for (long i = 2; i <= n; i++) { ans *= i; ans %= p; } return ans; } private static long lcm(long m, long n) { long ans = m / gcd(m, n); if (ans >= (LONGMAX / n)) throw new IllegalArgumentException("Input is to Large."); ans *= n; return ans; } private static long gcd(long m, long n) { // O(log(m+n)) if ((m <= 0L) || (n <= 0L)) throw new IllegalArgumentException("m and n should be natural."); while ((m > 0L) && (n > 0L)) { if (m >= n) m %= n; else n %= m; } if (m > 0L) return m; else return n; } private static boolean is_prime(long n2check) { // O(√n) if (n2check == 1L) return false; for (long i = 2L; i <= Math.sqrt(n2check); i++) { if (n2check % i == 0L) return false; } return true; } private static int safe_mod(int n, int p) { n %= p; if (n >= 0) return n; return (n + p); } private static long safe_mod(long n, long p) { n %= p; if (n >= 0L) return n; return (n + p); } private static long modinv(long n, long p) { // @Japanese 逆元を求める // O(10log(n)) // pは素数でなくてもよい // ネットから拾ってきたのが理解不能だったので、行列計算を用いて非効率的アルゴリズムを書いた n %= p; if ((p == 1L) || (gcd(n, p) != 1L)) throw new IllegalArgumentException("n and p should be coprime."); // @Japanese // yn≡1(mod p) // <-> xp+yn=1; (n<p) // ...(sx+ty)a+(ux+vy)b=1 (|sv-tu|=1) // ...(sx+ty)a+(ux+vy)=1 // <- sx+ty=0, ux+vy=1 long a = p, b = n, s = 1L, t = 0L, u = 0L, v = 1L; while (b > 1) { long quo = a / b, rem = a % b; a = b; b = rem; long s2 = s * quo + u, t2 = t * quo + v; u = s; v = t; s = s2; t = t2; } long det = s * v - t * u; if (abs(det) != 1L) throw new ArithmeticException("My algorithm was Wrong!!"); s /= det; s %= p; if (s < 0L) s += p; return s; } private static int minAll(int[] dt4min) { // O(n) int min = INF; for (int element : dt4min) { if (element < min) min = element; } return min; } private static long minAll(long[] dt4min) { // O(n) long min = INFL; for (long element : dt4min) { if (element < min) min = element; } return min; } private static int maxAll(int[] dt4max) { // O(n) int max = -INF; for (int element : dt4max) { if (element > max) max = element; } return max; } private static long maxAll(long[] dt4max) { // O(n) long max = -INFL; for (long element : dt4max) { if (element > max) max = element; } return max; } private static int sumAll(int[] dt4sum) { // O(n) int sum_of_dt = 0; for (int element : dt4sum) { if (sum_of_dt > (INTMAX - element)) throw new IllegalArgumentException("Input is to Large. Use Long."); sum_of_dt += element; } return sum_of_dt; } private static long sumAll(long[] dt4sum) { // O(n) long sum_of_dt = 0L; for (long element : dt4sum) { if (sum_of_dt > (LONGMAX - element)) throw new IllegalArgumentException("Input is to Large."); sum_of_dt += element; } return sum_of_dt; } private static int sumAll(ArrayList<Integer> dt4sum) { int sum_of_dt = 0; for (long element : dt4sum) { if (sum_of_dt > (INTMAX - element)) throw new IllegalArgumentException("Input is to Large. Use Long."); sum_of_dt += element; } return sum_of_dt; } private static int[] reverse(int[] as) { int ln = as.length; int[] bs = new int[ln]; for (int i = 0; i < ln; i++) bs[i] = as[ln - i - 1]; return bs; } private static void reverseSub(int[] as, int S_include, int Gnot_include) { // O(G-S) int ln = Gnot_include - S_include; int[] bs = new int[ln]; for (int i = S_include; i < Gnot_include; i++) bs[i - S_include] = as[i]; for (int i = 0; i < ln; i++) as[i + S_include] = bs[ln - i - 1]; } private static boolean is_in_area(int y, int x, int height, int width) { if (y < 0) return false; if (x < 0) return false; if (y >= height) return false; if (x >= width) return false; return true; } private static boolean is_in_area(Vector v, int height, int width) { if (v.y < 0) return false; if (v.x < 0) return false; if (v.y >= height) return false; if (v.x >= width) return false; return true; } private static int nC2(int n) { return ((n * (n - 1)) / 2); } private static long nC2(long n) { return ((n * (n - 1L)) / 2L); } private static int iflag(int pos) { if (pos >= 32) throw new IllegalArgumentException("Input is to Large. Use Long."); return (1 << pos); } private static long flag(int pos) { if (pos >= 64) throw new IllegalArgumentException("Input is to Large. Use Long."); return (1L << (long) pos); } private static boolean isFlaged(int bit, int pos) { if (pos >= 32) throw new IllegalArgumentException("Input is to Large."); return ((bit & (1 << pos)) != 0); } private static boolean isFlaged(long bit, int pos) { if (pos >= 64) throw new IllegalArgumentException("Input is to Large."); return ((bit & (1L << (long) pos)) != 0L); } private static int deflag(int bit, int pos) { return (bit & (~(1 << pos))); } private static int countFlaged(int bit) { int ans = 0; for (int i = 0; i < 31; i++) { if ((bit & (1 << i)) != 0) ans++; } return ans; } private static int countFlaged(long bit) { int ans = 0; for (long i = 0L; i < 63L; i++) { if ((bit & (1L << i)) != 0L) ans++; } return ans; } private static int[] Xdir4 = { 1, 0, 0, -1 }; private static int[] Ydir4 = { 0, 1, -1, 0 }; private static int[] Xdir8 = { 1, 1, 1, 0, 0, -1, -1, -1 }; private static int[] Ydir8 = { 1, 0, -1, 1, -1, 1, 0, -1 }; public static int biSearch(int[] dt, int target) { // O(log(dt.length)) // dt should be sorted in 0->INF // return adress of target int left = 0, right = dt.length - 1; int mid = -1; while (left <= right) { mid = ((right + left) / 2); if (dt[mid] == target) return mid; if (dt[mid] < target) left = (mid + 1); else right = (mid - 1); } return -1; } public static int biSearchMax(long[] dt, long target) { // O(log(dt.length)) // dt should be sorted in 0->INF int left = -1, right = dt.length, mid = -1; while ((right - left) > 1) { mid = ((right + left) / 2); if (dt[mid] <= target) left = mid; else right = mid; } return left; // @Japanese target以下の最大のaddress } public static int biSearchMin(long[] dt, long target) { // O(log(dt.length)) // dt should be sorted in 0->INF int left = -1, right = dt.length, mid = -1; while ((right - left) > 1) { mid = ((right + left) / 2); if (dt[mid] <= target) left = mid; else right = mid; } return right; // @Japanese targetより大きい最小のaddress } private static void fill(boolean[] target, boolean reset) { for (int i = 0; i < target.length; i++) target[i] = reset; } private static void fill(int[] target, int reset) { for (int i = 0; i < target.length; i++) target[i] = reset; } private static void fill(long[] target, long reset) { for (int i = 0; i < target.length; i++) target[i] = reset; } private static void fill(char[] target, char reset) { for (int i = 0; i < target.length; i++) target[i] = reset; } private static void fill(double[] target, double reset) { for (int i = 0; i < target.length; i++) target[i] = reset; } private static void fill(boolean[][] target, boolean reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { target[i][j] = reset; } } } private static void fill(int[][] target, int reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { target[i][j] = reset; } } } private static void fill(long[][] target, long reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { target[i][j] = reset; } } } private static void fill(char[][] target, char reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { target[i][j] = reset; } } } private static void fill(double[][] target, double reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { target[i][j] = reset; } } } private static void fill(int[][][] target, int reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { for (int k = 0; k < target[i][j].length; k++) { target[i][j][k] = reset; } } } } private static void fill(long[][][] target, long reset) { for (int i = 0; i < target.length; i++) { for (int j = 0; j < target[i].length; j++) { for (int k = 0; k < target[i][j].length; k++) { target[i][j][k] = reset; } } } } private static void fill_parent(int[] parent) { for (int i = 0; i < parent.length; i++) { parent[i] = i; } } private static void showBit(int bit) { for (int i = 0; i < getDigit2(bit); i++) { if (isFlaged(bit, i)) System.out.print("O"); else System.out.print("."); } System.out.println(); } private static void showBit(long bit) { for (int i = 0; i < getDigit2(bit); i++) { if (isFlaged(bit, i)) System.out.print("O"); else System.out.print("."); } System.out.println(); } static void show2(boolean[][] dt, String cmnt) { for (int i = 0; i < dt.length; i++) { for (int j = 0; j < dt[i].length; j++) { if (dt[i][j]) System.out.print("O"); else System.out.print("."); } if (!cmnt.equals("")) System.out.print("<-" + cmnt); System.out.println(" :" + i); } } static void show2(int[][] dt, String cmnt) { for (int i = 0; i < dt.length; i++) { for (int j = 0; j < dt[i].length; j++) System.out.print(dt[i][j] + ","); if (!cmnt.equals("")) System.out.print("<-" + cmnt); System.out.println(" :" + i); } } static void show2(long[][] dt, String cmnt) { for (int i = 0; i < dt.length; i++) { for (int j = 0; j < dt[i].length; j++) System.out.print(dt[i][j] + ","); if (!cmnt.equals("")) System.out.print("<-" + cmnt); System.out.println(" :" + i); } } static void show2(ArrayDeque<Long> dt) { long element = 0; while (dt.size() > 0) { element = dt.removeFirst(); System.out.print(element); } System.out.println("\n"); } static void show2(List<Object> dt) { for (int i = 0; i < dt.size(); i++) System.out.print(dt.get(i) + ","); System.out.println("\n"); } private static void prtlnas(int[] array) { PrintWriter out = new PrintWriter(System.out); for (int e: array) out.println(e); out.flush(); } private static void prtlnas(long[] array) { PrintWriter out = new PrintWriter(System.out); for (long e: array) out.println(e); out.flush(); } private static void prtlnas(ArrayList<Object> array) { PrintWriter out = new PrintWriter(System.out); for (Object e: array) out.println(e); out.flush(); } private static void prtspas(int[] array) { PrintWriter out = new PrintWriter(System.out); out.print(array[0]); for (int i = 1; i < array.length; i++) out.print(" " + array[i]); out.println(); out.flush(); } private static void prtspas(long[] array) { PrintWriter out = new PrintWriter(System.out); out.print(array[0]); for (int i = 1; i < array.length; i++) out.print(" " + array[i]); out.println(); out.flush(); } private static void prtspas(double[] array) { PrintWriter out = new PrintWriter(System.out); out.print(array[0]); for (int i = 1; i < array.length; i++) out.print(" " + array[i]); out.println(); out.flush(); } private static void prtspas(ArrayList<Integer> array) { if (array.isEmpty()) return; PrintWriter out = new PrintWriter(System.out); out.print(array.get(0)); for (int i = 1; i < array.size(); i++) out.print(" " + array.get(i)); out.println(); out.flush(); } static class Vector { int x, y; public Vector(int sx, int sy) { this.x = sx; this.y = sy; } public boolean equals(Vector v) { return (this.x == v.x && this.y == v.y); } public void show2() { System.out.println(this.x + ", " + this.y); } public static int dist2(Vector a, Vector b) { int dx = abs(a.x - b.x); int dy = abs(a.y - b.y); if (dx > 3e4) throw new IllegalArgumentException("Input is to Large. Use Long."); if (dy > 3e4) throw new IllegalArgumentException("Input is to Large. Use Long."); return (dx * dx + dy * dy); } } static class CompVector implements Comparator<Vector> { public int compare(Vector a, Vector b) { if (a.x == b.x) return a.y - b.y; else return a.x - b.x; } } static class FastScanner { //@Japanese ネットから拾ってきた。よく分からん。 private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return (33 <= c) && (c <= 126); } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nexL() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b) || b == ':') { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nexI() { long nl = nexL(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) { throw new NumberFormatException(); } return (int) nl; } public double nexD() { return Double.parseDouble(next()); } // a means array public void ai(int[]... array) { for (int i = 0; i < array[0].length; i++) { for (int j = 0; j < array.length; j++) { array[j][i] = nexI(); } } return; } public void al(long[]... array) { for (int i = 0; i < array[0].length; i++) { for (int j = 0; j < array.length; j++) { array[j][i] = nexL(); } } return; } public void aimin1(int[] array) { for (int i = 0; i < array.length; i++) { array[i] = nexI() - 1; } return; } public void aD(double[] array) { for (int i = 0; i < array.length; i++) { array[i] = nexD(); } return; } public void ai2d(int[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { array[i][j] = nexI(); } } return; } public void al2d(long[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { array[i][j] = nexL(); } } return; } } } // END OF THE CODE
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; public class House { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int t = sc.nextInt(); ArrayList<HS> list = new ArrayList<HS>(); for (int i = 0; i < n; i++) { list.add(new HS(sc.nextInt(),sc.nextInt())); } Collections.sort(list); int count = 0; if(n >= 1) count = 2; for(int i = 0; i < list.size() - 1; i++){ double d = Math.abs(list.get(i + 1).x - list.get(i).x); d -= ((1.0*list.get(i).a/2.0) + (1.0*list.get(i + 1).a/2.0)); if ((d >= t)&& ((d-t) <= 0.00000001)){ count++; } else if(d > t){ count+= 2; } } System.out.println(count); } } class HS implements Comparable<HS> { public int x; public int a; public HS(int x, int a) { this.x = x; this.a = a; } public int compareTo(HS o) { return x - o.x; } }
nlogn
15_A. Cottage Village
CODEFORCES
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** What do you think? What do you think? 1st on Billboard, what do you think of it Next is a Grammy, what do you think of it However you think, I’m sorry, but shit, I have no fcking interest ******************************* I'm standing on top of my Monopoly board That means I'm on top of my game and it don't stop til my hip don't hop anymore https://www.a2oj.com/Ladder16.html ******************************* 300iq as writer = Sad! */ import java.util.*; import java.io.*; import java.math.*; public class x1242C2 { public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); long[] sums = new long[N]; ArrayList<Integer>[] boxes = new ArrayList[N]; for(int i=0; i < N; i++) { boxes[i] = new ArrayList<Integer>(); st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken()); while(a-->0) boxes[i].add(Integer.parseInt(st.nextToken())); for(int x: boxes[i]) sums[i] += x; } long lmaosum = 0L; for(long x: sums) lmaosum += x; if(Math.abs(lmaosum)%N != 0) { System.out.println("No"); return; } long target = lmaosum/N; //fuck fuck fuck fuck fuck fuck fuck fuck fuck fuck fuck fuck fuck fuck fuck HashMap<Long, Integer> map = new HashMap<Long, Integer>(); for(int k=0; k < N; k++) for(int x: boxes[k]) map.put((long)x, k); HashMap<Long, Long> edges = new HashMap<Long, Long>(); for(int k=0; k < N; k++) for(int x: boxes[k]) { long nextval = target-sums[k]+x; if(map.containsKey(nextval)) edges.put((long)x, nextval); } Node[] dp = new Node[1<<N]; dp[0] = new Node(-69, -69, 0); //precompute subsets ass Node[] subsets = new Node[1<<N]; for(int b=0; b < N; b++) for(int i=0; i < boxes[b].size(); i++) { if(!edges.containsKey((long)boxes[b].get(i))) continue; long curr = edges.get((long)boxes[b].get(i)); //shit shit shit shit shit shit shit shit shit shit int submask = 0; boolean cyclic = true; while(curr != boxes[b].get(i)) { int k = map.get(curr); if((submask&(1<<k)) > 0 || !edges.containsKey((long)curr)) { cyclic = false; break; } submask |= 1<<k; curr = edges.get((long)curr); } submask |= (1<<b); if(cyclic) subsets[submask] = new Node(-69, i, b); } for(int mask=1; mask < (1<<N); mask++) outer:for(int submask=mask; submask > 0; submask=(submask-1)&mask) if(dp[mask^submask] != null && subsets[submask] != null) { dp[mask] = new Node(mask^submask, subsets[submask].dex, subsets[submask].start); break outer; } if(dp[(1<<N)-1] == null) System.out.println("No"); else { StringBuilder sb = new StringBuilder("Yes\n"); long[][] res = new long[N][2]; for(int i=0; i < N; i++) res[i][1] = -1L; int currmask = (1<<N)-1; while(currmask != 0) { int submask = dp[currmask].mask; int i = dp[currmask].dex; int b = dp[currmask].start; long nextval = target-sums[b]+boxes[b].get(i); int curr = map.get(nextval); res[map.get(nextval)][0] = nextval; res[map.get(nextval)][1] = b; while(true) { int lol = map.get(nextval); nextval = edges.get(nextval); res[map.get(nextval)][0] = nextval; if(res[map.get(nextval)][1] != -1) break; res[map.get(nextval)][1] = lol; } currmask = dp[currmask].mask; } for(int k=0; k < N; k++) sb.append(res[k][0]+" ").append(res[k][1]+1).append("\n"); System.out.print(sb); } } } class Node { public int mask; public int dex; public int start; public Node(int a, int b, int c) { mask = a; dex = b; start = c; } }
np
1242_C. Sum Balance
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Practice { public static long mod = (long) Math.pow(10, 9) + 7; public static long[][][]dp; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); // int t = Integer.parseInt(br.readLine()); // while (t-- > 0) { String[] s2 = br.readLine().split(" "); int n = Integer.parseInt(s2[0]); int m = Integer.parseInt(s2[1]); int k = Integer.parseInt(s2[2]); dp=new long[n][m][k+1]; int[][] hori = new int[n][m - 1]; int[][] verti = new int[n - 1][m]; for (int i = 0; i < n; i++) { String str = (br.readLine()); String[] s1 = str.split(" "); for (int j = 0; j < m - 1; j++) { hori[i][j] = Integer.parseInt(s1[j]); } } for (int i = 0; i < n - 1; i++) { String str = (br.readLine()); String[] s1 = str.split(" "); for (int j = 0; j < m; j++) { verti[i][j] = Integer.parseInt(s1[j]); } } long[][]ans=new long[n][m]; if(k%2!=0) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { ans[i][j]=-1; } } }else { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { ans[i][j]=findAns(i,j,k,hori,verti,n,m,Integer.MAX_VALUE); } } } for(int i=0;i<n;i++) { StringBuilder str=new StringBuilder(); for(int j=0;j<m;j++) { str.append(ans[i][j]+" "); }pw.println(str.toString()); } // } pw.close(); } private static long findAns(int i, int j, int k, int[][] hori, int[][] verti, int n, int m, int last) { // TODO Auto-generated method stub if(k==0) { return 0; } if(i<n&&j<m&&i>=0&&j>=0) { }else { return 100000000; } // System.out.println(i+" "+j+" "+k); if(dp[i][j][k]!=0) { return dp[i][j][k]; } long ans=k*((long)last); if(j>0) { long curr=2*hori[i][j-1]; curr+=findAns(i, j-1, k-2, hori, verti, n, m, hori[i][j-1]); ans=Math.min(ans, curr); } // System.out.println(ans+" 0"); if(j<m-1) { long curr=2*hori[i][j]; curr+=findAns(i, j+1, k-2, hori, verti, n, m, hori[i][j]); ans=Math.min(ans, curr); } // System.out.println(ans+" 1"); if(i>0) { long curr=2*verti[i-1][j]; curr+=findAns(i-1, j, k-2, hori, verti, n, m, verti[i-1][j]); ans=Math.min(ans, curr); } // System.out.println(ans+" 2"); if(i<n-1) { long curr=2*verti[i][j]; curr+=findAns(i+1, j, k-2, hori, verti, n, m, verti[i][j]); ans=Math.min(ans, curr); } // System.out.println(ans+" 3"); dp[i][j][k]=ans; return ans; } } //private static long getGCD(long l, long m) { //// TODO Auto-generated method stub // //long t1 = Math.min(l, m); //long t2 = Math.max(l, m); //while (true) { // long temp = t2 % t1; // if (temp == 0) { // return t1; // } // t2 = t1; // t1 = temp; //} //}
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class Handbag { // http://codeforces.com/problemset/problem/8/C // Source of most code : http://codeforces.com/contest/8/submission/3492661 // Keep track of each item location and also be able to // calculate distance between it and another object public static class Item{ int x; int y; Item(int x, int y){ this.x = x; this.y = y; } // Return distance between two points public int dist(Item i){ int dx = x - i.x; int dy = y - i.y; return dx*dx + dy*dy; } } // Each value in bits[] is the min time to get certain objects // Ex. bits[6] = 110 is the fastest time to get items that correspond with the '1s' public static int solve(int bitNum){ if(bitNum == (1 << N) - 1) // If bitNum is too big for the array return 0; if(bits[bitNum] != -1) // If bit value has already been calculated return bits[bitNum]; int ans = Integer.MAX_VALUE; int j = 0; for(int i = 1; i < N; i++){ if((bitNum & (1 << i)) == 0){ // Performs bitwise AND operation to see if bitNum and i have no bits in common if(j == 0){ // Only happens on the first time in IF statement // One item that can be picked up before returning to handbag ans = 2 * items[0].dist(items[i]) + solve(bitNum | (1 << i)); // Performs bitwise exclusive OR operation j = i; // Change value so this case isn't ever hit again && to store value to use in else statement dists } else{ // Find the distance between the handbag and the first item int dist1 = items[0].dist(items[i]); // Find the distance between the first item and the second item int dist2 = items[i].dist(items[j]); // Find the distance between the second item and the handbag int dist3 = items[j].dist(items[0]); // Two items that can be picked up before returning to handbag // distance covered between any two objects in the time equal // to the squared length of the segment between the points of the objects ans = Math.min(ans, dist1 + dist2 + dist3 + solve(bitNum | (1 << i) | (1 << j))); // Performs bitwise exclusive OR operation } } } return bits[bitNum] = ans; // Store all values in bits[] to speed up solve and for use in printOptPath } static void printOptPath(int bitNum) { if (bitNum == (1 << N) - 1) return; // Almost identical to solve equation except it doesn't calculate the answer, it checks the stored answer in bits int j = 0; for (int i = 1; i < N; i++) if ((bitNum & (1 << i)) == 0) { if (j == 0) { j = i; // Change value so this case isn't ever hit again && to find distance to this specific item in else if statement if (bits[bitNum] == 2 * items[0].dist(items[i]) + solve(bitNum | (1 << i))) { // solve() should quickly return an answer because the bits[] has already been calculated pw.print(" " + i + " 0"); // One item that can be picked up before returning to handbag printOptPath(bitNum | (1 << i)); // Recursively call print with new bitNum return; } } else if (bits[bitNum] == items[0].dist(items[i]) + items[i].dist(items[j]) + items[j].dist(items[0]) + solve(bitNum | (1 << i) | (1 << j))) { pw.print(" " + j + " " + i + " 0"); // Two items that can be picked up before returning to handbag printOptPath(bitNum | (1 << i) | (1 << j)); // Recursively call print with new bitNum return; } } } private static int N = 0; private static Item[] items; private static int[] bits; // PrintWriter needs to be class member because of recursive print strategy private static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] input = br.readLine().split(" "); Item handbag = new Item(Integer.parseInt(input[0]), Integer.parseInt(input[1])); N = Integer.parseInt(br.readLine()) + 1; items = new Item[N]; for(int n = 1; n < N; n++){ input = br.readLine().split(" "); items[n] = new Item(Integer.parseInt(input[0]), Integer.parseInt(input[1])); } items[0] = handbag; // x << n is a right shift operator // which will remove the last n bits from x // Ex 1 << 2 => 4 bits = new int[1 << N]; // Ex: 1 << 3 = 8; 1 << 5 = 64 Arrays.fill(bits, -1); // Init bits array to hold -1 values int ans = solve(1 << 0); // Start solving with bit #1 pw.println(ans); // Min time needed to put items in handbag pw.print("0"); // Init output with handbag location printOptPath(1 << 0); // Print possible optimum path to pick up items pw.close(); } }
np
8_C. Looking for Order
CODEFORCES
/* Codeforces Template */ import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { static long initTime; static final Random rnd = new Random(7777L); static boolean writeLog = false; public static void main(String[] args) throws IOException { initTime = System.currentTimeMillis(); try { writeLog = "true".equals(System.getProperty("LOCAL_RUN_7777")); } catch (SecurityException e) {} new Thread(null, new Runnable() { public void run() { try { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) {} long prevTime = System.currentTimeMillis(); new Main().run(); log("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); log("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); in.close(); } /*************************************************************** * Solution **************************************************************/ void solve() throws IOException { long leftBorder = nextLong(); long rightBorder = nextLong(); long[][][][][] dp = new long [64][2][2][2][2]; for (long[][][][] a : dp) for (long[][][] b : a) for (long[][] c : b) for (long[] d : c) fill(d, -1L); dp[63][0][0][0][0] = 0L; for (int lastBit = 63; lastBit > 0; lastBit--) { int curBit = lastBit - 1; int leftBit = (int) ((leftBorder >> curBit) & 1L); int rightBit = (int) ((rightBorder >> curBit) & 1L); for (int agl = 0; agl < 2; agl++) { for (int alr = 0; alr < 2; alr++) { for (int bgl = 0; bgl < 2; bgl++) { for (int blr = 0; blr < 2; blr++) { long prvXor = dp[lastBit][agl][alr][bgl][blr]; if (prvXor < 0L) continue; for (int ab = 0; ab < 2; ab++) { int nagl = left(agl, leftBit, ab); int nalr = right(alr, rightBit, ab); if (nagl < 0 || nalr < 0) continue; for (int bb = 0; bb < 2; bb++) { int nbgl = left(bgl, leftBit, bb); int nblr = right(blr, rightBit, bb); if (nbgl < 0 || nblr < 0) continue; long setBit = ab ^ bb; dp[curBit][nagl][nalr][nbgl][nblr] = max(dp[curBit][nagl][nalr][nbgl][nblr], prvXor | (setBit << curBit)); } } } } } } } long answer = -1L; for (int agl = 0; agl < 2; agl++) { for (int alr = 0; alr < 2; alr++) { for (int bgl = 0; bgl < 2; bgl++) { for (int blr = 0; blr < 2; blr++) { answer = max(answer, dp[0][agl][alr][bgl][blr]); } } } } // System.err.println(Long.toBinaryString(leftBorder)); // System.err.println(Long.toBinaryString(rightBorder)); // System.err.println(Long.toBinaryString(answer)); out.println(answer); } int left(int gl, int leftBit, int b) { if (gl == 0) { if (b < leftBit) return -1; if (b == leftBit) return 0; if (b > leftBit) return 1; } return 1; } int right(int lr, int rightBit, int b) { if (lr == 0) { if (b < rightBit) return 1; if (b == rightBit) return 0; if (b > rightBit) return -1; } return 1; } /*************************************************************** * Input **************************************************************/ BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int[] nextIntArray(int size) throws IOException { int[] ret = new int [size]; for (int i = 0; i < size; i++) ret[i] = nextInt(); return ret; } long[] nextLongArray(int size) throws IOException { long[] ret = new long [size]; for (int i = 0; i < size; i++) ret[i] = nextLong(); return ret; } double[] nextDoubleArray(int size) throws IOException { double[] ret = new double [size]; for (int i = 0; i < size; i++) ret[i] = nextDouble(); return ret; } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } /*************************************************************** * Output **************************************************************/ void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { if (array == null || array.length == 0) return; boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings("rawtypes") void printCollection(Collection collection) { if (collection == null || collection.isEmpty()) return; boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } /*************************************************************** * Utility **************************************************************/ static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } static void checkMemory() { System.err.println(memoryStatus()); } static long prevTimeStamp = Long.MIN_VALUE; static void updateTimer() { prevTimeStamp = System.currentTimeMillis(); } static long elapsedTime() { return (System.currentTimeMillis() - prevTimeStamp); } static void checkTimer() { System.err.println(elapsedTime() + " ms"); } static void chk(boolean f) { if (!f) throw new RuntimeException("Assert failed"); } static void chk(boolean f, String format, Object ... args) { if (!f) throw new RuntimeException(String.format(format, args)); } static void log(String format, Object ... args) { if (writeLog) System.err.println(String.format(Locale.US, format, args)); } }
logn
276_D. Little Girl and Maximum XOR
CODEFORCES
//package prac; 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 Round568G { InputStream is; PrintWriter out; String INPUT = ""; // void solve() { int n = ni(), T = ni(); int mod = 1000000007; int[][] a = new int[3][n]; int[] ap = new int[3]; for(int i = 0;i < n;i++){ int t = ni(); int k = ni()-1; a[k][ap[k]++] = t; } for(int i = 0;i < 3;i++)a[i] = Arrays.copyOf(a[i], ap[i]); long[][][][] com = new long[3][ap[0]+2][ap[1]+2][ap[2]+2]; com[0][1][0][0] = com[1][0][1][0] = com[2][0][0][1] = 1; for(int i = 0;i <= ap[0];i++){ for(int j = 0;j <= ap[1];j++){ for(int k = 0;k <= ap[2];k++){ for(int u = 0;u < 3;u++){ if(u != 0){ com[0][i+1][j][k] += com[u][i][j][k]; if(com[0][i+1][j][k] >= mod)com[0][i+1][j][k] -= mod; } if(u != 1){ com[1][i][j+1][k] += com[u][i][j][k]; if(com[1][i][j+1][k] >= mod)com[1][i][j+1][k] -= mod; } if(u != 2){ com[2][i][j][k+1] += com[u][i][j][k]; if(com[2][i][j][k+1] >= mod)com[2][i][j][k+1] -= mod; } } } } } int[][] fif = enumFIF(200, mod); long[][][] dp = new long[3][][]; for(int i = 0;i < 3;i++){ int s = 0; for(int v : a[i])s += v; dp[i] = new long[ap[i]+1][s+1]; dp[i][0][0] = 1; for(int v : a[i]){ for(int j = ap[i]-1;j >= 0;j--){ for(int k = s-v;k >= 0;k--){ dp[i][j+1][k+v] += dp[i][j][k]; if(dp[i][j+1][k+v] >= mod)dp[i][j+1][k+v] -= mod; } } } } long[][][] con = new long[ap[0]+1][ap[1]+1][2501]; for(int i = 0;i <= ap[0];i++){ for(int j = 0;j <= ap[1];j++){ for(int k = 0;k < dp[0][i].length;k++){ if(dp[0][i][k] == 0)continue; for(int l = 0;l < dp[1][j].length;l++){ con[i][j][k+l] += dp[0][i][k] * dp[1][j][l]; con[i][j][k+l] %= mod; } } } } long ans = 0; for(int i = 0;i <= ap[0];i++){ for(int j = 0;j <= ap[1];j++){ for(int k = 0;k <= ap[2];k++){ long base = (com[0][i][j][k] + com[1][i][j][k] + com[2][i][j][k]) * fif[0][i] % mod * fif[0][j] % mod * fif[0][k] % mod; long ls = 0; for(int l = 0;l <= T;l++){ if(T-l < dp[2][k].length){ ls += con[i][j][l] * dp[2][k][T-l]; ls %= mod; } } // if(base > 0 && ls > 0){ // tr(i, j, k, base, ls); // } ans += base * ls; ans %= mod; } } } out.println(ans); } public static int[][] enumFIF(int n, int mod) { int[] f = new int[n + 1]; int[] invf = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; i++) { f[i] = (int) ((long) f[i - 1] * i % mod); } long a = f[n]; long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } invf[n] = (int) (p < 0 ? p + mod : p); for (int i = n - 1; i >= 0; i--) { invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod); } return new int[][] { f, invf }; } void run() throws Exception { // int n = 50, m = 2500; // Random gen = new Random(); // StringBuilder sb = new StringBuilder(); // sb.append(n + " "); // sb.append(m + " "); // for (int i = 0; i < n; i++) { // sb.append(50 + " "); // sb.append(gen.nextInt(3)+1 + " "); // } // INPUT = sb.toString(); 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 Round568G().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
cubic
1185_G2. Playlist for Polycarp (hard version)
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class E implements Runnable { public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();} int n, m; char[] str; int[][] occs, cost; int[] dp; public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println(""); //where's my 420???? :( long tot = 0; for(int i = 0; i < 20000; i++) tot += i; n = fs.nextInt(); m = fs.nextInt(); byte[] str = fs.next().getBytes(); int[] occs = new int[1<<m]; for(int i = 0; i < n-1; i++) { int l1 = str[i] - 'a'; int l2 = str[i+1] - 'a'; occs[(1<<l1) | (1<<l2)]++; occs[(1<<l2) | (1<<l1)]++; } //cost[mask][v] = numPairs with v for some all bits on in mask int all = (1<<m)-1; cost = new int[m][1<<m]; for(int i = 0; i < m; i++) { for(int mask = 1; mask < all; mask++) { if(((1<<i)&mask) > 0) continue; int lb = mask & (-mask); int trail = Integer.numberOfTrailingZeros(lb); int nmask = mask ^ lb; cost[i][mask] = cost[i][nmask]+occs[1<<i | 1<<trail]; } } dp = new int[1<<m]; for(int mask = dp.length-2; mask >= 0; mask--) { int addOn = 0; for(int nxt = 0; nxt < m; nxt++) { if(((1<<nxt)&mask) > 0) continue; addOn += cost[nxt][mask]; } int res = oo; for(int nxt = 0; nxt < m; nxt++) { if(((1<<nxt)&mask) > 0) continue; int ret = addOn+dp[mask | (1<<nxt)]; res = min(res, ret); } dp[mask] = res; } System.out.println(dp[0]>>1); out.close(); } int oo = (int)1e9; int min(int a, int b) { if(a < b) return a; return b; } class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
np
1238_E. Keyboard Purchase
CODEFORCES
//~ 22:04:48 import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); String out = ""; String[] p = br.readLine().split("[ ]"); int n = Integer.valueOf(p[0]); double t = Double.valueOf(p[1]); int offset = 5000; boolean[] flags = new boolean[offset+5000]; for(int i=0;i<n;i++){ int[] q = toIntArray(br.readLine()); int c = 2*q[0]; for(int j=-q[1];j<q[1];j++){ flags[c+offset+j] = true; //~ System.out.println(c+offset+j); } } int buf = 0; int last = -1; int index = 0; for(;index<flags.length;index++){ if(flags[index]){ if(last==-1){ buf++; }else{ //~ System.out.println(last); //~ System.out.println(index); if(Math.abs(index-last-(2*t+1))<1e-10) buf++; else if(index-last>2*t+1) buf+=2; } last = index; } } buf ++; out = ""+buf+"\r\n"; bw.write(out,0,out.length()); br.close(); bw.close(); } static int[] toIntArray(String line){ String[] p = line.trim().split("\\s+"); int[] out = new int[p.length]; for(int i=0;i<out.length;i++) out[i] = Integer.valueOf(p[i]); return out; } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.util.*; import java.io.*; public class A { public static void main(String ar[]) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s1[]=br.readLine().split(" "); int n=Integer.parseInt(s1[0]); int S=Integer.parseInt(s1[1]); if(S%n==0) System.out.println(S/n); else System.out.println(S/n+1); } }
constant
1061_A. Coins
CODEFORCES
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]),k=Integer.parseInt(s[2]); int i,j,max=n*m,in[][]=new int[n][m],x=0; if(k%2==1) //not possible { for(i=0;i<n;i++) { for(j=0;j<m;j++) sb.append("-1 "); sb.append("\n"); } System.out.print(sb); return; } for(i=0;i<n;i++) for(j=0;j<m;j++) in[i][j]=x++; ArrayList<Edge> g[]=new ArrayList[max]; for(i=0;i<max;i++) g[i]=new ArrayList<>(); for(i=0;i<n;i++) { s=bu.readLine().split(" "); for(j=0;j<m-1;j++) { int u=in[i][j],v=in[i][j+1],w=Integer.parseInt(s[j]); g[u].add(new Edge(v,w)); g[v].add(new Edge(u,w)); } } for(i=0;i<n-1;i++) { s=bu.readLine().split(" "); for(j=0;j<m;j++) { int u=in[i][j],v=in[i+1][j],w=Integer.parseInt(s[j]); g[u].add(new Edge(v,w)); g[v].add(new Edge(u,w)); } } k/=2; int dp[][]=new int[k][max]; for(i=0;i<max;i++) { dp[0][i]=Integer.MAX_VALUE; for(Edge e:g[i]) dp[0][i]=Math.min(dp[0][i],2*e.w); } for(i=1;i<k;i++) for(j=0;j<max;j++) { dp[i][j]=Integer.MAX_VALUE; for(Edge e:g[j]) dp[i][j]=Math.min(dp[i][j],dp[i-1][e.v]+2*e.w); } for(i=0;i<n;i++) { for(j=0;j<m;j++) sb.append(dp[k-1][in[i][j]]+" "); sb.append("\n"); } System.out.print(sb); } static class Edge { int v,w,d; Edge(int a,int b) { v=a; w=b; d=0; } } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.io.IOException; import java.util.Locale; import java.util.Scanner; public class A { private void processInput() throws IOException { Scanner in = new Scanner(System.in); int n = in.nextInt(); long res = go(n); System.out.printf(Locale.ENGLISH, "%d\n", res); in.close(); } private long go(long n) { long res = 3*n / 2; return res; } public static void main(String[] args) throws Exception { A a = new A(); a.processInput(); } }
constant
84_A. Toy Army
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer tok; static boolean hasNext() { while(tok==null||!tok.hasMoreTokens()) try{ tok=new StringTokenizer(in.readLine()); } catch(Exception e){ return false; } return true; } static String next() { hasNext(); return tok.nextToken(); } static long nextLong() { return Long.parseLong(next()); } static int nextInt() { return Integer.parseInt(next()); } static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) { int n = nextInt(); int a[] = new int[9]; int b[] = new int[9]; for(int i=0;i<n;i++){ String s = next(); if(s.equals("M")){ a[0]++; }else if (s.equals("L")){ a[1]++; } else if (s.equals("XL")){ a[2]++; } else if (s.equals("XXL")){ a[3]++; } else if (s.equals("XXXL")){ a[4]++; } else if (s.equals("S")){ a[5]++; } else if (s.equals("XS")){ a[6]++; } else if (s.equals("XXS")){ a[7]++; } else if (s.equals("XXXS")){ a[8]++; } } for(int i=0;i<n;i++){ String s = next(); if(s.equals("M")){ b[0]++; }else if (s.equals("L")){ b[1]++; } else if (s.equals("XL")){ b[2]++; } else if (s.equals("XXL")){ b[3]++; } else if (s.equals("XXXL")){ b[4]++; } else if (s.equals("S")){ b[5]++; } else if (s.equals("XS")){ b[6]++; } else if (s.equals("XXS")){ b[7]++; } else if (s.equals("XXXS")){ b[8]++; } } int ans = 0; ans+=Math.abs(a[2]-b[2]); ans+=Math.abs(a[3]-b[3]); ans+=Math.abs(a[4]-b[4]); int max = Math.abs(a[0]-b[0]); max = max(max,Math.abs(a[1]-b[1])); max = max(max,Math.abs(a[5]-b[5])); ans+=max; out.print(ans); out.flush(); } public static int max(int a,int b){ return a>b?a:b; } }
linear
1000_A. Codehorses T-shirts
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates 744444444747477777774 44444447474747777777 */ /** * * @author Andy Phan */ public class b { public static void main(String[] args) { FS in = new FS(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); Integer[] arr = new Integer[n]; int numZ = 0; for(int i = 0; i < n; i++) { arr[i] = in.nextInt(); if(arr[i] == 0) numZ++; } Arrays.sort(arr); if(numZ > 1) { System.out.println("cslnb"); return; } int numDup = 0; int[] arr2 = new int[n]; for(int i = 0; i < n; i++) { arr2[i] = arr[i]; if(i != 0) { if(arr2[i] == arr2[i-1]) { arr2[i-1]--; numDup++; } } } if(numDup > 1) { System.out.println("cslnb"); return; } for(int i = 0; i < n; i++) { if(i != 0) { if(arr2[i] == arr2[i-1]) { System.out.println("cslnb"); return; } } } long num = 0; if(numDup == 1) num++; for(int i = 0; i < n; i++) { num += arr2[i]-i; } if(num%2 == 0) { System.out.println("cslnb"); } else { System.out.println("sjfnb"); } out.close(); } static class FS { BufferedReader in; StringTokenizer token; public FS(InputStream str) { in = new BufferedReader(new InputStreamReader(str)); } public String next() { if (token == null || !token.hasMoreElements()) { try { token = new StringTokenizer(in.readLine()); } catch (IOException ex) { } return next(); } return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
linear
1191_D. Tokitsukaze, CSL and Stone Game
CODEFORCES
import java.util.*; import java.io.*; public class luckydivision { public static int i(String s){ return Integer.parseInt(s); } public static boolean solve(String k, int n){ int temp = i(k); if(temp > n){ return false; } if(n % temp == 0) return true; if(solve(k + "7", n)) return true; return solve(k + "4", n); } public static void main(String args[]) throws Exception { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); int n = i(r.readLine()); boolean i = solve("7", n); boolean j = solve("4", n); if(i || j){ System.out.println("YES"); } else { System.out.println("NO"); } } }
constant
122_A. Lucky Division
CODEFORCES
import java.io.InputStreamReader; import java.io.IOException; import java.util.InputMismatchException; 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 Niyaz Nigmatullin */ 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); Fish solver = new Fish(); solver.solve(1, in, out); out.close(); } } class Fish { public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); double[][] p = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { p[i][j] = in.nextDouble(); } } double[] dp = new double[1 << n]; dp[(1 << n) - 1] = 1; for (int mask = (1 << n) - 1; mask >= 0; mask--) { int countPairs = Integer.bitCount(mask); countPairs = countPairs * (countPairs - 1) / 2; for (int i = 0; i < n; i++) { if (((mask >> i) & 1) == 0) { continue; } for (int j = i + 1; j < n; j++) { if (((mask >> j) & 1) == 0) { continue; } dp[mask ^ (1 << j)] += dp[mask] * p[i][j] / countPairs; dp[mask ^ (1 << i)] += dp[mask] * p[j][i] / countPairs; } } } for (int i = 0; i < n; i++) { out.print(dp[1 << i] + " "); } } } class FastScanner extends BufferedReader { boolean isEOF; 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(); } while (!isWhiteSpace(c)) { sb.appendCodePoint(c); c = read(); } return sb.toString(); } static boolean isWhiteSpace(int c) { return c >= -1 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (!isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } public double nextDouble() { return Double.parseDouble(next()); } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } }
np
16_E. Fish
CODEFORCES
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner input = new Scanner(System.in); long num = input.nextLong(); if(num==0){ System.out.println(num); }else if(num==1||num==2){ System.out.println(num);} else if(num%2==0&&num>2&&num%3!=0){ System.out.println(num*(num-1)*(num-3)); } else if(num%2==0&&num%3==0){ System.out.println((num-1)*(num-2)*(num-3)); } else{ System.out.println(num*(num-1)*(num-2));} } }
constant
235_A. LCM Challenge
CODEFORCES
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class A { public static void main(String[] args) throws Exception { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int k = scan.nextInt()-1; PrimeGen p = new PrimeGen(n); List<Integer> prims = new ArrayList<Integer>(); for(int i = 2; i <= n; i++){ if(p.isPrime(i)>0){ prims.add(i); } } int sum = 0; for(int i = 0; i < prims.size() - 1; i++){ int c = prims.get(i) + prims.get(i+1) + 1; if(c <= n && p.isPrime(c)>0){ sum ++; } } System.out.println(sum>=k?"YES":"NO"); } static int sum(List<Integer> is) { int c = 0; for (int i : is) c += i; return c; } static class PrimeGen { public PrimeGen(int m) { m = (int) Math.sqrt(m); double max = 0; int r = 1; for (int i = 0; i < 4;) { max += r * m / Math.pow(Math.log1p(m), ++i); r *= i; } p = new int[(int) max]; for (int i = 0, e = 2; i < p.length; i++) { for (; isPrime(e) < 1; e++) ; p[i] = e++; } this.m = p[p.length - 1]; this.m = this.m * this.m; } int isPrime(int n) { for (int e : p) if (e < 1) break; else if (n != e && n % e < 1) return 0; return 1; } int max() { return m; } int[] p; int m; } }
linear
17_A. Noldbach problem
CODEFORCES
import java.io.*; import java.util.*; public final class Solution { static PrintWriter out = new PrintWriter(System.out); static FastReader in = new FastReader(); static long mod = (long) 1e9 + 7; static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(1, 0), new Pair(0, -1), new Pair(0, 1)}; //6 3 //2 3 10 7 5 14 //1 6 //2 4 //3 5 public static void main(String[] args) { int n = i(); int m = i(); int k = i(); int[][] a = new int[n][m - 1]; for (int i = 0; i < n; i++) { a[i] = input(m - 1); } int[][] b = new int[n - 1][m]; for (int i = 0; i < n - 1; i++) { b[i] = input(m); } if (k % 2 > 0) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(-1 + " "); } out.println(); } out.flush(); return; } int[][][] f = new int[n][m][k / 2 + 1]; for (int s = 1; s <= k / 2; s++) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int ans = -1; if (j > 0) { ans = f[i][j - 1][s - 1] + a[i][j - 1]; } if (i > 0) { int t = f[i - 1][j][s - 1] + b[i - 1][j]; ans = ans == -1 ? t : Math.min(ans, t); } if (i < n - 1) { int t = f[i + 1][j][s - 1] + b[i][j]; ans = ans == -1 ? t : Math.min(ans, t); } if (j < m - 1) { int t = f[i][j + 1][s - 1] + a[i][j]; ans = ans == -1 ? t : Math.min(ans, t); } f[i][j][s] = ans; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { out.print(f[i][j][k / 2] * 2 + " "); } out.println(); } out.flush(); } static int sd(long i) { int d = 0; while (i > 0) { d += i % 10; i = i / 10; } return d; } static Set<Integer> getFactors(int x) { Set<Integer> res = new HashSet<>(); if (x <= 3) { res.add(x); } else { int t = x; for (int f = 2; f <= x / 2; f++) { if (t == 1) { break; } if (t % f == 0) { res.add(f); while (t % f == 0) { t = t / f; } } } if (t > 1) { res.add(t); } } return res; } static int lower(long A[], long x) { int l = -1, r = A.length; while (r - l > 1) { int m = (l + r) / 2; if (A[m] >= x) { r = m; } else { l = m; } } return r; } static int upper(long A[], long x) { int l = -1, r = A.length; while (r - l > 1) { int m = (l + r) / 2; if (A[m] <= x) { l = m; } else { r = m; } } return l; } static void swap(int A[], int a, int b) { int t = A[a]; A[a] = A[b]; A[b] = t; } static int lowerBound(int A[], int low, int high, int x) { if (low > high) { if (x >= A[high]) { return A[high]; } } int mid = (low + high) / 2; if (A[mid] == x) { return A[mid]; } if (mid > 0 && A[mid - 1] <= x && x < A[mid]) { return A[mid - 1]; } if (x < A[mid]) { return lowerBound(A, low, mid - 1, x); } return lowerBound(A, mid + 1, high, x); } static long pow(long a, long b) { long pow = 1; long x = a; while (b != 0) { if ((b & 1) != 0) { pow = (pow * x) % mod; } x = (x * x) % mod; b /= 2; } return pow; } 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 void print(char A[]) { for (char c : A) { out.print(c); } out.println(); } static void print(boolean A[]) { for (boolean c : A) { out.print(c + " "); } out.println(); } static void print(int A[]) { for (int c : A) { out.print(c + " "); } out.println(); } static void print(long A[]) { for (long i : A) { out.print(i + " "); } out.println(); } static void print(List<Integer> A) { for (int a : A) { out.print(a + " "); } } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static String s() { return in.nextLine(); } static int[] input(int N) { int A[] = new int[N]; for (int i = 0; i < N; i++) { A[i] = in.nextInt(); } return A; } static long[] inputLong(int N) { long A[] = new long[N]; for (int i = 0; i < A.length; i++) { A[i] = in.nextLong(); } return A; } static int GCD(int a, int b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static long GCD(long a, long b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } } class SegmentTree { long[] t; public SegmentTree(int n) { t = new long[n + n]; Arrays.fill(t, Long.MIN_VALUE); } public long get(int i) { return t[i + t.length / 2]; } public void add(int i, long value) { i += t.length / 2; t[i] = value; for (; i > 1; i >>= 1) { t[i >> 1] = Math.max(t[i], t[i ^ 1]); } } // max[a, b] public long max(int a, int b) { long res = Long.MIN_VALUE; for (a += t.length / 2, b += t.length / 2; a <= b; a = (a + 1) >> 1, b = (b - 1) >> 1) { if ((a & 1) != 0) { res = Math.max(res, t[a]); } if ((b & 1) == 0) { res = Math.max(res, t[b]); } } return res; } } class Pair { int i, j; Pair(int i, int j) { this.i = i; this.j = j; } } 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; } }
cubic
1517_D. Explorer Space
CODEFORCES
import java.util.*; public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n= sc.nextInt(); int x= (int)Math.sqrt(n) ; int a[] = new int[n+5]; for(int i=1,o=n,j;i<=n;i+=x) for(j=(int)Math.min(i+x-1,n);j>=i;a[j--]=o--); for(int i=1;i<=n;i++)System.out.print(a[i]+" "); System.out.println(); } }
linear
1017_C. The Phone Number
CODEFORCES
import java.io.*; public class Main { public static void main (String [] args) throws IOException { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); do { int n = Integer.parseInt (br.readLine ()); //args; int [] ns = new int [(args = br.readLine ().split (" ")).length]; int evenCount = 0, oddCount = 0, evI = 1, oddI = 1; for (int i = 0; i < ns.length; i++) { if ((ns [i] = Integer.parseInt (args [i])) % 2 == 0) { evenCount ++; evI = i; } else { oddCount ++; oddI = i; } } if (evenCount == 1) System.out.println (evI + 1); else System.out.println (oddI + 1); } while (br.ready ()); } }
linear
25_A. IQ test
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Don Li */ public class EhabAndAComponentChoosingProblem { long INF = (long) 1e18; int n; int[] a; int[][] G; void solve() { n = in.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); int[] fr = new int[n - 1], to = new int[n - 1]; for (int i = 0; i < n - 1; i++) { fr[i] = in.nextInt() - 1; to[i] = in.nextInt() - 1; } G = build_graph(n, fr, to); int[][] ret = bfs(G, 0); int[] par = ret[0], ord = ret[2]; long best = -INF; long[] dp = new long[n]; for (int i = n - 1; i >= 0; i--) { int u = ord[i]; dp[u] = a[u]; for (int v : G[u]) { if (v != par[u]) { if (dp[v] > 0) dp[u] += dp[v]; } } best = Math.max(best, dp[u]); } int k = 0; for (int i = n - 1; i >= 0; i--) { int u = ord[i]; dp[u] = a[u]; for (int v : G[u]) { if (v != par[u]) { if (dp[v] > 0) dp[u] += dp[v]; } } if (dp[u] == best) { dp[u] = -INF; k++; } } out.printf("%d %d%n", best * k, k); } int[][] bfs(int[][] G, int root) { int n = G.length; int[] par = new int[n]; Arrays.fill(par, -1); int[] dep = new int[n]; dep[root] = 0; int[] qu = new int[n]; qu[0] = root; for (int l = 0, r = 1; l < r; l++) { int u = qu[l]; for (int v : G[u]) { if (v != par[u]) { qu[r++] = v; par[v] = u; dep[v] = dep[u] + 1; } } } return new int[][]{par, dep, qu}; } int[][] build_graph(int n, int[] from, int[] to) { int[][] G = new int[n][]; int[] cnt = new int[n]; for (int i = 0; i < from.length; i++) { cnt[from[i]]++; cnt[to[i]]++; } for (int i = 0; i < n; i++) G[i] = new int[cnt[i]]; for (int i = 0; i < from.length; i++) { G[from[i]][--cnt[from[i]]] = to[i]; G[to[i]][--cnt[to[i]]] = from[i]; } return G; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new EhabAndAComponentChoosingProblem().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
linear
1088_E. Ehab and a component choosing problem
CODEFORCES
import java.io.*; import java.util.*; public class B { void solve() throws IOException { in = new InputReader("__std"); out = new OutputWriter("__std"); int n = in.readInt(); int a = in.readInt(); int b = in.readInt(); int ma = 0; int mb = 1; if (a < b) { int t = a; a = b; b = t; t = ma; ma = mb; mb = t; } final int[] p = new int[n]; Integer id[] = new Integer[n]; Map<Integer, Integer> pos = new HashMap<Integer, Integer>(); for (int i = 0; i < n; ++i) { p[i] = in.readInt(); id[i] = i; pos.put(p[i], i); } Arrays.sort(id, new Comparator<Integer>() { public int compare(Integer i, Integer j) { return p[i] - p[j]; } }); int[] mask = new int[n]; Arrays.fill(mask, -1); boolean flag = true; for (int i = 0; i < n && flag; ++i) { if (mask[id[i]] == -1) { if (p[id[i]] < a) { if (pos.containsKey(a - p[id[i]])) { int j = pos.get(a - p[id[i]]); if (mask[j] != mb) { mask[id[i]] = mask[j] = ma; continue; } } if (p[id[i]] < b && pos.containsKey(b - p[id[i]])) { int j = pos.get(b - p[id[i]]); if (mask[j] != ma) { mask[id[i]] = mask[j] = mb; continue; } } } flag = false; } } if (flag) { out.println("YES"); for (int m : mask) { out.print(m + " "); } } else { out.println("NO"); } exit(); } void exit() { //System.err.println((System.currentTimeMillis() - startTime) + " ms"); out.close(); System.exit(0); } InputReader in; OutputWriter out; //long startTime = System.currentTimeMillis(); public static void main(String[] args) throws IOException { new B().solve(); } class InputReader { private InputStream stream; private byte[] buffer = new byte[1024]; private int pos, len; private int cur; private StringBuilder sb = new StringBuilder(32); InputReader(String name) throws IOException { if (name.equals("__std")) { stream = System.in; } else { stream = new FileInputStream(name); } cur = read(); } private int read() throws IOException { if (len == -1) { throw new EOFException(); } if (pos >= len) { pos = 0; len = stream.read(buffer); if (len == -1) return -1; } return buffer[pos++]; } char readChar() throws IOException { if (cur == -1) { throw new EOFException(); } char res = (char) cur; cur = read(); return res; } int readInt() throws IOException { if (cur == -1) { throw new EOFException(); } while (whitespace()) { cur = read(); } if (cur == -1) { throw new EOFException(); } int sign = 1; if (cur == '-') { sign = -1; cur = read(); } int res = 0; while (!whitespace()) { if (cur < '0' || cur > '9') { throw new NumberFormatException(); } res *= 10; res += cur - '0'; cur = read(); } return res * sign; } long readLong() throws IOException { if (cur == -1) { throw new EOFException(); } return Long.parseLong(readToken()); } double readDouble() throws IOException { if (cur == -1) { throw new EOFException(); } return Double.parseDouble(readToken()); } String readLine() throws IOException { if (cur == -1) { throw new EOFException(); } sb.setLength(0); while (cur != -1 && cur != '\r' && cur != '\n') { sb.append((char) cur); cur = read(); } if (cur == '\r') { cur = read(); } if (cur == '\n') { cur = read(); } return sb.toString(); } String readToken() throws IOException { if (cur == -1) { throw new EOFException(); } while (whitespace()) { cur = read(); } if (cur == -1) { throw new EOFException(); } sb.setLength(0); while (!whitespace()) { sb.append((char) cur); cur = read(); } return sb.toString(); } boolean whitespace() { return cur == ' ' || cur == '\t' || cur == '\r' || cur == '\n' || cur == -1; } boolean eof() { return cur == -1; } } class OutputWriter { private PrintWriter writer; OutputWriter(String name) throws IOException { if (name.equals("__std")) { writer = new PrintWriter(System.out); } else { writer = new PrintWriter(name); } } void print(String format, Object ... args) { writer.print(new Formatter(Locale.US).format(format, args)); } void println(String format, Object ... args) { writer.println(new Formatter(Locale.US).format(format, args)); } void print(Object value) { writer.print(value); } void println(Object value) { writer.println(value); } void println() { writer.println(); } void close() { writer.close(); } } }
linear
468_B. Two Sets
CODEFORCES
import java.util.*; import java.io.*; public class code{ public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int ok,ok2; int va,vb; va = 0; vb = 0; out.println("? "+va+" "+vb); out.flush(); ok = sc.nextInt(); for(int i=29;i>=0;i--){ if(ok==0){ va += (1<<i); out.println("? "+va+" "+vb); out.flush(); ok2 = sc.nextInt(); if(ok2==1){ va -= (1<<i); }else{ vb += (1<<i); } }else{ va += (1<<i); vb += (1<<i); out.println("? "+va+" "+vb); out.flush(); ok2 = sc.nextInt(); if(ok==ok2){ vb -= (1<<i); out.println("? "+va+" "+vb); out.flush(); ok2 = sc.nextInt(); if(ok2==1){ va -= (1<<i); }else{ vb += (1<<i); } }else{ if(ok==1){ vb -= (1<<i); out.println("? "+va+" "+vb); out.flush(); ok = sc.nextInt(); } else { va -= (1<<i); out.println("? "+va+" "+vb); out.flush(); ok = sc.nextInt(); } } } } out.println("! "+va+" "+vb); out.flush(); } }
logn
1088_D. Ehab and another another xor problem
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class DTask { static Scanner in; static int[] first = new int[4]; static int[] second = new int[4]; static PrintWriter out; static int n; public static void main(String[] args) throws IOException { in = new Scanner(System.in); out = new PrintWriter(System.out); n = in.nextInt() + 1; first = new int[]{0, 0, n, n}; second = new int[]{0, 0, n, n}; for (int i = 0; i < first.length; i++) { boolean inc = i < 2; search(first, i, inc, false); if (!inc) { first[i] += 1; } } for (int i = 0; i < second.length; i++) { boolean inc = i < 2; search(second, i, inc, true); if (!inc) { second[i] += 1; } } String s = "!"; for (int i = 0; i < 4; i++) { s += " " + second[i]; } for (int i = 0; i < 4; i++) { s += " " + first[i]; } out.println(s); out.flush(); } static void search(int arr[], int i, boolean inc, boolean cond) { int start = 0; int end = n; while (true) { if (end - start <= 1) { arr[i] = start; return; } int mid = (start + end) / 2; arr[i] = mid; int n = ask(arr, cond); if (n > 0) { if (inc) { start = mid; } else { end = mid; } } else { if (inc) { end = mid; } else { start = mid; } } } } static int ask(int arr[], boolean cond) { if (arr[1] > arr[3] || arr[0] > arr[2]) { return 0; } arr = Arrays.copyOf(arr, 4); String q = ""; q += "?"; for (int i = 0; i < arr.length; i++) { int x = Math.min(arr[i], n - 1); x = Math.max(x, 1); q += " " + x; } out.println(q); out.flush(); int x = in.nextInt(); if (cond) { x -= within(arr, first) ? 1 : 0; } return x; /*if (arr[1] > arr[3] || arr[0] > arr[2]) { return 0; } int[] check = new int[]{1, 1, 10, 1}; int[] check1 = new int[]{5, 5, 5, 10}; int result = within(arr, check) ? 1 : 0; result += within(arr, check1) ? 1 : 0; if (cond) { result -= within(arr, first) ? 1 : 0; } return result;*/ } static boolean within(int outer[], int inner[]) { return (outer[0] <= inner[0] && outer[1] <= inner[1] && outer[2] >= inner[2] && outer[3] >= inner[3]); } static class MyInputReader { public BufferedReader reader; public StringTokenizer tokenizer; public MyInputReader(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()); } } }
logn
713_B. Searching Rectangles
CODEFORCES
//package codeforces.br23; import java.io.*; /** * User: Kandy * Date: 12.07.2010 * Time: 21:51:52 */ public class ProblemA { public void solve() { boolean oj = true; try { Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("A.in"); Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("A.out"); BufferedReader br = new BufferedReader(reader); StreamTokenizer st = new StreamTokenizer(reader); PrintWriter out = new PrintWriter(writer); String s = br.readLine(); int n = s.length(); int max = 0; for (int i = 0; i < n; i++) for (int j = i; j < n; j++) { int len = j - i + 1; int count = 0; for (int k = 0; k < n - len + 1; k++) { boolean eq = true; for(int l = 0; l < len;l++) { if (s.charAt(i + l) != s.charAt(k + l)) { eq = false; break; } } if (eq) { count++; } } if (count >= 2 && len > max) { max = len; } } out.printf("%d", max); br.close(); out.close(); reader.close(); writer.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { } } public static void main(String[] args) { ProblemA f = new ProblemA(); f.solve(); } private class MyTokenizer { private String s; private int cur; public MyTokenizer(String s) { this.s = s; cur = 0; } public void skip() { while (cur < s.length() && (s.charAt(cur) == ' ' || s.charAt(cur) == '\n')) { cur++; } } public double getNum() { skip(); String snum = ""; while (cur < s.length() && (s.charAt(cur) >= '0' && s.charAt(cur) <= '9' || s.charAt(cur) == '.' || s.charAt(cur) == '-')) { snum += s.charAt(cur); cur++; } return Double.valueOf(snum); } public String getString() { skip(); String s2 = ""; while (cur < s.length() && (((s.charAt(cur) >= 'a' && s.charAt(cur) <= 'z')) || ((s.charAt(cur) >= 'A' && s.charAt(cur) <= 'Z')))) { s2 += s.charAt(cur); cur++; } return s2; } public char getCurrentChar() throws Exception { if (cur < s.length()) return s.charAt(cur); else throw new Exception("Current character out of string length"); } public void moveNextChar() { if (cur < s.length()) cur++; } public boolean isFinished() { return cur >= s.length(); } } }
cubic
23_A. You're Given a String...
CODEFORCES
//https://github.com/EgorKulikov/yaal/tree/master/lib/main/net/egork import java.util.*; import java.io.*; public class B{ static PrintWriter out; static InputReader in; public static void main(String args[]){ out = new PrintWriter(System.out); in = new InputReader(); new B(); out.flush(); out.close(); } B(){ solve(); } class pair{ int F, S; pair(int a, int b){ F = a; S = b; } } void solve(){ int n = in.nextInt(), mod = in.nextInt(); long dp[][] = new long[n + 1][n + 1]; long ncr[][] = new long[810][410]; ncr[0][0] = 1; for(int i = 1; i < 810; i++){ for(int j = 0; j < 410; j++){ ncr[i][j] = (ncr[i - 1][j] + (j > 0 ? ncr[i - 1][j - 1] : 0)) % mod; } } for(int i = 1; i <= n; i++)dp[i][i] = 1; for(int i = 1; i < n; i++){ for(int j = 1; j + i <= n; j++){ int end = i + j; dp[j][end] = (dp[j + 1][end] + dp[j][end - 1]) % mod; } } long value[] = new long[n + 1]; for(int i = 1; i <= n; i++){ value[i] = dp[1][i]; } long fdp[][] = new long[n + 2][n + 2]; fdp[0][0] = 1; long ans = 0; for(int b = 1; b <= (n + 1) / 2; b++){ for(int i = 1; i <= n; i++){ for(int k = Math.max(0, b - 2); k < i; k++){ fdp[i + 1][b] = (fdp[i + 1][b] + fdp[k][b - 1] * value[i - k] % mod * ncr[k - b + 2 + i - k - 1][i - k] % mod) % mod; } } ans = (ans + fdp[n + 1][b]) % mod; } out.print(ans); } public static class InputReader{ BufferedReader br; StringTokenizer st; InputReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){} } return st.nextToken(); } } }
cubic
1515_E. Phoenix and Computers
CODEFORCES
import java.util.Scanner; public class SimpleTask { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); boolean[][] graph = new boolean[n][n]; for (int i = 0; i < m; i++) { int u = scan.nextInt() - 1; int v = scan.nextInt() - 1; graph[u][v] = true; graph[v][u] = true; } long[][] dp = new long[1 << n][n]; for (int i = 0; i < n; i++) dp[1 << i][i] = 1; for (int mask = 1; mask < (1 << n); mask++) { int first = Integer.numberOfTrailingZeros(mask); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) == 0 || first == i) continue; for (int j = 0; j < n; j++) { if (graph[i][j]) dp[mask][i] += dp[mask ^ 1 << i][j]; } } } long answer = 0; for (int mask = 1; mask < (1 << n); mask++) { if (Integer.bitCount(mask) < 3) continue; int first = Integer.numberOfTrailingZeros(mask); for (int i = 0; i < n; i++) { if (graph[first][i]) answer += dp[mask][i]; } } System.out.println(answer / 2); scan.close(); } }
np
11_D. A Simple Task
CODEFORCES
import java.util.Scanner; public class IQ { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = scan.nextInt(); for(int i = 0; i < n; i++) { boolean x = a[i] % 2 == 0; int c = 0; for(int j = 0; j < n; j++) { if(x != (a[j] % 2 == 0)) c++; } if(c == n-1) { System.out.println(i+1); break; } } } }
linear
25_A. IQ test
CODEFORCES
import java.util.Scanner; public class ChainReaction { public static void main(String [] args) { Scanner kb = new Scanner(System.in); int num = kb.nextInt(); int[] beacons = new int[1000002]; for (int i=0; i<num; i++) { beacons[kb.nextInt()] = kb.nextInt(); } int [] dp = new int[1000002]; int max = 0; if (beacons[0] != 0) dp[0] = 1; for (int i=1; i<dp.length; i++) { if (beacons[i] == 0) { dp[i] = dp[i-1]; } else { int index = i-1-beacons[i]; if (index<0) dp[i] = 1; else dp[i] = 1 + dp[index]; } max = Math.max(max, dp[i]); //if (i<11) //System.out.println(i +" is "+dp[i]); } System.out.println(num-max); } }
linear
608_C. Chain Reaction
CODEFORCES
import java.util.*; import java.io.*; public class C { private static int[] dx = {1, -1, 0, 0}; private static int[] dy = {0, 0, -1, 1}; public static void main(String[] args) throws Exception{ Thread t = new Thread(null, null, "~", Runtime.getRuntime().maxMemory()){ @Override public void run(){ try { solve(); } catch(Exception e) { System.err.println("ERROR"); } } }; t.start(); t.join(); } public static void solve() throws Exception { Scanner in = new Scanner(new File("input.txt")); PrintWriter out = new PrintWriter(new File("output.txt")); int n = in.nextInt(); int m = in.nextInt(); int[][] time = new int[n][m]; for(int i = 0; i < n; ++i) { Arrays.fill(time[i], Integer.MAX_VALUE); } int qq = in.nextInt(); int[] xs = new int[qq]; int[] ys = new int[qq]; for(int i = 0; i < qq; ++i){ xs[i] = in.nextInt() - 1; ys[i] = in.nextInt() - 1; } for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { for(int k = 0; k < qq; ++k) { int dist = Math.abs(i - xs[k]) + Math.abs(j - ys[k]); time[i][j] = Math.min(time[i][j], dist); } } } int max = -1; int x = -1; int y = -1; for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) if(max < time[i][j]) { max = time[i][j]; x = i + 1; y = j + 1; } } out.println(x + " " + y); out.flush(); out.close(); } private static class Pair { int f, s; int time; public Pair(int f, int s) { this.f = f; this.s = s; } public Pair(int f, int s, int time) { this(f, s); this.time = time; } } }
cubic
35_C. Fire Again
CODEFORCES
/** * Write a description of class VK2A here. * * @author (your name) * @version (a version number or a date) */ import java.util.*; public class VK2A { public static void main(String args[]) { Scanner S = new Scanner(System.in); int n = S.nextInt(); int a = S.nextInt(); int b = S.nextInt(); int[] A = new int[n]; for(int i = 0; i < n; i++) A[i] = S.nextInt(); for(int i = 0; i < n; i++) for(int j = 0; j < n - i - 1; j++) { if(A[j] < A[j + 1]) { int temp = A[j]; A[j] = A[j + 1]; A[j + 1] = temp; } } System.out.println(A[a - 1] - A[a]); } }
nlogn
169_A. Chores
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; import java.util.Vector; /** * Created with IntelliJ IDEA. * User: horikawa * Date: 3/23/13 * Time: 1:29 AM * To change this template use File | Settings | File Templates. */ public class B { public static void main (String[] argv) { Scanner in = new Scanner(System.in); long n = in.nextLong(); long k = in.nextLong(); long max = ((k*(k-1))/2L)+1L; long ans = -1; if (n == 1) { System.out.println(0); return; } if (max < n) { ans = -1; } else if (max == n) { ans = k-1; } else { if (k >= n) { ans = 1; } else { long low = 1; long high = k-1; while (high > low+1) { long mid = (low+high)/2; long sum = (((mid+(k-1)) * (k-mid)) / 2) + 1; if (sum >= n) { low = mid; } else { high = mid; } } ans = (k - low); } } System.out.println(ans); return; } }
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; } final long[][] dp = new long[1 << n][n]; for (int i = 0; i < n; ++i) { int Limit = 1 << (n - i); int nn = n - i; for (int mask = 0; mask < Limit; ++mask) { for (int j = 0; j < nn; ++j) { dp[mask][j] = 0; } } dp[0][0] = 1; for (int mask = 0; mask < Limit; ++mask) { if ((mask & 1) == 0) { for (int j = 0; j < nn; ++j) { if (dp[mask][j] != 0) { long am = dp[mask][j]; for (int k = 0; k < nn; ++k) { if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) { dp[mask | (1 << k)][k] += am; } } } } } else { res += dp[mask][0]; } } } out.println((res - m) / 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
// @author Sanzhar import java.io.*; import java.util.*; import java.awt.Point; public class Template { BufferedReader in; PrintWriter out; StringTokenizer st; String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (Exception e) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } public void run() throws Exception { //in = new BufferedReader(new FileReader("input.txt")); //out = new PrintWriter(new FileWriter("output.txt")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.flush(); out.close(); in.close(); } public int sub(int a, int b) { int res = 0; while (b > 0) { res += a / b; int m = a % b; a = b; b = m; } return res; } public void solve() throws Exception { int n = nextInt(); while (n-- > 0) { out.println(sub(nextInt(), nextInt())); } } public static void main(String[] args) throws Exception { new Template().run(); } }
constant
267_A. Subtractions
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; 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 { private long MOD = (long) (1e9 + 7); int[][] dp = new int[5001][5001]; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); ArrayList<Character> commands = new ArrayList<>(); for (int i = 0; i < n; i++) { char ch = in.next().charAt(0); commands.add(ch); } for (int a[] : dp) Arrays.fill(a, -1); out.println(count(0, commands, 0)); } public int count(int index, ArrayList<Character> commands, int deepCount) { if (deepCount < 0) { return 0; } if (index == commands.size()) { return 1; } else { if (dp[index][deepCount] != -1) return dp[index][deepCount]; long result = 0; char ch = commands.get(index); result = count(index, commands, deepCount - 1); if (ch == 's') { result += count(index + 1, commands, deepCount); } else { result += count(index + 1, commands, deepCount + 1); result -= count(index + 1, commands, deepCount); } if (result >= MOD) { result -= MOD; } if (result < 0) { result += MOD; } return dp[index][deepCount] = (int) result; } } } 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 String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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 String next() { return readString(); } public int nextInt() { return readInt(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
quadratic
909_C. Python Indentation
CODEFORCES
import static java.lang.Math.*; import java.util.*; import java.io.*; public class A { public void solve() throws Exception { int n = nextInt(); int[] p = nextArr(n); Arrays.sort(p); int sum = 0; for (int i=0; i<n; ++i) sum+=p[i]; int curr = 0; for (int i=n-1; i>=0; --i) { curr += p[i]; if (curr>sum-curr) halt(n-i); } } //////////////////////////////////////////////////////////////////////////// boolean showDebug = true; static boolean useFiles = false; static String inFile = "input.txt"; static String outFile = "output.txt"; double EPS = 1e-7; int INF = Integer.MAX_VALUE; long INFL = Long.MAX_VALUE; double INFD = Double.MAX_VALUE; int absPos(int num) { return num<0 ? 0:num; } long absPos(long num) { return num<0 ? 0:num; } double absPos(double num) { return num<0 ? 0:num; } int min(int... nums) { int r = Integer.MAX_VALUE; for (int i: nums) if (i<r) r=i; return r; } int max(int... nums) { int r = Integer.MIN_VALUE; for (int i: nums) if (i>r) r=i; return r; } long minL(long... nums) { long r = Long.MAX_VALUE; for (long i: nums) if (i<r) r=i; return r; } long maxL(long... nums) { long r = Long.MIN_VALUE; for (long i: nums) if (i>r) r=i; return r; } double minD(double... nums) { double r = Double.MAX_VALUE; for (double i: nums) if (i<r) r=i; return r; } double maxD(double... nums) { double r = Double.MIN_VALUE; for (double i: nums) if (i>r) r=i; return r; } long sumArr(int[] arr) { long res = 0; for (int i: arr) res+=i; return res; } long sumArr(long[] arr) { long res = 0; for (long i: arr) res+=i; return res; } double sumArr(double[] arr) { double res = 0; for (double i: arr) res+=i; return res; } long partsFitCnt(long partSize, long wholeSize) { return (partSize+wholeSize-1)/partSize; } boolean odd(long num) { return (num&1)==1; } boolean hasBit(int num, int pos) { return (num&(1<<pos))>0; } long binpow(long a, int n) { long r = 1; while (n>0) { if ((n&1)!=0) r*=a; a*=a; n>>=1; } return r; } boolean isLetter(char c) { return (c>='a' && c<='z') || (c>='A' && c<='Z'); } boolean isLowercase(char c) { return (c>='a' && c<='z'); } boolean isUppercase(char c) { return (c>='A' && c<='Z'); } boolean isDigit(char c) { return (c>='0' && c<='9'); } boolean charIn(String chars, String s) { if (s==null) return false; if (chars==null || chars.equals("")) return true; for (int i=0; i<s.length(); ++i) for (int j=0; j<chars.length(); ++j) if (chars.charAt(j)==s.charAt(i)) return true; return false; } String stringn(String s, int n) { if (n<1 || s==null) return ""; StringBuilder sb = new StringBuilder(s.length()*n); for (int i=0; i<n; ++i) sb.append(s); return sb.toString(); } String str(Object o) { if (o==null) return ""; return o.toString(); } long timer = System.currentTimeMillis(); void startTimer() { timer = System.currentTimeMillis(); } void stopTimer() { System.err.println("time: "+(System.currentTimeMillis()-timer)/1000.0); } static class InputReader { private byte[] buf; private int bufPos = 0, bufLim = -1; private InputStream stream; public InputReader(InputStream stream, int size) { buf = new byte[size]; this.stream = stream; } private void fillBuf() throws IOException { bufLim = stream.read(buf); bufPos = 0; } char read() throws IOException { if (bufPos>=bufLim) fillBuf(); return (char)buf[bufPos++]; } boolean hasInput() throws IOException { if (bufPos>=bufLim) fillBuf(); return bufPos<bufLim; } } static InputReader inputReader; static BufferedWriter outputWriter; char nextChar() throws IOException { return inputReader.read(); } char nextNonWhitespaceChar() throws IOException { char c = inputReader.read(); while (c<=' ') c=inputReader.read(); return c; } String nextWord() throws IOException { StringBuilder sb = new StringBuilder(); char c = inputReader.read(); while (c<=' ') c=inputReader.read(); while (c>' ') { sb.append(c); c = inputReader.read(); } return new String(sb); } String nextLine() throws IOException { StringBuilder sb = new StringBuilder(); char c = inputReader.read(); while (c<=' ') c=inputReader.read(); while (c!='\n' && c!='\r') { sb.append(c); c = inputReader.read(); } return new String(sb); } int nextInt() throws IOException { int r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r=c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10; r+=c-48; c=nextChar(); } return neg ? -r:r; } long nextLong() throws IOException { long r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r = c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10L; r+=c-48L; c=nextChar(); } return neg ? -r:r; } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextWord()); } int[] nextArr(int size) throws NumberFormatException, IOException { int[] arr = new int[size]; for (int i=0; i<size; ++i) arr[i] = nextInt(); return arr; } long[] nextArrL(int size) throws NumberFormatException, IOException { long[] arr = new long[size]; for (int i=0; i<size; ++i) arr[i] = nextLong(); return arr; } double[] nextArrD(int size) throws NumberFormatException, IOException { double[] arr = new double[size]; for (int i=0; i<size; ++i) arr[i] = nextDouble(); return arr; } String[] nextArrS(int size) throws NumberFormatException, IOException { String[] arr = new String[size]; for (int i=0; i<size; ++i) arr[i] = nextWord(); return arr; } char[] nextArrCh(int size) throws IOException { char[] arr = new char[size]; for (int i=0; i<size; ++i) arr[i] = nextNonWhitespaceChar(); return arr; } char[][] nextArrCh(int rows, int columns) throws IOException { char[][] arr = new char[rows][columns]; for (int i=0; i<rows; ++i) for (int j=0; j<columns; ++j) arr[i][j] = nextNonWhitespaceChar(); return arr; } char[][] nextArrChBorders(int rows, int columns, char border) throws IOException { char[][] arr = new char[rows+2][columns+2]; for (int i=1; i<=rows; ++i) for (int j=1; j<=columns; ++j) arr[i][j] = nextNonWhitespaceChar(); for (int i=0; i<columns+2; ++i) { arr[0][i] = border; arr[rows+1][i] = border; } for (int i=0; i<rows+2; ++i) { arr[i][0] = border; arr[i][columns+1] = border; } return arr; } void printf(String format, Object... args) throws IOException { outputWriter.write(String.format(format, args)); } void print(Object o) throws IOException { outputWriter.write(o.toString()); } void println(Object o) throws IOException { outputWriter.write(o.toString()); outputWriter.newLine(); } void print(Object... o) throws IOException { for (int i=0; i<o.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(o[i].toString()); } } void println(Object... o) throws IOException { print(o); outputWriter.newLine(); } void printn(Object o, int n) throws IOException { String s = o.toString(); for (int i=0; i<n; ++i) { outputWriter.write(s); if (i!=n-1) outputWriter.write(' '); } } void printnln(Object o, int n) throws IOException { printn(o, n); outputWriter.newLine(); } void printArr(int[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Integer.toString(arr[i])); } } void printArr(long[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Long.toString(arr[i])); } } void printArr(double[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(Double.toString(arr[i])); } } void printArr(String[] arr) throws IOException { for (int i=0; i<arr.length; ++i) { if (i!=0) outputWriter.write(' '); outputWriter.write(arr[i]); } } void printArr(char[] arr) throws IOException { for (char c: arr) outputWriter.write(c); } void printlnArr(int[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(long[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(double[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(String[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void printlnArr(char[] arr) throws IOException { printArr(arr); outputWriter.newLine(); } void halt(Object... o) throws IOException { if (o.length!=0) println(o); outputWriter.flush(); outputWriter.close(); System.exit(0); } void debug(Object... o) { if (showDebug) System.err.println(Arrays.deepToString(o)); } public static void main(String[] args) throws Exception { Locale.setDefault(Locale.US); if (!useFiles) { inputReader = new InputReader(System.in, 1<<16); outputWriter = new BufferedWriter(new OutputStreamWriter(System.out), 1<<16); } else { inputReader = new InputReader(new FileInputStream(new File(inFile)), 1<<16); outputWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outFile))), 1<<16); } new A().solve(); outputWriter.flush(); outputWriter.close(); } }
nlogn
160_A. Twins
CODEFORCES
import java.util.*; import java.text.*; import java.io.*; import java.math.*; public class code5 { InputStream is; PrintWriter out; static long mod=pow(10,9)+7; static int dx[]={0,0,1,-1},dy[]={1,-1,0,0}; String arr[]; long dp[][]; void solve() throws IOException { int n=ni(); int a[]=na(n); int q=ni(); boolean flag=false; for(int i=0;i<n;i++) { for(int j=0;j<i;j++) { if(a[j]>a[i]) flag^=true; } } while(q--!=0) { int l=ni()-1; int r=ni()-1; int num=(r-l+1); int tot=num*(num-1)/2; if(tot%2==1) flag^=true; if(flag) out.println("odd"); else out.println("even"); } } int sum(int i) { int sum=0; while(i!=0) { if((i%10)%2==1) sum+=i%10; i/=10; } return sum; } ArrayList<Integer> al[]; void take(int n,int m) { al=new ArrayList[n]; for(int i=0;i<n;i++) al[i]=new ArrayList<Integer>(); for(int i=0;i<m;i++) { int x=ni()-1; int y=ni()-1; al[x].add(y); al[y].add(x); } } int check(long n) { int count=0; while(n!=0) { if(n%10!=0) break; n/=10; count++; } return count; } public static int count(int x) { int num=0; while(x!=0) { x=x&(x-1); num++; } return num; } static long d, x, y; void extendedEuclid(long A, long B) { if(B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A%B); long temp = x; x = y; y = temp - (A/B)*y; } } long modInverse(long A,long M) //A and M are coprime { extendedEuclid(A,M); return (x%M+M)%M; //x may be negative } public static void mergeSort(int[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(int arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); int left[] = new int[n1]; int right[] = new int[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } public static void mergeSort(long[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(long arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); long left[] = new long[n1]; long right[] = new long[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } static class Pair implements Comparable<Pair>{ int x,y,k; int i,dir; long val; Pair (int x,int y){ this.x=x; this.y=y; } public int compareTo(Pair o) { if(this.x!=o.x) return this.x-o.x; return this.y-o.y; } public String toString(){ return x+" "+y+" "+k+" "+i;} public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode() ; } } public static boolean isPal(String s){ for(int i=0, j=s.length()-1;i<=j;i++,j--){ if(s.charAt(i)!=s.charAt(j)) return false; } return true; } public static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } public static long gcd(long x,long y){ if(y==0) return x; else return gcd(y,x%y); } public static int gcd(int x,int y){ if(y==0) return x; return gcd(y,x%y); } public static long gcdExtended(long a,long b,long[] x){ if(a==0){ x[0]=0; x[1]=1; return b; } long[] y=new long[2]; long gcd=gcdExtended(b%a, a, y); x[0]=y[1]-(b/a)*y[0]; x[1]=y[0]; return gcd; } public static int abs(int a,int b){ return (int)Math.abs(a-b); } public static long abs(long a,long b){ return (long)Math.abs(a-b); } public static int max(int a,int b){ if(a>b) return a; else return b; } public static int min(int a,int b){ if(a>b) return b; else return a; } public static long max(long a,long b){ if(a>b) return a; else return b; } public static long min(long a,long b){ if(a>b) return b; else return a; } public static long pow(long n,long p,long m){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void run() throws Exception { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { new code5().run(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); //new code5().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { private static IO io; public static void main(String[] args) throws IOException { new Main().run(); } private void run() throws IOException { io = new IO(System.getProperty("ONLINE_JUDGE")!=null); solve(); io.flush(); } private void solve() throws IOException { int n = io.nI(), a = io.nI(), b = io.nI(), h[] = new int[n], i; for(i = 0; i<n; i++)h[i] = io.nI(); Arrays.sort(h); io.wln(h[b]-h[b-1]); }//2.2250738585072012e-308 private int gcd(int a, int b) { while(b>0) b^=a^=b^=a%=b; return a; } @SuppressWarnings("unused") private class IO{ StreamTokenizer in; PrintWriter out; BufferedReader br; Reader reader; Writer writer; public IO(boolean oj) throws IOException{ Locale.setDefault(Locale.US); reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt"); writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt"); br = new BufferedReader(reader); in = new StreamTokenizer(br); out = new PrintWriter(writer); } public void wln(){out.println();} public void wln(int arg){out.println(arg);} public void wln(long arg){out.println(arg);} public void wln(double arg){out.println(arg);} public void wln(String arg){out.println(arg);} public void wln(boolean arg){out.println(arg);} public void wln(char arg){out.println(arg);} public void wln(float arg){out.println(arg);} public void wln(Object arg){out.println(arg);} public void w(int arg){out.print(arg);} public void w(long arg){out.print(arg);} public void w(double arg){out.print(arg);} public void w(String arg){out.print(arg);} public void w(boolean arg){out.print(arg);} public void w(char arg){out.print(arg);} public void w(float arg){out.print(arg);} public void w(Object arg){out.print(arg);} public void wf(String format, Object...args){out.printf(format, args);} public void flush(){out.flush();} public int nI() throws IOException {in.nextToken(); return(int)in.nval;} public long nL() throws IOException {in.nextToken(); return(long)in.nval;} public String nS() throws IOException {in.nextToken(); return in.sval;} public double nD() throws IOException {in.nextToken(); return in.nval;} public float nF() throws IOException {in.nextToken(); return (float)in.nval;} public void wc(char...a){for(char c : a){in.ordinaryChar(c);in.wordChars(c, c);}} public void wc(char c1, char c2){in.ordinaryChars(c1, c2); in.wordChars(c1, c2);} } }
nlogn
169_A. Chores
CODEFORCES
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class P111C{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int h, w; void run(){ h=sc.nextInt(); w=sc.nextInt(); solve(); } void shuffle(int[] is){ Random rand=new Random(); for(int i=is.length-1; i>=1; i--){ int j=rand.nextInt(i+1); int t=is[i]; is[i]=is[j]; is[j]=t; } } void solve(){ n=w*h; g=new long[n]; int[] dx={0, 0, -1, 1}; int[] dy={-1, 1, 0, 0}; for(int y=0; y<h; y++){ for(int x=0; x<w; x++){ for(int k=0; k<4; k++){ int x2=x+dx[k]; int y2=y+dy[k]; if(x2>=0&&x2<w&&y2>=0&&y2<h){ g[y*w+x]|=1L<<(y2*w+x2); } } } } candidate=new int[n]; xs=new Xorshift(); mds=(1L<<n)-1; mds(0, 0, 0); println((n-Long.bitCount(mds))+""); } int n; long[] g; long mds; int[] candidate; Xorshift xs; void mds(long choosed, long removed, long covered){ if(Long.bitCount(choosed)>=Long.bitCount(mds)) return; if(covered==((1L<<n)-1)){ if(Long.bitCount(choosed)<Long.bitCount(mds)) mds=choosed; return; } int index=0; int k=-1; for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){ int i=Long.numberOfTrailingZeros(remained); if((covered>>>i&1)==1){ if(Long.bitCount(g[i]&~covered)==0){ mds(choosed, removed|(1L<<i), covered); return; }else if(Long.bitCount(g[i]&~covered)==1 &&(g[i]&~covered&~removed)!=0){ mds(choosed, removed|(1L<<i), covered); return; } }else{ if(Long.bitCount(g[i]&~removed)==0){ mds(choosed|(1L<<i), removed|(1L<<i), covered|(1L<<i)|g[i]); return; }else if(Long.bitCount(g[i]&~removed)==1 &&((g[i]&~removed)|(g[i]&~covered))==(g[i]&~removed)){ int j=Long.numberOfTrailingZeros(g[i]&~removed); mds(choosed|(1L<<j), removed|(1L<<i)|(1L<<j), covered |(1L<<j)|g[j]); return; } } // if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)) // k=i; if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)){ index=0; candidate[index++]=i; k=i; }else if(Long.bitCount(g[i]&~covered)==Long.bitCount(g[k]&~covered)){ candidate[index++]=i; } } if(k==-1) return; k=candidate[xs.nextInt(index)]; mds(choosed|(1L<<k), removed|(1L<<k), covered|(1L<<k)|g[k]); mds(choosed, removed|(1L<<k), covered); } class Xorshift{ int x, y, z, w; public Xorshift(){ x=123456789; y=362436069; z=521288629; w=88675123; } public Xorshift(int seed){ x=_(seed, 0); y=_(x, 1); z=_(y, 2); w=_(z, 3); } int _(int s, int i){ return 1812433253*(s^(s>>>30))+i+1; } // 32bit signed public int nextInt(){ int t=x^(x<<11); x=y; y=z; z=w; return w=w^(w>>>19)^t^(t>>>8); } // error = O(n*2^-32) public int nextInt(int n){ return (int)(n*nextDouble()); } // [0, 1) (53bit) public double nextDouble(){ int a=nextInt()>>>5, b=nextInt()>>>6; return (a*67108864.0+b)*(1.0/(1L<<53)); } } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(Arrays.deepToString(os)); } public static void main(String[] args){ Locale.setDefault(Locale.US); new P111C().run(); } }
np
111_C. Petya and Spiders
CODEFORCES
import java.io.*; import java.util.*; public class p343a { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println(); long a = sc.nextLong(); long b = sc.nextLong(); if(a==b) System.out.println("1"); else if(b==1) System.out.println(a); else if(a==1) System.out.println(b); else if(a>b) System.out.println(count(a,b)); else System.out.println(count(b,a)); } public static long count(long a,long b) { long count = 0; while(b!=1) { long c = a/b; count += c; long d = a-(c*b); a = b; b = d; if(b==1) { count += a; break; } } return count; } }
constant
343_A. Rational Resistance
CODEFORCES
import java.util.*; import java.io.*; public class A{ static long mod = 1000000000+7; static int arr[]; static HashMap<Long,Long> map = new HashMap<>(); public static void main(String[] args) { Scanner scan = new Scanner(System.in); long x = scan.nextLong(); long k = scan.nextLong(); if(x == 0) { System.out.println(0); return; } x = x%mod; long power = pow(2,k + 1)%mod; power = (power*x)%mod; long num = (pow(2,k) - 1 + mod)%mod; long ans = (power - num + mod)%mod; System.out.println((ans)); } public static long pow(long a,long b) { if(b == 0) return 1; if(b == 1) return a; long x1,x2; if(map.containsKey(b - b/2)) x1 = map.get(b - b/2); else { x1 = pow(a,b - b/2)%mod; map.put(b - b/2,x1); } if(map.containsKey(b/2)) x2 = map.get(b/2); else { x2 = pow(a,b/2)%mod; map.put(b/2,x2); } return (x1*x2)%mod; } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
//package codeforces.br25; import java.io.*; import java.math.*; import java.util.*; public class ProblemA { public void solve() { boolean oj = true; try { Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("A.in"); Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("A.out"); BufferedReader br = new BufferedReader(reader); StreamTokenizer st = new StreamTokenizer(reader); PrintWriter out = new PrintWriter(writer); int n = Integer.valueOf(br.readLine()); String s = br.readLine(); MyTokenizer tok = new MyTokenizer(s); int[] a = new int[2]; int[] ind = new int[2]; int[] c = new int[2]; for(int i=0;i<n;i++) { int p = (int)tok.getNum(); c[p%2]++; a[p%2] = p; ind[p%2] = i; } int b = ind[0]; if (c[0] > c[1]) b = ind[1]; out.printf("%d", b + 1); br.close(); out.close(); reader.close(); writer.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { } } public static void main(String[] args) { ProblemA f = new ProblemA(); f.solve(); } private class MyTokenizer { private String s; private int cur; public MyTokenizer(String s) { this.s = s; cur = 0; } public void skip() { while (cur < s.length() && (s.charAt(cur) == ' ' || s.charAt(cur) == '\n')) { cur++; } } public double getNum() { skip(); String snum = ""; while (cur < s.length() && (s.charAt(cur) >= '0' && s.charAt(cur) <= '9' || s.charAt(cur) == '.' || s.charAt(cur) == '-')) { snum += s.charAt(cur); cur++; } return Double.valueOf(snum); } public String getString() { skip(); String s2 = ""; while (cur < s.length() && (((s.charAt(cur) >= 'a' && s.charAt(cur) <= 'z')) || ((s.charAt(cur) >= 'A' && s.charAt(cur) <= 'Z')))) { s2 += s.charAt(cur); cur++; } return s2; } public char getCurrentChar() throws Exception { if (cur < s.length()) return s.charAt(cur); else throw new Exception("Current character out of string length"); } public void moveNextChar() { if (cur < s.length()) cur++; } public boolean isFinished() { return cur >= s.length(); } } }
linear
25_A. IQ test
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Main { protected static final double EPS = 1e-11; private static StreamTokenizer in; private static Scanner ins; private static PrintWriter out; protected static final Double[] BAD = new Double[]{null, null}; private boolean[][] layouts; private int c; private int b; private int a; private String word; public static void main(String[] args) { try { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); ins = new Scanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); try { if (System.getProperty("xDx") != null) { in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt"))); ins = new Scanner(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); } } catch (Exception e) { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); ins = new Scanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); } new Main().run(); } catch (Throwable e) { // e.printStackTrace(); throw new RuntimeException(e); } finally { out.close(); } } private int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } private long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } private double nextDouble() throws IOException { in.nextToken(); return in.nval; } private String nextString() throws IOException { in.nextToken(); return in.sval; } private char nextChar() throws IOException { in.nextToken(); return (char) in.ttype; } private void run() throws Exception { /*int t = nextInt(); for (int i = 0; i < t; i++) { out.printf(Locale.US, "Case #%d: %d\n", i + 1, solve()); }*/ solve(); } private void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } Map<Long, Integer> map = new HashMap<>(); BigInteger res = BigInteger.ZERO; long sum = 0; long amount = 0; for (int i = n - 1; i >= 0; i--) { long cur = a[i]; Pair same = getZeroAmount(cur, map); res = res.add(BigInteger.valueOf((sum - same.sum) - cur * (amount - same.amount))); amount++; sum += cur; map.put(cur, map.getOrDefault(cur, 0) + 1); } out.println(res); } class Pair { long amount; long sum; public Pair(long amount, long sum) { this.amount = amount; this.sum = sum; } } private Pair getZeroAmount(long cur, Map<Long, Integer> map) { long amount = 0; long sum = 0; for (long i = cur - 1; i <= cur + 1; i++) { long amountI = map.getOrDefault(i, 0); amount += amountI; sum += amountI * i; } return new Pair(amount, sum); } private List<Integer> iterate(List<Integer> a) { ArrayList<Integer> b = new ArrayList<>(); int prev = -1; for (int x : a) { if (x == prev) { b.add(x); } else { prev = x; } } return b; } private long gcd(long a, long b) { while (a > 0 && b > 0) { long k = a % b; a = b; b = k; } return a | b; } }
nlogn
903_D. Almost Difference
CODEFORCES
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class D { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); // int n = Integer.parseInt(bf.readLine()); StringTokenizer st = new StringTokenizer(bf.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); for(int i=0; i<100000; i++) { long mult = 1L*i*(i+1)/2; long b = 1L*mult - k; if(i+b == n*1L) { out.println(b); out.close(); System.exit(0); } } //out.println(count); out.close(); System.exit(0); } } // a(a+1)/2 - b = k; a+b = n
logn
1195_B. Sport Mafia
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] arr = new int[n]; HashMap<Integer, Integer> map = new HashMap<>(); StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { int x = Integer.parseInt(st.nextToken()); arr[i] = x; if (!map.containsKey(x)) { map.put(x, 1); } else { map.replace(x, map.get(x) + 1); } } int[] power = new int[31]; for (int i = 0; i < 31; i++) { power[i] = 1 << i; // 0 100=4 1000=8 10000=16 } int c = 0; for (int i = 0; i < n; i++) { boolean f = false; for (int j = 0; j <= 30; j++) { int check = power[j] - arr[i]; if ((map.containsKey(check) && check != arr[i])) { f = true; break;} if((map.containsKey(check) && check == arr[i] && map.get(check) >=2)) { f = true; break; } } if (!f) { c++; } } System.out.println(c); } }
nlogn
1005_C. Summarize to the Power of Two
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeMap; public class A { private static final long MOD = 1000000009L; public static void main(String [] args) throws IOException { Scanner in = new Scanner(System.in); long n = in.nextInt(); long m = in.nextInt(); long k = in.nextInt(); long w = n-m; long c = w*k; if(c >= n) { System.out.println(m); return; } long rem = n-c; long h = rem/k; long p = power(2, h+1); p -= 2; p += MOD; p %= MOD; p *= k; p %= MOD; long point = p + m - (h*k) % MOD; point += MOD; point %= MOD; System.out.println(point); } private static long power(int num, long power) { if(power == 0) return 1; long res = power(num, power/2); res = (res*res)%MOD; if(power % 2 != 0) res *= num; res%=MOD; return res; } }
logn
338_A. Quiz
CODEFORCES
import java.util.Scanner; public class A { public static void main(String[] args) { new A().solve(); } public void solve() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int t = sc.nextInt(); float[] left = new float[n]; float[] right = new float[n]; for (int i=0; i<n; ++i) { int c = sc.nextInt(); int w = sc.nextInt(); left[i] = (float) (c - (float) w * 1.0 / 2); right[i] = (float) (c + (float) w * 1.0 / 2); } for (int i=0; i<n; ++i) for (int j=i+1; j<n; ++j) if (left[j] < left[i]) { float tmp = left[i]; left[i] = left[j]; left[j] = tmp; tmp = right[i]; right[i] = right[j]; right[j] = tmp; } int res = 2; for (int i=1; i<n; ++i) { float dis = left[i] - right[i-1]; if (Math.abs(dis - t) < 0.000001) res ++; if ((dis - t) > 0.000001) res += 2; } System.out.println(res); } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author pttrung */ public class B { static Senator[] data; public static void main(String[] args) { Scanner in = new Scanner(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int k = in.nextInt(); int A = in.nextInt(); data = new Senator[n]; for (int i = 0; i < n; i++) { data[i] = new Senator(in.nextInt(), in.nextInt()); } out.println(cal(0, new int[n], A, k)); out.close(); } public static double cal(int index, int[] num, int A, int left) { if (index == data.length - 1) { int dif = (100 - data[index].loyal)/10; dif = left >= dif? dif:left; num[index] = dif; double result = 0; for (int k = 0; k < (1 << num.length); k++) { double val = 1; double total = 0; for (int i = 0; i < num.length; i++) { if (((1 << i) & k) != 0) { val *= ((double)(data[i].loyal + 10*num[i])/100); } else { val *= ((double)(100 - (data[i].loyal + 10*num[i]))/100); total += data[i].level; } } if (countBit(k) > num.length / 2) { result += val; } else { result += val * ((double) A / (A + total)); } } // // if(result >= 1){ // for(int i : num){ // System.out.print(i + " "); // } // System.out.println("\n" + result); // //} return result; } else { double result = 0; for (int i = 0; i <= left; i++) { if (i * 10 + data[index].loyal <= 100) { num[index] = i; // double val = cal(index + 1 , num , A, left - i); result = Math.max(result, cal(index + 1, num, A, left - i)); } else { break; } } return result; } } public static int countBit(int val) { int result = 0; while (val > 0) { result += val % 2; val >>= 1; } return result; } public static class Senator { int level, loyal; public Senator(int level, int loyal) { this.level = level; this.loyal = loyal; } } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static class Point { int x, y, z; public Point(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } public double pow(double a, int b) { if (b == 0) { return 1; } if (b == 1) { return a; } double val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * val * a; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long lcm(long a, long b) { return a * b / gcd(a, b); } }
np
105_B. Dark Assembly
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class MainC { private FastScanner in; private PrintWriter out; private int N; private Dist[] dists; private int countDists; private int[][] minLeft;// startsFrom, count private int[] minOrder; private int minOrderCount = 10000000; public void solve() throws IOException { int xb = in.nextInt(); int yb = in.nextInt(); N = in.nextInt(); int[] x, y; boolean isOdd; if (N % 2 == 0) { x = new int[N]; y = new int[N]; isOdd = false; } else { x = new int[N + 1]; y = new int[N + 1]; isOdd = true; } for (int i = 0; i < N; i++) { x[i] = in.nextInt() - xb; y[i] = in.nextInt() - yb; } if (N % 2 == 1) { N++; x[N - 1] = 0; y[N - 1] = 0; } countDists = N * (N - 1) / 2; dists = new Dist[countDists]; int c = 0; int commonSum = 0; for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { dists[c] = new Dist(); dists[c].from = i; dists[c].to = j; dists[c].dist = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]); dists[c].dist = Math.min(dists[c].dist, x[i] * x[i] + y[i] * y[i] + x[j] * x[j] + y[j] * y[j]); c++; } commonSum += x[i] * x[i] + y[i] * y[i]; } Arrays.sort(dists); minLeft = new int[countDists][N + 1]; for (int i = 0; i < countDists; i++) { int sum = 0; for (int j = 1; j <= N; j++) { if (i + j - 1 < countDists) { sum = sum + dists[i + j - 1].dist; minLeft[i][j] = sum; } else { minLeft[i][j] = 100000000; } } } order(0, new int[N], 0, 0); out.println(minOrderCount + commonSum); for (int i = 1; i <= N / 2; i++) { int first = -1; int second = -1; for (int j = 0; j < N; j++) { if (minOrder[j] == i) { if (first == -1) { first = j; } else { second = j; } } } if (isOdd && (first == N - 1 || second == N - 1)) { first++; second++; out.print("0 " + (first + second - N) + " "); } else if (x[first] * x[first] + y[first] * y[first] + x[second] * x[second] + y[second] * y[second] < (x[first] - x[second]) * (x[first] - x[second]) + (y[first] - y[second]) * (y[first] - y[second])) { first++; second++; out.print("0 " + first + " 0 " + second + " "); } else { first++; second++; out.print("0 " + first + " " + second + " "); } } out.println("0"); } private void order(int countOrdered, int[] order, int startsFrom, int sum) { if (countOrdered == N) { if (sum < minOrderCount) { minOrder = Arrays.copyOf(order, N); minOrderCount = sum; } return; } while (startsFrom < countDists) { if (order[dists[startsFrom].from] == 0 && order[dists[startsFrom].to] == 0) { if (minLeft[startsFrom][(N - countOrdered) / 2] + sum >= minOrderCount) { break; } order[dists[startsFrom].from] = countOrdered / 2 + 1; order[dists[startsFrom].to] = countOrdered / 2 + 1; order(countOrdered + 2, order, startsFrom + 1, sum + dists[startsFrom].dist); order[dists[startsFrom].from] = 0; order[dists[startsFrom].to] = 0; } startsFrom++; } } private class Dist implements Comparable<Dist> { int from; int to; int dist; @Override public int compareTo(Dist o) { if (dist < o.dist) { return -1; } if (dist == o.dist) { return 0; } return 1; } } 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()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] arg) { new MainC().run(); } }
np
8_C. Looking for Order
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class C { public static void main(String[] args) { new C(); } final int oo = (int)1e9; int Hx,Hy; int N; int[][] P; int[] memo; int[][] soln; int[] dist1; int[][] dist2; C() { Scanner in = new Scanner(System.in); Hx=in.nextInt(); Hy=in.nextInt(); N=in.nextInt(); P=new int[N][2]; for (int i=0; i<N; ++i) { P[i][0]=in.nextInt(); P[i][1]=in.nextInt(); } memo=new int[1<<N]; Arrays.fill(memo, -1); soln=new int[2][1<<N]; dist1=new int[N]; Arrays.fill(dist1, -1); dist2=new int[N][N]; for (int[] d : dist2) Arrays.fill(d, -1); int res=go((1<<N)-1); System.out.println(res); int set=(1<<N)-1; while (set>0) { System.out.print("0 "); System.out.print((soln[0][set]+1)+" "); if (soln[1][set]>-1) System.out.print((soln[1][set]+1)+" "); if (soln[1][set]>-1) { set-=((1<<soln[0][set])+(1<<soln[1][set])); } else { set-=(1<<soln[0][set]); } } System.out.println("0"); } int go(int set) { if (set==0) return 0; if (memo[set]>-1) return memo[set]; int res=oo; int i=0; while (!on(set,i)) ++i; res=dist(i)+go(set-(1<<i)); soln[0][set]=i; soln[1][set]=-1; for (int j=i+1; j<N; ++j) { if (on(set,j)) { int tmp=dist(i,j)+go(set-(1<<i)-(1<<j)); if (tmp<res) { res=tmp; soln[0][set]=i; soln[1][set]=j; } } } return memo[set]=res; } // H->i->H int dist(int i) { if (dist1[i]>-1) return dist1[i]; int dx=P[i][0]-Hx; int dy=P[i][1]-Hy; return dist1[i]=2*(dx*dx+dy*dy); } // H->i->j->H int dist(int i, int j) { if (dist2[i][j]>-1) return dist2[i][j]; int res=0,dx,dy; dx=P[i][0]-Hx; dy=P[i][1]-Hy; res+=dx*dx+dy*dy; dx=P[i][0]-P[j][0]; dy=P[i][1]-P[j][1]; res+=dx*dx+dy*dy; dx=P[j][0]-Hx; dy=P[j][1]-Hy; res+=dx*dx+dy*dy; return dist2[i][j]=res; } boolean on(int set, int loc) { return (set&(1<<loc))>0; } }
np
8_C. Looking for Order
CODEFORCES
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner in=new Scanner(System.in); long x=in.nextLong(); long k=in.nextLong(); long mod=1000000007; long get=power(2,k,mod); long ans=((get%mod)*((2*x)%mod))%mod-get+1; if(ans<0) ans+=mod; if(x==0) ans=0; System.out.println(ans); } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if((y & 1)==1) res = (res * x) % p; // y must be even now // y = y / 2 y = y >> 1; x = (x * x) % p; } return res; } }
logn
992_C. Nastya and a Wardrobe
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author KharYusuf */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); APaintTheNumbers solver = new APaintTheNumbers(); solver.solve(1, in, out); out.close(); } static class APaintTheNumbers { public void solve(int testNumber, FastReader s, PrintWriter w) { int n = s.nextInt(); boolean[] b = new boolean[n]; int[] a = new int[n]; int ans = 0; for (int i = 0; i < n; i++) { a[i] = s.nextInt(); } func.sort(a); for (int i = 0; i < n; i++) { if (!b[i]) { ans++; b[i] = true; for (int j = i + 1; j < n; j++) { //w.println(a[j]+" "+a[i]); if (a[j] % a[i] == 0) { b[j] = true; } } } } w.println(ans); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(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 - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class func { public static void sort(int[] arr) { int n = arr.length, mid, h, s, l, i, j, k; int[] res = new int[n]; for (s = 1; s < n; s <<= 1) { for (l = 0; l < n - 1; l += (s << 1)) { h = Math.min(l + (s << 1) - 1, n - 1); mid = Math.min(l + s - 1, n - 1); i = l; j = mid + 1; k = l; while (i <= mid && j <= h) res[k++] = (arr[i] <= arr[j] ? arr[i++] : arr[j++]); while (i <= mid) res[k++] = arr[i++]; while (j <= h) res[k++] = arr[j++]; for (k = l; k <= h; k++) arr[k] = res[k]; } } } } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; public class Main { static final int MOD = (int)1e9 + 7; static int n; static int[] t; static int[] g; static int[][] memo; static int dp(int mask, int rem, int last) { if(rem == 0) return 1; if(memo[last][mask] != -1) return memo[last][mask]; int ans = 0; for(int i = 0; i < n; i++) { if((mask & (1 << i)) == 0 && rem >= t[i] && g[i] != last) ans += dp(mask | 1 << i, rem - t[i], g[i]); if(ans >= MOD) ans -= MOD; } return memo[last][mask] = ans; } public static void main (String[] args) throws java.lang.Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); n = in.nextInt(); int T = in.nextInt(); t = new int[n]; g = new int[n]; for(int i = 0; i < n; i++) { t[i] = in.nextInt(); g[i] = in.nextInt() - 1; } memo = new int[4][1 << n]; for(int []x : memo) { Arrays.fill(x, -1); } out.println(dp(0, T, 3)); out.close(); } 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()); } catch(IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
np
1185_G1. Playlist for Polycarp (easy version)
CODEFORCES
// upsolve with rainboy import java.io.*; import java.util.*; public class CF1187G extends PrintWriter { CF1187G() { super(System.out); } static class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; int k, l; byte[] bb = new byte[1 << 15]; byte getc() { if (k >= l) { k = 0; try { l = in.read(bb); } catch (IOException e) { l = 0; } if (l <= 0) return -1; } return bb[k++]; } int nextInt() { byte c = 0; while (c <= 32) c = getc(); int a = 0; while (c > 32) { a = a * 10 + c - '0'; c = getc(); } return a; } } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1187G o = new CF1187G(); o.main(); o.flush(); } static final int INF = 0x3f3f3f3f; ArrayList[] aa_; int n_, m_; int[] pi, kk, bb; int[] uu, vv, 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_]; kk = 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); } void dijkstra(int s) { Arrays.fill(pi, INF); pi[s] = 0; TreeSet<Integer> pq = new TreeSet<>((u, v) -> pi[u] != pi[v] ? pi[u] - pi[v] : kk[u] != kk[v] ? kk[u] - kk[v] : u - v); pq.add(s); Integer first; while ((first = pq.pollFirst()) != null) { int u = first; int k = kk[u] + 1; ArrayList<Integer> adj = aa_[u]; for (int h_ : adj) if (cc[h_] > 0) { int h = h_ >> 1; int p = pi[u] + ((h_ & 1) == 0 ? cost_[h] : -cost_[h]); int v = u ^ uv[h]; if (pi[v] > p || pi[v] == p && kk[v] > k) { if (pi[v] < INF) pq.remove(v); pi[v] = p; kk[v] = k; bb[v] = h_; pq.add(v); } } } } void push(int s, int t) { int c = INF; for (int u = t, h_, h; u != s; u ^= 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) { System.arraycopy(cost, 0, cost_, 0, m_); while (true) { dijkstra(s); if (pi[t] == INF) break; push(s, t); for (int h = 0; h < m_; h++) { int u = uu[h], v = vv[h]; if (pi[u] != INF && pi[v] != INF) cost_[h] += pi[u] - pi[v]; } } int c = 0; for (int h = 0; h < m_; h++) c += cost[h] * cc[h << 1 ^ 1]; return c; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); int[] ii = new int[k]; for (int h = 0; h < k; h++) ii[h] = sc.nextInt() - 1; ArrayList[] aa = new ArrayList[n]; for (int i = 0; i < n; i++) aa[i] = new ArrayList<Integer>(); for (int h = 0; h < m; h++) { int i = sc.nextInt() - 1; int j = sc.nextInt() - 1; aa[i].add(j); aa[j].add(i); } int t = n + k + 1; n_ = n * t + 1; m_ = k + (m * 2 * k + n) * (t - 1); init(); for (int i = 0; i < n; i++) { ArrayList<Integer> adj = aa[i]; for (int s = 0; s < t - 1; s++) { int u = i * t + s; for (int j : adj) { int v = j * t + s + 1; for (int x = 1; x <= k; x++) link(u, v, 1, c + (x * 2 - 1) * d); } } } for (int i = 0; i < n; i++) for (int s = 0; s < t - 1; s++) { int u = i * t + s, v = u + 1; link(u, v, k, i == 0 ? 0 : c); } for (int h = 0; h < k; h++) link(n_ - 1, ii[h] * t + 0, 1, 0); println(edmonds_karp(n_ - 1, 0 * t + t - 1)); } }
cubic
1187_G. Gang Up
CODEFORCES
import javafx.util.Pair; import java.util.*; import static java.lang.Math.floor; import static java.lang.Math.min; public class Main { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int n = scanInt(); List<Integer> a = scanList(n); int m = scanInt(); List<Integer> left = new ArrayList<>(); List<Integer> right = new ArrayList<>(); for (int i = 0; i < m; i++) { left.add(scanInt()); right.add(scanInt()); } String even = "even"; String odd = "odd"; int inversions = 0; for (int i = 0; i < a.size(); i++) { for (int j = i; j < a.size(); j++) { if (a.get(i) > a.get(j)) { ++inversions; } } } inversions = inversions % 2; for (int i = 0; i < m; i++) { inversions = (inversions + (right.get(i) - left.get(i) + 1) / 2 % 2) % 2; println(inversions % 2 == 0 ? even : odd); } } private static Integer get(int digit, List<Integer> numbers) { Integer toReturn = null; for (Integer number : numbers ) { if (number <= digit) { toReturn = number; break; } } return toReturn; } private static List<Integer> toList(char[] chars) { List<Integer> integers = new ArrayList<>(); for (int i = 0; i < chars.length; i++) { integers.add(Integer.parseInt(String.valueOf(chars[i]))); } return integers; } private static List<Pair<Integer, Integer>> scanPairs(int amount) { List<Pair<Integer, Integer>> list = new ArrayList<>(); for (int i = 0; i < amount; i++) { list.add(new Pair<>(scanInt(), scanInt())); } return list; } private static int[] scanArray(int length) { int array[] = new int[length]; for (int i = 0; i < length; i++) { array[i] = scanner.nextInt(); } return array; } private static List<Integer> scanList(int length) { List<Integer> integers = new ArrayList<>(); for (int i = 0; i < length; i++) { integers.add(scanner.nextInt()); } return integers; } public static String scanString() { return scanner.next(); } private static int scanInt() { return scanner.nextInt(); } private static void println(int n) { System.out.println(n); } private static void print(int n) { System.out.print(n); } private static void println(String s) { System.out.println(s); } private static void print(String s) { System.out.print(s); } private static void print(int a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } }
quadratic
911_D. Inversion Counting
CODEFORCES
import java.util.*; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE; for (int i = 0, x; i < N; ++i) { x = sc.nextInt(); if (x < first) { second = first; first = x; } else if (x > first && x < second) { second = x; } } if (second == Integer.MAX_VALUE) System.out.println("NO"); else System.out.println(second); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.util.*; public class task1 { static void print(Object... a) { for (Object aa : a) { System.out.println(aa.toString()); } } static Map<Character, Integer> stringToCharsMap(String str) { Map<Character, Integer> charcount = new HashMap<Character, Integer>(); for (Character c : str.toCharArray()) { if (charcount.containsKey(c)) { charcount.put(c, charcount.get(c) + 1); } else { charcount.put(c, 1); } } return charcount; } static Set<Character> stringToCharsSet(String str) { Set<Character> chars = new HashSet<>(); for (Character c : str.toCharArray()) { chars.add(c); } return chars; } static int[] readArrayOfInt() { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int array[] = new int[a]; for (int i = 0; i < a; i++) { array[i] = sc.nextInt(); } return array; } static class Point { double x; double y; Point(double x, double y) { this.x = x; this.y = y; } double distance(Point p) { return Math.sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y)); } double distance(Line l) { return Math.abs(l.a * this.x + l.b * this.y + l.c) / Math.sqrt(l.a * l.a + l.b * l.b); } } static class Line { double a; double b; double c; double EPS = 1e-6; Line(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } Line(Point f, Point s) { this.a = f.y - s.y; this.b = s.x - f.x; this.c = -this.a * f.x - this.b * f.y; } double distance(Point p) { return Math.abs(this.a * p.x + this.b * p.y + this.c) / Math.sqrt(this.a * this.a + this.b * this.b); } boolean isPointOnLine(Point p) { return p.x * this.a + p.y * this.b + this.c < EPS; } Point linesIntersection(Line a) { double x = -(this.c * a.b - a.c * this.b) / (this.a * a.b - a.a * this.b); double y = -(this.a * a.c - a.a * this.c) / (this.a * a.b - a.a * this.b); return new Point(x, y); } } static HashMap<Integer, Integer> getDels(int a) { HashMap<Integer, Integer> h = new HashMap<>(); int i = 2; while (a != 1) { if (a % i == 0) { if (h.containsKey(i)) { h.put(i, h.get(i) + 1); } else { h.put(i, 1); } a = a / i; } else { i++; } } return h; } static class Rect { Point fcorner; Point scorner; Rect(Point f, Point s) { fcorner = f; scorner = s; } double volume() { return Math.abs((fcorner.x - scorner.x) * (fcorner.y - scorner.y)); } } public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int arr[] = new int[n]; int c[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } Arrays.sort(arr); int count = 1; c[0] = 1; for (int i = 1; i < arr.length; i++) { for (int j = 0; j < i; j++) { if (arr[i] % arr[j] == 0) { c[i] = c[j]; break; } } if (c[i] == 0) { c[i] = count + 1; count++; } } System.out.println(count); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.*; import java.util.*; public class Main { boolean eof; public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "-1"; } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } int NOD(int a, int b) { while (a * b > 0) { if (a > b) { a %= b; } else { b %= a; } } return a + b; } void solve() { int n = nextInt(), k= nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i){ a[i] = nextInt() - 1; } int[] b = new int[100000]; int p = 0; for (int i = 0; i < n; ++i){ ++b[a[i]]; if (b[a[i]] == 1){ ++p; } if (k == p){ int j; for (j = 0; j <= i; ++j){ if (b[a[j]] > 1){ --b[a[j]]; } else { break; } } out.print((j + 1) + " " + (i + 1)); return; } } out.print("-1 -1"); } BufferedReader br; StringTokenizer st; PrintWriter out; void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); // br = new BufferedReader(new FileReader("input.txt")); // out = new PrintWriter(new FileWriter("output.txt")); solve(); br.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { new Main().run(); } }
linear
224_B. Array
CODEFORCES
import java.io.*; import java.util.*; public class Main { private static void solve(InputReader in, OutputWriter out) { int n = in.nextInt(); if (n < 6) { out.println(-1); } else { int m = (n - 2); for (int i = 2; i <= m; i++) { out.println("1 " + i); } out.println(m + " " + (m + 1)); out.println(m + " " + (m + 2)); } for (int i = 2; i <= n; i++) { out.println("1 " + i); } } private static void shuffleArray(int[] array) { int index; Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { index = random.nextInt(i + 1); if (index != i) { array[index] ^= array[i]; array[i] ^= array[index]; array[index] ^= array[i]; } } } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); solve(in, out); in.close(); out.close(); } private static class InputReader { private BufferedReader br; private StringTokenizer st; InputReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); st = null; } String nextLine() { String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } String next() { while (st == null || !st.hasMoreTokens()) { String line = nextLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } byte nextByte() { return Byte.parseByte(next()); } short nextShort() { return Short.parseShort(next()); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } private static class OutputWriter { BufferedWriter bw; OutputWriter(OutputStream os) { bw = new BufferedWriter(new OutputStreamWriter(os)); } void print(int i) { print(Integer.toString(i)); } void println(int i) { println(Integer.toString(i)); } void print(long l) { print(Long.toString(l)); } void println(long l) { println(Long.toString(l)); } void print(double d) { print(Double.toString(d)); } void println(double d) { println(Double.toString(d)); } void print(boolean b) { print(Boolean.toString(b)); } void println(boolean b) { println(Boolean.toString(b)); } void print(char c) { try { bw.write(c); } catch (IOException e) { e.printStackTrace(); } } void println(char c) { println(Character.toString(c)); } void print(String s) { try { bw.write(s); } catch (IOException e) { e.printStackTrace(); } } void println(String s) { print(s); print('\n'); } void close() { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
linear
959_C. Mahmoud and Ehab and the wrong algorithm
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Solution{ public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringTokenizer st; for(int z=0;z<t;z++){ st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int min=1; int max=1; for(int i=0;i<n;i++){ int k = Integer.parseInt(st.nextToken()); if(max<k){ min = max; max = k; }else if(min<k){ min = k; } } int res = Math.min(n-2,min-1); System.out.println(res); } } }
linear
1197_A. DIY Wooden Ladder
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 Main implements Runnable { boolean TEST = System.getProperty("ONLINE_JUDGE") == null; void solve() throws IOException { int n = nextInt(); Pair[] ps = new Pair[n]; for (int i = 0; i < n; i++) { ps[i] = new Pair(nextInt(), i + 1); } sort(ps, new Comparator<Pair>() { public int compare(Pair a, Pair b) { return a.x - b.x; } }); BigInteger res = find(ps, n); for (int i = 0; i * 2 < n; i++) { Pair t = ps[i]; ps[i] = ps[n - i - 1]; ps[n - i - 1] = t; } res = res.add(find(ps, n)); out.println(res); } BigInteger find(Pair[] ps, int n) { BigInteger res = ZERO; int i = 0; FenwickTree ft = new FenwickTree(n + 1); boolean[] added = new boolean[n + 1]; for (int j = 0; j < n; j++) { if (abs(ps[j].x - ps[i].x) <= 1) continue; while (abs(ps[j].x - ps[i].x) > 1) { if (!added[ps[i].i]) ft.add(ps[i].i, 1); added[ps[i].i] = true; i++; } i--; long total = ft.sum(n); long left = ft.sum(ps[j].i - 1); long right = total - left; res = res.add(valueOf(ps[j].x).multiply(valueOf(left))); res = res.add(valueOf(-ps[j].x).multiply(valueOf(right))); } return res; } class Pair implements Comparable<Pair> { int x, i; Pair(int x, int i) { this.x = x; this.i = i; } public int compareTo(Pair p) { return x - p.x; } public String toString() { return "(" + x + ", " + i + ")"; } } class FenwickTree { int n; int[] tree; public FenwickTree(int n) { this.n = n; tree = new int[n]; } public int sum(int id) { int res = 0; while (id > 0) { res += tree[id]; id -= id & -id; } return res; } public void add(int id, int v) { while (id < n) { tree[id] += v; id += id & -id; } } int findkth(int k) { int low = 1, high = n; while (low < high) { int mid = (low + high) / 2; int val = sum(mid); if(val < k) low = mid + 1; else high = mid; } return low; } } 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 debug(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("input.in")); else input = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedOutputStream(System.out)); //out = new PrintWriter(new BufferedWriter(new FileWriter("output.out"))); } public static void main(String[] args) throws IOException { new Thread(null, new Main(), "", 1 << 20).start(); } public void run() { try { init(); if (TEST) { int runs = nextInt(); for(int i = 0; i < runs; i++) solve(); } else solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
nlogn
903_D. Almost Difference
CODEFORCES
import java.io.*; import java.util.*; public class Main { static Scanner in; static PrintWriter out; // static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;} public static void main(String[] args) throws Exception { in = new Scanner(System.in); out = new PrintWriter(System.out); // in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); int n = in.nextInt(); double[][] p = new double[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) p[i][j] = in.nextDouble(); double[] q = new double[1 << n]; q[(1 << n) - 1] = 1; for (int mask = (1 << n) - 1; mask > 0; mask--) { int count = 0; for (int t = 0; t < n; t++) if (((1 << t) & mask) != 0) count++; if (count <= 1) continue; count = count*(count - 1)/2; for (int t = 0; t < n; t++) if (((1 << t) & mask) != 0) for (int s = 0; s < t; s++) if (((1 << s) & mask) != 0) { q[mask - (1 << t)] += q[mask] / count * p[s][t]; q[mask - (1 << s)] += q[mask] / count * p[t][s]; } } for (int i = 0; i < n; i++) out.print(q[1 << i] + " "); out.close(); } }
np
16_E. Fish
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); COnTheBench solver = new COnTheBench(); solver.solve(1, in, out); out.close(); } } static class COnTheBench { Modular mod = new Modular(1e9 + 7); Factorial fact = new Factorial(1000, mod); Combination comb = new Combination(fact); Debug debug = new Debug(true); public int f(int i, int j) { int ans = mod.mul(fact.fact(i), comb.combination(i + j - 1 - j, j - 1)); ans = mod.mul(ans, fact.invFact(j)); return ans; } public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); DSU dsu = new DSU(n); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = in.readInt(); } for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if (square(a[j] * a[i])) { dsu.merge(j, i); break; } } } IntegerList list = new IntegerList(); for (int i = 0; i < n; i++) { if (dsu.find(i) == i) { list.add(dsu.size[dsu.find(i)]); } } int[] cnts = list.toArray(); debug.debug("cnts", cnts); int m = cnts.length; int[][] dp = new int[m + 1][n + 1]; dp[0][0] = 1; for (int i = 1; i <= m; i++) { int way = cnts[i - 1]; for (int j = 0; j <= n; j++) { dp[i][j] = 0; for (int k = 1; k <= j && k <= way; k++) { int contrib = mod.mul(f(way, k), dp[i - 1][j - k]); dp[i][j] = mod.plus(dp[i][j], contrib); } } } debug.debug("dp", dp); int ans = 0; for (int i = 0; i <= n; i++) { int local = mod.mul(dp[m][i], fact.fact(i)); if ((n - i) % 2 == 1) { local = mod.valueOf(-local); } ans = mod.plus(ans, local); } out.println(ans); } public boolean square(long x) { long l = 1; long r = (long) 1e9; while (l < r) { long m = (l + r) / 2; if (m * m < x) { l = m + 1; } else { r = m; } } return l * l == x; } } static class IntegerList implements Cloneable { private int size; private int cap; private int[] data; private static final int[] EMPTY = new int[0]; public IntegerList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } } public IntegerList(IntegerList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public IntegerList() { this(0); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } public void add(int x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(int[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(IntegerList list) { addAll(list.data, 0, list.size); } public int[] toArray() { return Arrays.copyOf(data, size); } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof IntegerList)) { return false; } IntegerList other = (IntegerList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Integer.hashCode(data[i]); } return h; } public IntegerList clone() { IntegerList ans = new IntegerList(); ans.addAll(this); return ans; } } static class Combination implements IntCombination { final Factorial factorial; final Modular modular; public Combination(Factorial factorial) { this.factorial = factorial; this.modular = factorial.getModular(); } public Combination(int limit, Modular modular) { this(new Factorial(limit, modular)); } public int combination(int m, int n) { if (n > m) { return 0; } return modular.mul(modular.mul(factorial.fact(m), factorial.invFact(n)), factorial.invFact(m - n)); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static interface IntCombination { } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(int c) { cache.append(c); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class InverseNumber { int[] inv; public InverseNumber(int[] inv, int limit, Modular modular) { this.inv = inv; inv[1] = 1; int p = modular.getMod(); for (int i = 2; i <= limit; i++) { int k = p / i; int r = p % i; inv[i] = modular.mul(-k, inv[r]); } } public InverseNumber(int limit, Modular modular) { this(new int[limit + 1], limit, modular); } } static class Debug { private boolean offline; private PrintStream out = System.err; static int[] empty = new int[0]; public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public Debug debug(String name, Object x) { return debug(name, x, empty); } public Debug debug(String name, Object x, int... indexes) { if (offline) { if (x == null || !x.getClass().isArray()) { out.append(name); for (int i : indexes) { out.printf("[%d]", i); } out.append("=").append("" + x); out.println(); } else { indexes = Arrays.copyOf(indexes, indexes.length + 1); if (x instanceof byte[]) { byte[] arr = (byte[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof short[]) { short[] arr = (short[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof boolean[]) { boolean[] arr = (boolean[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof char[]) { char[] arr = (char[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof int[]) { int[] arr = (int[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof float[]) { float[] arr = (float[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof double[]) { double[] arr = (double[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof long[]) { long[] arr = (long[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else { Object[] arr = (Object[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } } } return this; } } static class Factorial { int[] fact; int[] inv; Modular modular; public Modular getModular() { return modular; } public Factorial(int[] fact, int[] inv, InverseNumber in, int limit, Modular modular) { this.modular = modular; this.fact = fact; this.inv = inv; fact[0] = inv[0] = 1; for (int i = 1; i <= limit; i++) { fact[i] = modular.mul(fact[i - 1], i); inv[i] = modular.mul(inv[i - 1], in.inv[i]); } } public Factorial(int limit, Modular modular) { this(new int[limit + 1], new int[limit + 1], new InverseNumber(limit, modular), limit, modular); } public int fact(int n) { return fact[n]; } public int invFact(int n) { return inv[n]; } } static class DSU { protected int[] p; protected int[] rank; int[] size; public DSU(int n) { p = new int[n]; rank = new int[n]; size = new int[n]; reset(); } public final void reset() { for (int i = 0; i < p.length; i++) { p[i] = i; rank[i] = 0; size[i] = 1; } } public final int find(int a) { if (p[a] == p[p[a]]) { return p[a]; } return p[a] = find(p[a]); } public final void merge(int a, int b) { a = find(a); b = find(b); if (a == b) { return; } if (rank[a] == rank[b]) { rank[a]++; } if (rank[a] < rank[b]) { int tmp = a; a = b; b = tmp; } size[a] += size[b]; p[b] = a; } } static class Modular { int m; public int getMod() { return m; } public Modular(int m) { this.m = m; } public Modular(long m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public Modular(double m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public int valueOf(int x) { x %= m; if (x < 0) { x += m; } return x; } public int valueOf(long x) { x %= m; if (x < 0) { x += m; } return (int) x; } public int mul(int x, int y) { return valueOf((long) x * y); } public int plus(int x, int y) { return valueOf(x + y); } public String toString() { return "mod " + m; } } static class SequenceUtils { public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } }
cubic
840_C. On the Bench
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.nextInt(); int r = in.nextInt(); int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); } double res = 0; double[] y = new double[n]; for (int i = 0; i < n; i++) { double curY = r; for (int j = 0; j < i; j++) { int d = Math.abs(x[i] - x[j]); if (d <= 2 * r) { int a2 = 4 * r * r - d * d; curY = Math.max(curY, y[j] + Math.sqrt(a2)); } } y[i] = curY; out.printf("%.14f", y[i]); if (i < n - 1) { out.print(" "); } else { out.println(); } } } } static class InputReader { final InputStream is; final byte[] buf = new byte[1024]; int pos; int size; public InputReader(InputStream is) { this.is = is; } public int nextInt() { int c = read(); while (isWhitespace(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = read(); } while (!isWhitespace(c)); return res * sign; } int read() { if (size == -1) throw new InputMismatchException(); if (pos >= size) { pos = 0; try { size = is.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (size <= 0) return -1; } return buf[pos++] & 255; } static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
quadratic
908_C. New Year and Curling
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 A2 { 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(); b = radixSort(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"); } } 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; } 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 A2().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.io.*; import java.util.*; public class Main { static BufferedReader br; static PrintWriter out; static StringTokenizer st; static int[][] moves = new int[][]{{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; static boolean correct(int x, int y, int n, int m) { return (x >= 0 && x < n && y >= 0 && y < m); } static void solve() throws Exception { int n = nextInt(); int m = nextInt(); int k = nextInt(); int[][] order = new int[n][m]; boolean[][] used = new boolean[n][m]; Queue<Integer[]> q = new LinkedList<>(); Set<String> set = new HashSet<String>(); for(int i = 0; i < k; i++) { int x = nextInt() - 1; int y = nextInt() - 1; order[x][y] = 1; used[x][y] = true; q.add(new Integer[] {x, y}); set.add(x + "" + y); } while(!q.isEmpty()) { Integer[] v = q.remove(); for(int[] move : moves) { int x = v[0] + move[0]; int y = v[1] + move[1]; // if(set.contains(x + "" + y)) { // continue; // } if(correct(x, y, n, m) && !used[x][y]) { q.add(new Integer[] {x, y}); used[x][y] = true; order[x][y] = order[v[0]][v[1]] + 1; } } } int max = Integer.MIN_VALUE; int maxI = -1; int maxJ = -1; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(order[i][j] > max) { max = order[i][j]; maxI = i; maxJ = j; } } } maxI++; maxJ++; out.println(maxI + " " + maxJ); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public static void main(String[] args) { try { InputStream input = System.in; OutputStream output = System.out; br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); out = new PrintWriter(new PrintStream(new File("output.txt"))); solve(); out.close(); br.close(); } catch (Throwable t) { t.printStackTrace(); } } }
cubic
35_C. Fire Again
CODEFORCES
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class mainE { public static PrintWriter out = new PrintWriter(System.out); public static FastScanner enter = new FastScanner(System.in); public static void main(String[] args) throws IOException { int t=enter.nextInt(); for (int i = 0; i < t; i++) { solve(); } out.close(); } public static int[][] arr=new int[13][2010]; public static pair[] par= new pair[2010]; private static void solve() throws IOException{ int n=enter.nextInt(); int m=enter.nextInt(); for (int i = 0; i <n ; i++) { for (int j = 0; j <m ; j++) { arr[i][j]=enter.nextInt(); } } for (int i = 0; i <n ; i++) { for (int j = m; j <m+3 ; j++) { arr[i][j]=0; } } m=m+3; for (int i = 0; i <m ; i++) { int max=-1; for (int j = 0; j <n ; j++) { max=Math.max(arr[j][i], max); } par[i]=new pair(max,i); } Arrays.sort(par,0,m, pair::compareTo); int i0=par[0].st; int i1=par[1].st; int i2=par[2].st; int i3=par[3].st; int ans=-1; for (int i = 0; i <n ; i++) { for (int j = 0; j <n ; j++) { for (int k = 0; k <n ; k++) { for (int l = 0; l <n ; l++) { int first=Math.max(Math.max(arr[i][i0],arr[j][i1]), Math.max(arr[k][i2],arr[l][i3])); int second=Math.max(Math.max(arr[(i+1)%n][i0],arr[(j+1)%n][i1]), Math.max(arr[(k+1)%n][i2],arr[(l+1)%n][i3])); int third=Math.max(Math.max(arr[(i+2)%n][i0],arr[(j+2)%n][i1]), Math.max(arr[(k+2)%n][i2],arr[(l+2)%n][i3])); int fourth=Math.max(Math.max(arr[(i+3)%n][i0],arr[(j+3)%n][i1]), Math.max(arr[(k+3)%n][i2],arr[(l+3)%n][i3])); if(n==1) { second=0; third=0; fourth=0; } else if(n==2){ third=0; fourth=0; } else if(n==3){ fourth=0; } ans=Math.max(ans, first+second+fourth+third); } } } } System.out.println(ans); } static class pair implements Comparable<pair>{ int max,st; public pair(int max, int st) { this.max = max; this.st = st; } @Override public int compareTo(pair o) { return -Integer.compare(max, o.max); } } static class FastScanner { BufferedReader br; StringTokenizer stok; FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.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()); } char nextChar() throws IOException { return (char) (br.read()); } String nextLine() throws IOException { return br.readLine(); } } }
np
1209_E1. Rotate Columns (easy version)
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /* public class _908C { } */ public class _908C { public void solve() throws FileNotFoundException { InputStream inputStream = System.in; InputHelper in = new InputHelper(inputStream); // actual solution int n = in.readInteger(); double r = in.readInteger(); double[] x = new double[n]; for (int i = 0; i < n; i++) { x[i] = in.readInteger(); } double[] ans = new double[n]; ans[0] = r; for (int i = 1; i < n; i++) { double cans = r; for (int j = 0; j < i; j++) { double dis = Math.abs(x[j] - x[i]); if (dis <= 2 * r) { if (dis == 2 * r) { cans = Math.max(cans, ans[j]); continue; } else if (x[i] == x[j]) { cans = Math.max(cans, ans[j] + 2 * r); continue; } cans = Math.max(cans, ans[j] + Math.sqrt((4 * (r * r)) - dis * dis)); } } ans[i] = cans; } for (int i = 0; i < n; i++) { System.out.print(ans[i] + " "); } // end here } public static void main(String[] args) throws FileNotFoundException { (new _908C()).solve(); } class InputHelper { StringTokenizer tokenizer = null; private BufferedReader bufferedReader; public InputHelper(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader, 16384); } public String read() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = bufferedReader.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public Integer readInteger() { return Integer.parseInt(read()); } public Long readLong() { return Long.parseLong(read()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; public class A{ InputStream is; PrintWriter out; String INPUT = ""; public void solve(){ int n=ni(); char[] arr=new char[n]; for(int i=0;i<n;i++){ arr[i]=ns().charAt(0); } long mod=1000000007; long[][] memo=new long[n][n]; memo[0][0]=1L; int k=0; for(int i=1; i<n; i++){ if( (arr[i]=='f' && arr[i-1]=='s') || (arr[i]=='s' && arr[i-1]=='s') ){ long sum=0; for(int j=k; j>=0; j--){ sum=(sum+(memo[i-1][j]%mod))%mod; memo[i][j]=sum; } } else{ k+=1; for(int j=1; j<=k; j++){ memo[i][j] = memo[i-1][j-1] % mod; } } } //print(n, memo); long sum=0; for(int i=0;i<=k;i++){ sum=(sum+(memo[n-1][i])%mod)%mod; } out.println(sum); } void print(int n, long[][] memo){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ out.print(memo[i][j]+" "); } out.println(); } } void run(){ is = new DataInputStream(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 A().run();} //Fast I/O code is copied from uwi code. private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte(){ if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns(){ int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n){ char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m){ char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n){ int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni(){ int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl(){ long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } static int i(long x){return (int)Math.round(x);} static class Pair implements Comparable<Pair>{ long fs,sc; Pair(long a,long b){ fs=a;sc=b; } public int compareTo(Pair p){ if(this.fs>p.fs)return 1; else if(this.fs<p.fs)return -1; else{ return i(this.sc-p.sc); } //return i(this.sc-p.sc); } public String toString(){ return "("+fs+","+sc+")"; } } }
quadratic
909_C. Python Indentation
CODEFORCES
import java.io.*; import java.util.*; public class Main implements Runnable { public void _main() throws IOException { int n = nextInt(); int[] a = new int[n]; String s = next(); for (int i = 0; i < n; i++) a[i] = s.charAt(i) == 'H' ? 1 : 0; int res = 10 * n; for (int i = 0; i < n; i++) { int[] b = new int[n]; for (int j = 0; j < n; j++) b[j] = a[(i + j) % n]; res = Math.min(res, solve(b, 0)); res = Math.min(res, solve(b, 1)); } out.print(res); } private int solve(int[] a, int x) { int n = a.length; int j; for (j = n - 1; j >= 0; j--) if (a[j] == x) break; if (a[j] != x) return 0; int res = 0; for (int i = 0; i < j; i++) if (a[i] != x) { --j; while (j >= i && a[j] != x) --j; ++res; } return res; } private BufferedReader in; private PrintWriter out; private StringTokenizer st; private String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String rl = in.readLine(); if (rl == null) return null; st = new StringTokenizer(rl); } return st.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } private long nextLong() throws IOException { return Long.parseLong(next()); } private double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) { Locale.setDefault(Locale.UK); new Thread(new Main()).start(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); _main(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(202); } } }
linear
46_C. Hamsters and Tigers
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.Map; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int n; int[] bitCount; long neededSum; long[] sums; Map<Long, Integer> where; public void solve(int testNumber, FastScanner in, PrintWriter out) { n = in.nextInt(); int[][] a = new int[n][]; neededSum = 0; sums = new long[n]; for (int i = 0; i < n; i++) { int k = in.nextInt(); a[i] = new int[k]; for (int j = 0; j < k; j++) { a[i][j] = in.nextInt(); neededSum += a[i][j]; sums[i] += a[i][j]; } } if (neededSum % n != 0) { out.println("No"); return; } neededSum /= n; where = new HashMap<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < a[i].length; j++) { where.put((long) a[i][j], i); } } bitCount = new int[1 << n]; for (int i = 0; i < bitCount.length; i++) { bitCount[i] = Integer.bitCount(i); } Entry[][] cycleSol = new Entry[1 << n][]; List<Entry> sol = new ArrayList<>(); for (int i = 0; i < n; i++) { for (int x : a[i]) { search(i, i, x, x, 0, 0, sol, cycleSol); } } boolean[] can = new boolean[1 << n]; int[] via = new int[1 << n]; can[0] = true; for (int mask = 0; mask < 1 << n; mask++) { for (int submask = mask; submask > 0; submask = (submask - 1) & mask) { if (cycleSol[submask] != null && can[mask ^ submask]) { can[mask] = true; via[mask] = submask; } } } if (!can[(1 << n) - 1]) { out.println("No"); return; } int[][] ans = new int[n][2]; for (int mask = (1 << n) - 1; mask > 0; ) { int sm = via[mask]; mask ^= sm; for (Entry e : cycleSol[sm]) { ans[e.from][0] = e.what; ans[e.from][1] = e.to + 1; } } out.println("Yes"); for (int i = 0; i < n; i++) { out.println(ans[i][0] + " " + ans[i][1]); } } private void search(int start, int cur, long fromStart, long fromCur, int hasIn, int hasOut, List<Entry> sol, Entry[][] cycleSol) { for (int i = 0; i < n; i++) { if ((hasIn & (1 << i)) > 0) { continue; } if ((hasOut & (1 << cur)) > 0) { continue; } long fromI = sums[i] + fromCur - neededSum; Integer w = where.get(fromI); if (w == null || w != i) { continue; } sol.add(new Entry(cur, i, (int) fromCur)); int nHasIn = hasIn | (1 << i); int nHasOut = hasOut | (1 << cur); if (i == start && fromI == fromStart) { cycleSol[nHasOut] = sol.toArray(new Entry[0]); } search(start, i, fromStart, fromI, nHasIn, nHasOut, sol, cycleSol); sol.remove(sol.size() - 1); } } class Entry { int from; int to; int what; Entry(int from, int to, int what) { this.from = from; this.to = to; this.what = what; } public String toString() { return from + " " + to + " " + what; } } } 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 { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
np
1242_C. Sum Balance
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); long x = input.nextLong(); if(x==1||x==2){System.out.println(x); } else if(x%2==0&&x>2&&x%3!=0){ System.out.println((x)*(x-1)*(x-3)); }else if(x%2==0&&x%3==0){ System.out.println((x-1)*(x-2)*(x-3)); } else {System.out.println(x*(x-1)*(x-2));} } }
constant
235_A. LCM Challenge
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.readInt(); while (t-- > 0) { int[] a = new int[]{in.readInt(), in.readInt()}; Arrays.sort(a); int ans = 0; while (a[0] > 0) { int x = a[1] / a[0]; ans += x; a[1] -= a[0] * x; Arrays.sort(a); } out.println(ans); } } } 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); } } }
constant
267_A. Subtractions
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputScanner in = new InputScanner(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, InputScanner in, PrintWriter out) { int[] arr = in.readIntArr(); int n = arr[0]; int r = arr[1]; int[] x = in.readIntArr(); for (int i = 0; i < n; i++) { x[i] += 999; } double[] h = new double[n]; int dsk[] = new int[3000]; Arrays.fill(dsk, -1); for (int i = 0; i < r; i++) { dsk[x[0] + i] = 0; dsk[x[0] - i - 1] = 0; } int rs = 4 * r * r; h[0] = r; for (int i = 1; i < n; i++) { double ch = r; for (int j = 0; j < r; j++) { if (dsk[x[i] + j] != -1) { int ind = dsk[x[i] + j]; int diff = x[ind] - x[i]; int diffs = diff * diff; int hs = rs - diffs; ch = Math.max(ch, h[ind] + Math.sqrt(hs)); } if (dsk[x[i] - j - 1] != -1) { int ind = dsk[x[i] - j - 1]; int diff = x[ind] - x[i]; int diffs = diff * diff; int hs = rs - diffs; ch = Math.max(ch, h[ind] + Math.sqrt(hs)); } } if (x[i] + r < 3000) { if (dsk[x[i] + r] != -1) { ch = Math.max(ch, h[dsk[x[i] + r]]); } } if (x[i] - r - 1 > 0) { if (dsk[x[i] - r - 1] != -1) { ch = Math.max(ch, h[dsk[x[i] - r - 1]]); } } for (int j = 0; j < r; j++) { dsk[x[i] + j] = i; dsk[x[i] - j - 1] = i; } h[i] = ch; } for (int i = 0; i < n; i++) { out.print(h[i] + " "); } out.println(); } } static class InputScanner { BufferedReader br; public InputScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String readLine() { String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } public String[] readStringArr() { return readLine().split(" "); } public int[] readIntArr() { String[] str = readStringArr(); int arr[] = new int[str.length]; for (int i = 0; i < arr.length; i++) arr[i] = Integer.parseInt(str[i]); return arr; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class One { InputStreamReader inp = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(inp); boolean test = false; // String[] inData = { "4", "A", "B", "C", "D", "A-B 1:1", "A-C 2:2", // "A-D 1:0", "B-C 1:0", "B-D 0:3", "C-D 0:3" }; String[] inData = { "4","1 1 2" }; static int id = -1; public String readLine() throws IOException { id++; if (test) return inData[id]; else return in.readLine(); } public void solve() throws Exception { readLine(); String readLine = readLine(); String[] split = readLine.split(" "); List<Integer> ints = new ArrayList<Integer>(); for (int i = 0; i < split.length; i++) { ints.add(Integer.valueOf(split[i])); } Collections.sort(ints); Integer object = ints.get(0); for (int i = 0; i < split.length; i++) { if(ints.get(i).compareTo(object) > 0){ System.out.println(ints.get(i)); return; } } System.out.println("NO"); } public static void main(String[] args) throws Exception { new One().solve(); } }
nlogn
22_A. Second Order Statistics
CODEFORCES
import java.util.*; import java.io.*; import java.math.BigInteger; public class template { public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); Integer[] arr = new Integer[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); } Arrays.sort(arr); int ct = 0; boolean[] ar = new boolean[n]; for(int i=0;i<n;i++) { if(!ar[i]) { ar[i]=true; ct++; int x = arr[i]; for(int j=0;j<n;j++) { if(arr[j]%x==0) { ar[j]=true; } } } } pw.println(ct); pw.close(); } } @SuppressWarnings("all") class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(BufferedReader d) { br=d; } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } }
quadratic
1209_A. Paint the Numbers
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; public class Main { public Main() { super(); } public static void main(String... args) { Main main = new Main(); main.start(); } public void start() { Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int n = in.nextInt(); int t = in.nextInt(); House list[] = new House[n]; for (int i = 0; i < n; i++) { int x = in.nextInt(); int a = in.nextInt(); list[i] = new House(x, a); } Arrays.sort(list); int c = 2; for (int i = 1; i < n; i++) { float d = list[i].left - list[i - 1].right; if (d == t) c++; else if (d > t) c += 2; } System.out.println(c); } } class House implements Comparable<House> { public int x; public float left, right; public House(int x, int a) { this.x = x; float h = a / 2f; this.left = x - h; this.right = x + h; } public int compareTo(House h) { return this.x == h.x ? 0 : this.x < h.x ? -1 : 1; } }
nlogn
15_A. Cottage Village
CODEFORCES
import java.io.BufferedReader; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Collection; import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.ArrayList; import java.util.StringTokenizer; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author AlexFetisov */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { private double[][][] dp; private int n; private int k; private int[] loyalty; private int[] level; double[] P; private int a; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); k = in.nextInt(); a = in.nextInt(); level = new int[n]; loyalty = new int[n]; for (int i = 0; i < n; ++i) { level[i] = in.nextInt(); loyalty[i] = in.nextInt(); } P = new double[1 << n]; for (int mask = 0; mask < (1 << n); ++mask) { if (Integer.bitCount(mask) * 2 > n) { P[mask] = 1.; } else { double sumB = 0; for (int i = 0; i < n; ++i) { if (!BitUtils.checkBit(mask, i)) { sumB += level[i]; } } P[mask] = (double)a / (sumB + a); } } dp = new double[1 << n][n + 1][k + 1]; ArrayUtils.fill(dp, -1); newLoyalty = new int[n]; //double res = rec(0, 0, k, 0); brute(0, k); out.println(best); } int[] newLoyalty; double best = 0; void brute(int id, int leftCandies) { if (id == n) { double cur = calcCur(); if (best < cur) { best = cur; } return; } for (int candies = 0; candies <= leftCandies; ++candies) { newLoyalty[id] = loyalty[id] + candies * 10; if (newLoyalty[id] > 100) { break; } brute(id + 1, leftCandies - candies); } } private double calcCur() { double sum = 0; for (int mask = 0; mask < (1 << n); ++mask) { double p = getP(mask) * P[mask]; sum += p; } return sum; } private double getP(int mask) { double p = 1; for (int i = 0; i < n; ++i) { if (BitUtils.checkBit(mask, i)) { p *= (newLoyalty[i] * 1.) / 100.; } else { p *= (100. - newLoyalty[i]) / 100.; } } return p; } } class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine().trim(); } catch (IOException e) { return null; } } public String nextString() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(nextString()); } } class BitUtils { public static boolean checkBit(int mask, int bit) { return (mask & (1 << bit)) > 0; } } class ArrayUtils { public static void fill(double[][][] f, double value) { for (int i = 0; i < f.length; ++i) { for (int j = 0; j < f[i].length; ++j) { Arrays.fill(f[i][j], value); } } } }
np
105_B. Dark Assembly
CODEFORCES