src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
import java.util.*; public class global{ public static void main(String s[]){ Scanner sc = new Scanner(System.in); long n = sc.nextLong(); String st = String.valueOf(n); if(st.length()==1){ System.out.println(n); }else{ long val = 1; long prev=9; long total=9; long late=9; for(int i=2;i<=12;i++){ val*=10; total+=i*(val*9); if(n<=total){ long diff = n-late; long div = diff/i; long mod = diff%i; if(mod==0){ prev+=div; System.out.println((prev)%10); break; }else{ prev+=div+1; String fg = String.valueOf(prev); System.out.println(fg.charAt((int)mod-1)); break; } } prev+=(9*val); late=total; } } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.FileNotFoundException; import java.util.Scanner; public class P1177A { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(System.in); // Scanner in = new Scanner(new File("input.txt")); System.out.println(solve(in.nextLong())); } private static String solve(long k) { long digitCnt = 1; long nine = 9; while (k > nine * digitCnt) { k -= nine * digitCnt; nine *= 10; digitCnt++; } long num = nine / 9 - 1 + (k - 1) / digitCnt + 1; return String.valueOf(String.valueOf(num).charAt((int) ((k - 1) % digitCnt))); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class Solution { public static void main(String[] args) { long b=0;long p=1; Scanner s=new Scanner(System.in); long m=s.nextLong(); long x=1; do{ p=(m+b)/x; b=10*b+10; x++; }while(p/(long)Math.pow(10, x-1)!=0); rest : x--;b=b/10-1; b=x*p-b; b=m-b; b=x-b-1; p/=(long)Math.pow(10, b); p%=10; System.out.println(p); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc =new Scanner(System.in); long n=sc.nextLong(); long x=1; long ar=0; tag:for(long i=1;;i++) { ar+=9*i*x; if(ar>=n) { long d = n - (ar-9*i*x); long ans = x+d/i; long p=d%i; if(p==0) { p=i; ans--; } p=i-p; p++; long fns=0; //System.out.println(ans); while(p!=0) { fns=ans%10; ans/=10; p--; } System.out.println(fns); break tag; } x*=10; } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
// Change Of Plans BABY.... Change Of Plans // import java.io.*; import java.util.*; import java.util.Queue; import static java.lang.Math.*; public class digitSequence { static void MainSolution() { long k = nl() - 1; for (int i = 1; ; i++) { long temp=9L*i*fastPow(10,i-1); if(k<temp){ long x=k/i; long y=k%i; long ans=(x+fastPow(10,i-1))/fastPow(10,i-y-1); pl(ans%10); break; } k-=temp; } } static long fastPow(long b, long e) { if (e == 0) return 1; if ((e & 1) == 1) return b * fastPow(b, e >> 1) * fastPow(b, e >> 1); return fastPow(b, e >> 1) * fastPow(b, e >> 1); } /*----------------------------------------------------------------------------------------------------------------*/ //THE DON'T CARE ZONE BEGINS HERE...\\ static int mod9 = 1_000_000_007; static int n, m, l, k, t; static AwesomeInput input = new AwesomeInput(System.in); static PrintWriter pw = new PrintWriter(System.out, true); // The Awesome Input Code is a fast IO method // static class AwesomeInput { private InputStream letsDoIT; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private AwesomeInput(InputStream incoming) { this.letsDoIT = incoming; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = letsDoIT.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } private long ForLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private String ForString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } // functions to take input// static int ni() { return (int) input.ForLong(); } static String ns() { return input.ForString(); } static long nl() { return input.ForLong(); } static double nd() throws IOException { return Double.parseDouble(new BufferedReader(new InputStreamReader(System.in)).readLine()); } //functions to give output static void pl() { pw.println(); } static void p(Object o) { pw.print(o + " "); } static void pws(Object o) { pw.print(o + ""); } static void pl(Object o) { pw.println(o); } // Fast Sort is Radix Sort public static int[] fastSort(int[] f) { int n = f.length; int[] to = new int[n]; { int[] b = new int[65537]; for (int i = 0; i < n; i++) b[1 + (f[i] & 0xffff)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < n; i++) to[b[f[i] & 0xffff]++] = f[i]; int[] d = f; f = to; to = d; } { int[] b = new int[65537]; for (int i = 0; i < n; i++) b[1 + (f[i] >>> 16)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < n; i++) to[b[f[i] >>> 16]++] = f[i]; int[] d = f; f = to; to = d; } return f; } public static void main(String[] args) { //threading has been used to increase the stack size. new Thread(null, null, "Vengeance", 1 << 25) //the last parameter is stack size desired. { public void run() { try { double s = System.currentTimeMillis(); MainSolution(); //pl(("\nExecution Time : " + ((double) System.currentTimeMillis() - s) / 1000) + " s"); pw.flush(); pw.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
/** * @(#)DigitSequence.java * * * @author * @version 1.00 2019/6/1 */ import java.io.*; import java.util.*; public class DigitSequence { /** * Creates a new instance of <code>DigitSequence</code>. */ public DigitSequence() { } /** * @param args the command line arguments */ public static void main(String[] args) { Scanner in=new Scanner(System.in); long k=in.nextLong(); long[] end=new long[12]; end[0]=-1; for (int i=1; i<end.length; i++) { end[i]=(i*(long)(Math.pow(10,i))); end[i]-=(((long)(Math.pow(10,i))-1)/9); } //System.out.println(Arrays.toString(end)); int st=0;//st=1 {0,9}; st=2 {10, 189}; st=3 {190-2889}; st=4 {2890-38889} for (int i=1; i<end.length; i++) { if (k>=end[i-1]+1 && k<=end[i]) st=i; } //System.out.println("st " + st); long diff=k-end[st-1]; long mod=((diff+st-1)%st); //System.out.println(mod); long digit=-1; int addOn=0; if (mod==0) addOn=1; if (mod==st-1) addOn=-1; digit=(diff/(st*(long)(Math.pow(10,st-1-mod)))); digit+=addOn; digit%=10; System.out.println(digit); //98888888889 //98888888879 //1088888888889 //1088888888878 } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class A1177 { public static long exponential(long a, long b){ long result = 1; for(int i=0;i<b;i++){ result *= a; } return result; } public static void main(String args[]){ Scanner scanner = new Scanner(System.in); long k = scanner.nextLong(); //int k =21; long sum = 0; long i=1; while(true){ long interval = 9 * exponential(10,i-1) * i; if(sum + interval >= k){ break; } else { i++; sum += interval; } } long t = k-sum; long targetNumber = exponential(10, i-1) + (t-1)/i; String s = "" + targetNumber; int hedef = (int)((t-1)%i); System.out.println(s.charAt(hedef)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class P1177A { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { long k = sc.nextLong(); int pow = 1; while ((long) ((Math.pow(10, pow) - Math.pow(10, pow - 1)) * pow) < k) { k -= (long) ((Math.pow(10, pow) - Math.pow(10, pow - 1)) * pow); pow++; } // System.out.println(k + " " + pow); k--; long n = (long) Math.pow(10, pow - 1) + k / pow; k %= pow; // System.out.println(k + " " + n); System.out.println(String.valueOf(n).charAt((int) k)); } catch (Exception e) { e.printStackTrace(); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { FastScanner sc=new FastScanner(); long K = sc.nextLong(); long nums = 9; int digits = 1; while (K > nums*digits) { K -= nums*digits; nums *= 10; digits++; } long removal = (K-1)/digits; int pos = (int)((K-1)%digits); long base = (long)Math.pow(10,digits-1); String num = Long.toString(base+removal); System.out.println(num.charAt(pos)); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { static class Task { int NN = 1000001; int MOD = 1000000007; int INF = 2000000000; long INFINITY = 2000000000000000000L; public void solve(InputReader in, PrintWriter out) { long k = in.nextLong(); for(long mul = 1,d=1;;mul*=10,++d) { if(k > 9*mul*d) { k -= 9*mul*d; } else { for(long i=1;i<=9;++i) { if(k > mul*d) { k -= mul*d; } else { --k; long num = k / d; k %= d; String str = String.valueOf(num); while(str.length() < d - 1) { str = "0" + str; } str = String.valueOf(i) + str; out.println(str.charAt((int) k));return; } } } } } } static void prepareIO(boolean isFileIO) { //long t1 = System.currentTimeMillis(); Task solver = new Task(); // Standard IO if(!isFileIO) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver.solve(in, out); //out.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0); out.close(); } // File IO else { String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in"; String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out"; InputReader fin = new InputReader(IPfilePath); PrintWriter fout = null; try { fout = new PrintWriter(new File(OPfilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } solver.solve(fin, fout); //fout.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0); fout.close(); } } public static void main(String[] args) { prepareIO(false); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public InputReader(String filePath) { File file = new File(filePath); try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class Main { static class LeftOver { int a; long b; long c; LeftOver(int a, long b, long c) { this.a = a; this.b = b; this.c = c; } } private static long pow(long base, long coe) { if (coe == 0) return 1; if (coe == 1) return base; long res = pow(base, coe / 2); if (coe % 2 == 0) { return res * res; } else { return res * res * base; } } private static void getLen(long n) { long tmp = 0; int cnt = 0; while(tmp < n) { ++cnt; tmp += cnt * 9 * pow(10, cnt - 1); } if (tmp == n) System.out.println("9"); else { tmp -= cnt * 9 * pow(10, cnt - 1); long ans = (n - tmp - 1) / cnt + pow(10, cnt - 1); System.out.println(String.valueOf(ans).charAt((int) ((n - tmp - 1) % cnt))); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); getLen(n); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class BDigitSequence { public static void main(String[] args) { Scanner scan = new Scanner(System.in); long k = scan.nextLong(); long digits = 1; long counter = 9L; while(k > counter * digits) { k -= counter * digits; counter *= 10; digits++; } long num = (long)(Math.ceil((double)k/digits)); String s = String.valueOf((long)Math.pow(10,digits-1) - 1 + num ); System.out.println(s.charAt((int)((k+digits-1)%digits))); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.util.*; public class digits { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long k = Long.parseLong(br.readLine()); long temp = 9 * (int)Math.pow(10,0); int count = 0; long initial = 0; while(k > temp) { count++; initial = temp; temp += 9 * (long)Math.pow(10,count)*(count+1); } long index = (k-initial-1)%(count+1); long num = (long)Math.pow(10,count) + (k-initial-1)/(count+1); System.out.println((num+"").charAt((int)index)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); long k = in.nextLong(); long t = 1; long l = 1; if(k <= 9) { System.out.print(k); System.exit(0); } long x = 9; while(true) { ++l; t *= 10; x += 9 * l * t; if(x >= k) { break; } } if(x == k) { System.out.print(9); System.exit(0); } x -= 9 * l * t; long a = (k - x) / l; if((k - x) % l == 0) { x = t + a - 1; System.out.print(x % 10); } else { k -= (x + a * l); x = t + a; String s = Long.toString(x); System.out.print(s.charAt((int)k - 1)); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.math.BigDecimal; import java.math.MathContext; import java.util.*; public class Main { static int len(long n) { int res = 0; while (n > 0) { n /= 10; res++; } return res; } static long big(int len) { long p = 1; while (len-- > 0) p *= 10; return p - 1; } static long small(int len) { return big(len - 1) + 1; } static long cnt(long n) { int len = len(n); long cnt = 0; for (int l = 1; l < len; l++) cnt += 1l * l * (big(l) - small(l) + 1); cnt += 1l * len * (n - small(len)); return cnt; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); long k = sc.nextLong(); if (k == 1) { System.out.println(1); return; } long lo = 1, hi = k, res = 1; while(lo <= hi) { long mid = lo + hi >> 1L; if(cnt(mid) < k) { res = mid; lo = mid + 1; } else { hi = mid - 1; } } ArrayList<Integer> digits = new ArrayList<>(); long tmp = res; while (tmp > 0) { digits.add((int)(tmp % 10)); tmp /= 10; } // System.err.println("RES " + res); // System.err.println("DIGITS " + digits); // System.err.println("Cnt Res " + cnt(res)); Collections.reverse(digits); out.println(digits.get((int)(k - cnt(res) - 1))); out.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class DigitsSequence2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long index = scanner.nextLong(); solution1(index); } static void solution1(Long index){ int i = 1; // group number long len = 9; // the max length long max = 9; // the max integer while(len < index){ long tmp = 9 * (long) Math.pow(10, i); i++; len += i * tmp; max += tmp; } long diff = len - index; // the digit number between index and len long laterCount = diff / i; // the number after index int remainder = (int) (diff % i); long current = max - laterCount; // the number of the index int k = i - 1 - remainder; System.out.println(String.valueOf(current).charAt(k)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; public class _v14 { public static void main(String args[]){ PrintWriter out = new PrintWriter(System.out); Reader in = new Reader(); long k = in.nextLong(); if(k<10){ System.out.println(k); return; } long sum = 0; long cur = 9; long prev = 0; int count = 1; while(k>cur){ k= k - cur; sum = sum + cur/count; prev = cur; cur = 9*(count+1)*(long)Math.pow(10,count); count++; } long num = k/(count); sum = sum + num; if(k%count == 0){ System.out.println(sum%10); } else{ sum++; k = k%(count); String str = String.valueOf(sum); System.out.println(str.charAt((int)k-1)); } out.flush(); out.close(); } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.util.*; import java.util.Queue; import java.util.LinkedList; import java.util.Stack; public class Main { @SuppressWarnings("unchecked") public static void main(String args[])throws IOException { Reader ob=new Reader(); Writer out=new Writer(System.out); Random oo=new Random(); long k=ob.nL(),ans=0,p=9,num=0; for(int i=1;i<18;i++) { if(num+i*p<k) { num+=i*p;p*=10; ans=0; for(int j=0;j<i;j++) ans=9+ans*10; } else { long left=k-num; long r=left/i; left-=r*i; ans+=r; if(left>0) { String s=Long.toString(ans+1); out.pln(s.charAt((int)left-1)); } else { String s=Long.toString(ans); out.pln(s.charAt(i-1-(int)left)); } break; } } out.flush(); } static void sort(int a[]) { RA(a); Arrays.sort(a); } public static Pairs[] RA(Pairs [] array){ Random rgen = new Random(); // Random number generator for (int i=0; i<array.length; i++) { int randomPosition = rgen.nextInt(array.length); Pairs temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } public static int[] RA(int [] array){ Random rgen = new Random(); // Random number generator for (int i=0; i<array.length; i++) { int randomPosition = rgen.nextInt(array.length); int temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } static void sort(long a[]) { RA(a); Arrays.sort(a); } public static long[] RA(long [] array){ Random rgen = new Random(); // Random number generator for (int i=0; i<array.length; i++) { int randomPosition = rgen.nextInt(array.length); long temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } static void sort(String a[]) { RA(a); Arrays.sort(a); } public static String[] RA(String [] array){ Random rgen = new Random(); // Random number generator for (int i=0; i<array.length; i++) { int randomPosition = rgen.nextInt(array.length); String temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } static long inverse(long x, long p) { return pow(x, p - 2, p); } static boolean isPrime(long n) { long h=(long)Math.sqrt(n); for(long i=2;i<=h;i++) if(n%i==0) return false; return true&&n!=1; } static long gcd(long a,long b) { if(a<b) return gcd(b,a); else if(b==0) return a; else return gcd(b,a%b); } static long pow(long a,long b,long mod){ if(b == 0) return 1; long t = pow(a,b>>1,mod); t = (t * t) % mod; if((b & 1) == 1) t = (t * a); if(t >= mod) t %= mod; return t; } static long pow(long a,long b){ if(b == 0) return 1; long t = pow(a,b>>1); t = (t * t); if((b & 1) == 1) t = (t * a); return t; } static void seive(int n,int prime[])//1 for prime -1 for not prime { for(int i=2;i<=n;i++) if(prime[i]==0) { prime[i]=1; for(int j=2;j*i<=n;j++) prime[j*i]=-1; } } static int max(int ...a) { int m=a[0]; for(int i=0;i<a.length;i++) m=Math.max(m,a[i]); return m; } static long max(long ...a) { long m=a[0]; for(int i=0;i<a.length;i++) m=Math.max(m,a[i]); return m; } static int min(int ...a) { int m=a[0]; for(int i=0;i<a.length;i++) m=Math.min(m,a[i]); return m; } static long min(long ...a) { long m=a[0]; for(int i=0;i<a.length;i++) m=Math.min(m,a[i]); return m; } static class Pair<T1,T2> { T1 x;T2 y; Pair(T1 xx,T2 yy) { x=xx; y=yy; } } static class Writer { private final PrintWriter p; Writer(OutputStream o) { p = new PrintWriter(new BufferedWriter(new OutputStreamWriter(o))); } void p(Object... o1) { for (Object o11 : o1) { p.print(o11 + "" ); } } <T>void pa(T a[]) { for(T i:a) System.out.print(i+" "); System.out.println(); } void p(String s) { p.print(s); } void pln(Object... o1) { p(o1); p.println(); } void flush() { p.flush(); } void close() { p.close(); } } static class Reader { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; int flag=0; FileReader file; Reader() { } Reader(String x)throws IOException { flag=1; file=new FileReader(x); } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nl() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String n() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nL() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nI() { 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 int[] NIA(int n) //nextINtArray { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nI(); } return arr; } public int[] NIA1(int n) //nextINtArray { int[] arr = new int[n+1]; for (int i = 1; i <=n; i++) { arr[i] = nI(); } return arr; } public long[] NLA(int n) //nextLongArray { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nL(); } return arr; } public long[] NLA1(int n) //nextLongArray { long[] arr = new long[n+1]; for (int i = 1; i <=n; i++) { arr[i] = nL(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static class DSU { int a[],size[],c=1,m; HashMap<String,Integer> hm=new HashMap<String,Integer>(); DSU(int n) { a=new int[n+1]; m=n; size=new int[n+1]; for(int i=1;i<=n;i++) { a[i]=i; size[i]=1; } } void add(String x,int i) { hm.put(x,i); } int find(int n) { while(a[n]!=n) { a[n]=a[a[n]]; n=a[n]; } return n; } int[] eval() { int y[]=new int[m+1]; for(int i=1;i<=m;i++) y[find(i)]++; return y; } void union(int a1,int b) { int x=find(a1); int y=find(b); if(size[x]>size[y]) { a[y]=x; size[x]+=size[y]; } else { a[x]=y; size[y]+=size[x]; } } //System.out.println(Arrays.toString(a)); } class Segment { int sum[]; void build(int a[],int v,int l,int r) { if(l==r) sum[v]=a[l]; else { int m=(l+r)/2; build(a,v*2,l,m); build(a,2*v+1,m+1,r); sum[v]=sum[v*2]+sum[2*v+1]; } } void update(int a[],int l,int r,int x,int v,int y) { if(l==r&&r==y) sum[v]+=x; else if(l>y||y>r) return; else { int m=(l+r)/2; update(a,l,m,x,2*v,y); update(a,m+1,r,x,2*v+1,y); sum[v]=sum[2*v]+sum[2*v+1]; } } int query(int v,int l,int r,int x,int y) { if(x>r||y<l) return 0; else if(x<=l&&r<=y) return sum[v]; else { int m=(l+r)/2; return query(2*v,l,m,x,y)+query(2*v+1,m+1,r,x,y); } } } static class Trie { Trie child[]=new Trie[26]; int count=0; } /* void insert(String a) { Trie tmp=root; for(int i=0;i<a.length();i++) { int v=a.charAt(i)-'a'; if(tmp.child[v]==null) { tmp.child[v]=new Trie(); } tmp=tmp.child[v]; } if(tmp.count==0) r++; tmp.count=1; }*/ } class Pairs implements Comparable<Pairs> { int x,y;String z; Pairs(int a,int b) { x=a;y=b; } @Override public int compareTo(Pairs a) { if(a.x>this.x||(a.x==this.x&&a.y<this.y)||(a.x==this.x&&a.y==this.y&&(a.z).equals("BhayanakMaut"))) return 1; else return -1; } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; import static java.lang.Long.bitCount; public class Main { public static void main(String[] args) { FastScanner in = new FastScanner(); long []a = new long[16]; a[0] = 0; for(int i=1; i<16; ++i) a[i] = a[i-1]+((9*(long)Math.pow(10, i-1))*i); long N = in.nextLong(); int pos = 0; for(int i=0; i<16; ++i){ if(N<=a[i]){ pos = i; break; } } if(pos==1){ System.out.println(N); System.exit(0); } long prev = a[pos-1]; long curr = N; long rem = curr - prev; long ans = 0; for(int i=1; i<pos; ++i){ ans = ans*10 + 9; } long g = (rem+(pos-1))/pos; long take = (rem+(pos-1))%pos; long number = ans + g; String str = Long.toString(number); System.out.println(str.charAt((int)take)); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class DigitsSequence { public static void main(String[] args){ Scanner sc=new Scanner(System.in); long k,c,n,d; c=1; d=9; n=1; k= sc.nextLong(); while(k>(c*d)) { k-=(c*d); n*=10; d*=10; c++; } n+=(k-1)/c; char[] num = String.valueOf(n).toCharArray(); System.out.println(num[(int)((k-1)%c)]); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
//package codeforces; import java.util.*; import java.math.BigInteger; public class test_round_B { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); BigInteger k=sc.nextBigInteger(); BigInteger i=new BigInteger("0"); int d=0; BigInteger a=new BigInteger("0"); while(i.compareTo(k)!=1) { if(i.compareTo(k)==0) { break; } else { d++; BigInteger temp=new BigInteger("0"); for(int j=0;j<d;j++) { temp=temp.multiply(new BigInteger("10")).add(new BigInteger("9")); } i=i.add(new BigInteger(Integer.toString(d)).multiply(temp.subtract(a))); //i=i+d*(temp-a); a=temp; } } //System.out.println(a) ; BigInteger b=a.divide(new BigInteger("10")); BigInteger t=b; BigInteger l=t; //System.out.println(b); int dig=0; if(b.equals(new BigInteger("0"))) { dig=0; } else { while(b.compareTo(new BigInteger("0"))==1) { dig++; b=b.divide(new BigInteger("10")); } } //System.out.println(dig); int flag=dig+1; BigInteger num=new BigInteger("0"); b=t; while(b.compareTo(new BigInteger("0"))==1) { //System.out.println("sun"); BigInteger rev=b.divide(new BigInteger("10")); num=num.add(new BigInteger(Integer.toString(dig)).multiply(b.subtract(rev))); //num+=(b-rev)*dig; b=b.divide(new BigInteger("10")); dig--; } //System.out.println(num); //System.out.println(t); BigInteger net=k.subtract(num); BigInteger div=net.divide(new BigInteger(Integer.toString(flag))); int q; if(net.mod(new BigInteger(Integer.toString(flag))).equals(new BigInteger("0"))) { //System.out.println("s"); //System.out.println(); q=0; t=t.add(div); System.out.println(t.mod(new BigInteger("10"))); } else { //System.out.println(div); //System.out.println(flag); //System.out.println(net); BigInteger r=div.multiply(new BigInteger(Integer.toString(flag))); r=net.subtract(r); //q=Integer.toString(net%flag).length(); //System.out.println(q); //System.out.println(t); //System.out.println(pig); //System.out.println(w); t=t.add(div.add(new BigInteger("1"))); //System.out.println(r); l=t; int pig=0; while(t.compareTo(new BigInteger("0"))==1) { pig++; t=t.divide(new BigInteger("10")); } //System.out.println(pig); BigInteger p=new BigInteger(Integer.toString(pig)); BigInteger rem=p.subtract(r); //System.out.println(l); while(rem.compareTo(new BigInteger("0"))==1) { l=l.divide(new BigInteger("10")); rem=rem.subtract(new BigInteger("1")); } //System.out.println(l); //System.out.println(r); //System.out.println(c); //int f=t/w; //System.out.println(f); System.out.println(l.mod(new BigInteger("10"))); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class ABC { public static void main(String[] args){ Scanner sc=new Scanner(System.in); long k,c,n,d; c=1; d=9; n=1; k= sc.nextLong(); while(k>(c*d)) { k-=(c*d); n*=10; d*=10; c++; } n+=(k-1)/c; char[] num = String.valueOf(n).toCharArray(); System.out.println(num[(int)((k-1)%c)]); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; import java.io.*; import java.util.stream.Collectors; public class P1177A { public static void main(String[] args) throws Exception { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); long n = Long.parseLong(r.readLine()); if (n < 10) { System.out.print(n); return; } int len = 1; long edge = 10; long prev = 0; long prepow = 0; while (edge - 1 < n) { prepow = (long)Math.pow(10, len); long pow = prepow * 10; prev = edge; edge = edge + (pow - prepow) * (len + 1); len += 1; } long b = n - prev; long c = b / len; int rem = (int)(b % len); String s = Long.toString(prepow + c).charAt(rem) + ""; System.out.print(s); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class DigitSeq { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc = new FastReader(); OutputStream outputstream = System.out; PrintWriter out = new PrintWriter(outputstream); long n = sc.nextLong(); long[] arr = new long[14]; for(int i = 1; i <= 13; i++){ arr[i] = (long)Math.pow(10, i)-(long)Math.pow(10, i-1); } long total = 0; for(int i = 1; i <= 13; i++){ if(total+(long)i*arr[i]>=n){ long ans = n-total; long rest = ans; if(ans%i!=0){ ans /= i; ans++; } else { ans /= i; } ans += (long)Math.pow(10, i-1)-1; String str = Long.toString(ans); int ind = (rest%i==0) ? i-1 : (int)(rest%i)-1; out.println(str.charAt(ind)); break; } total = total+(long)i*arr[i]; } out.close(); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class DD { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); long k=Long.parseLong(br.readLine()); long ans=9*(int)Math.pow(10,0); int c=0; long start=0; while(k>ans) { c++; start=ans; ans+=9*(long)Math.pow(10,c)*(c+1); } long ms=(k-start-1)%(c+1); long a=(long)Math.pow(10,c)+(k-start-1)/(c+1); System.out.println((a+"").charAt((int)ms)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; import java.io.*; public class DigitSequence { public static PrintWriter out; /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer token = new StringTokenizer(""); String temp[] = br.readLine().split(" "); long pos = Long.parseLong(temp[0]); out = new PrintWriter(new BufferedOutputStream(System.out)); if (pos<10) { out.println(pos); } else { out.println(findDigitSequence(pos)); } out.close(); } private static char findDigitSequence(long pos) { //long result = 0; long min = 0; long max = 9; long dig = 1; while (pos>max) { dig++; min = max+1; max=(long) (max+9*Math.pow(10, dig-1)*dig); } pos = pos-min; long num = (long) (pos/dig+Math.pow(10, dig-1)); String st = String.valueOf(num); if (dig==1) { return st.charAt(0); } char result = st.charAt((int) (pos%dig)); return result; } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.util.*; public class digits { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long k = Long.parseLong(br.readLine()); long temp = 9 * (int)Math.pow(10,0); int count = 0; long initial = 0; while(k > temp) { count++; initial = temp; temp += 9 * (long)Math.pow(10,count)*(count+1); } long index = (k-initial-1)%(count+1); long num = (long)Math.pow(10,count) + (k-initial-1)/(count+1); System.out.println((num+"").charAt((int)index)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; import java.lang.management.*; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.lang.Math.max; import static java.lang.Math.sqrt; import static java.lang.Integer.signum; @SuppressWarnings("unchecked") public class P1177B { public void run() throws Exception { for (long k = nextLong() - 1, d = 1, dc = 9, sv = 1; true; k -= dc, d++, sv *= 10, dc = (sv * 10 - sv) * d) { if (k <= dc) { println(Long.toString(sv + k / d).charAt((int)(k % d))); break; } } } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P1177B().run(); br.close(); pw.close(); System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]"); long gct = 0, gcc = 0; for (GarbageCollectorMXBean garbageCollectorMXBean : ManagementFactory.getGarbageCollectorMXBeans()) { gct += garbageCollectorMXBean.getCollectionTime(); gcc += garbageCollectorMXBean.getCollectionCount(); } System.err.println("[GC time : " + gct + " ms, count = " + gcc + "]"); } static long startTime = System.currentTimeMillis(); static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void printsp(int [] a) { for (int i = 0, n = a.length; i < n; print(a[i] + " "), i++); } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } int gcd(int a, int b) { if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a); a = Math.abs(a); b = Math.abs(b); int az = Integer.numberOfTrailingZeros(a), bz = Integer.numberOfTrailingZeros(b); a >>>= az; b >>>= bz; while (a != b) { if (a > b) { a -= b; a >>>= Integer.numberOfTrailingZeros(a); } else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); } } return (a << Math.min(az, bz)); } long gcd(long a, long b) { if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a); a = Math.abs(a); b = Math.abs(b); int az = Long.numberOfTrailingZeros(a), bz = Long.numberOfTrailingZeros(b); a >>>= az; b >>>= bz; while (a != b) { if (a > b) { a -= b; a >>>= Long.numberOfTrailingZeros(a); } else { b -= a; b >>>= Long.numberOfTrailingZeros(b); } } return (a << Math.min(az, bz)); } void shuffle(int [] a) { // RANDOM shuffle Random r = new Random(); for (int i = a.length - 1, j, t; i >= 0; j = r.nextInt(a.length), t = a[i], a[i] = a[j], a[j] = t, i--); } void shuffle(int [] a, int m) { // QUICK shuffle for (int i = 0, n = a.length, j = m % n, t; i < n; t = a[i], a[i] = a[j], a[j] = t, i++, j = (i * m) % n); } void shuffle(long [] a) { Random r = new Random(); for (int i = a.length - 1; i >= 0; i--) { int j = r.nextInt(a.length); long t = a[i]; a[i] = a[j]; a[j] = t; } } void shuffle(Object [] a) { Random r = new Random(); for (int i = a.length - 1; i >= 0; i--) { int j = r.nextInt(a.length); Object t = a[i]; a[i] = a[j]; a[j] = t; } } int [] sort(int [] a) { final int SHIFT = 16, MASK = (1 << SHIFT) - 1, SIZE = (1 << SHIFT) + 1; int n = a.length, ta [] = new int [n], ai [] = new int [SIZE]; for (int i = 0; i < n; ai[(a[i] & MASK) + 1]++, i++); for (int i = 1; i < SIZE; ai[i] += ai[i - 1], i++); for (int i = 0; i < n; ta[ai[a[i] & MASK]++] = a[i], i++); int [] t = a; a = ta; ta = t; ai = new int [SIZE]; for (int i = 0; i < n; ai[(a[i] >> SHIFT) + 1]++, i++); for (int i = 1; i < SIZE; ai[i] += ai[i - 1], i++); for (int i = 0; i < n; ta[ai[a[i] >> SHIFT]++] = a[i], i++); return ta; } void flush() { pw.flush(); } void pause() { flush(); System.console().readLine(); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class Cses { public static void main(String[] args) { FastReader sc = new FastReader(); // int t = sc.nextInt(); // while (t-- > 0) { long n = sc.nextLong(); if (n < 10) { System.out.println(n); return; } else { long sum = 0; long cur = 9; long prev = 0; int count = 1; while (n > cur) { n -= cur ; sum += cur / count; prev = cur; cur = 9 * (count + 1) * (long)Math.pow(10, count); count ++; } sum = sum + (n / count); if (n % count == 0) { System.out.println(sum % 10); } else { sum++; n = n % count; String s = String.valueOf(sum); System.out.println(s.charAt((int)n - 1)); } // } } } public static boolean isSafe(int[][] chess, int row, int col) { for (int i = row - 1, j = col; i >= 0; i--) { if (chess[i][j] == 1) { return false; } } for (int i = col - 1, j = row - 1; i >= 0 && j >= 0; i--, j--) { if (chess[i][j] == 1) { return false; } } for (int i = col - 1, j = row + 1; i >= 0 && j < chess.length; i--, j++) { if (chess[i][j] == 1) { return false; } } return true; } static String swap(String str, int i, int j) { char temp; char[] ch = str.toCharArray(); temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return String.valueOf(ch); } static String rev(String str) { StringBuilder sb = new StringBuilder(str); for (int i = str.length() - 1; i >= 0; i--) { sb.append(str.charAt(i)); } String s = sb.toString(); return s; } static int swap(int a, int b) { return a; } static class pair { int first; int second; public pair(int first, int second) { this.first = first; this.second = second; } } public static long power(long a, long b) { long res = 1; while (b > 0) { if ((b & 1) != 0) { res = (res * a) % 1000000007; } a = (a * a) % 1000000007; b = b >> 1; } return res; } public static int pow(int a, int b) { int res = 1; while (b > 0) { if ((b & 1) != 0) { res = (res * a); } a = a * a; b = b >> 1; } return res; } public static String catoString(char[] ch) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < ch.length; i++) { sb.append(ch[i]); } return sb.toString(); } public static boolean isPrime(long n) { if (n < 2) return false; for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } 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) { long d = gcd(a, b); return (a * b) / d; } static boolean isPowerOfTwo(long n) { return (long)(Math.ceil(Math.log(n) / Math.log(2))) == (long)(Math.floor(Math.log(n) / Math.log(2))); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = " "; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class CodeForces { class Pair<K, V> { K first; V second; public Pair(K k, V v) { first = k; second = v; } } private boolean contain(int set, int i) { return (set & (1<<i)) > 0; } private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a%b); } private long pow(long a, long p) { if (p == 0) return 1; long b = pow(a, p/2); b = b * b; if (p % 2 == 1) b *= a; return b % mod; } private static boolean isSame(double a, double b) { return Math.abs(a - b) < 1e-10; } private static void swapBoolean(boolean[] p, int i, int j) { boolean tmp = p[i]; p[i] = p[j]; p[j] = tmp; } private static void swap(int[] p, int i, int j) { int tmp = p[i]; p[i] = p[j]; p[j] = tmp; } private static int countOne(int a) { if (a == 0) return 0; return countOne(a & (a-1)) + 1; } private static int sdiv(int a, int b) { return (a +b -1) / b; } private int[] retran(int index) { int[] res = new int[2]; res[0] = index / M; res[1] = index % M; return res; } private int tran(int x, int y) { return x * M + y; } private boolean inTable(int x, int y) { return x>=0 && x< N && y >= 0 && y < M; } int N; int R; int[][] C = new int[10][10]; int M; int mod = 1_000_000_007; long IMPO; int ans; int[] dx = new int[]{1,0, -1, 0}; int[] dy = new int[]{0, -1, 0, 1}; Map<String, Boolean> dp = new HashMap<>(); class Edge { int u; int v; int start; int duration; public Edge(int u, int v, int l, int d) { this.u = u; this.v = v; this.start = l; this.duration = d; } } List<List<Integer>> graph = new ArrayList<>(); List<Edge> edges = new ArrayList<>(); int[] parent; boolean[] visited; public void run(Scanner scanner) throws IOException { long k = scanner.nextLong(); int len = 1; long number = 9; for (int i = 0; true; i++) { if (len * number < k) { k -= len * number; len ++; number *= 10; } else { break; } } number /= 9; StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 9; i++) { if (len * number < k) { k -= len * number; } else { sb.append(i); break; } } for (int i = 1; i < len; i++) { number /= 10; for (int j = 0; j <= 9; j++) { if (len * number < k) { k -= len * number; } else { sb.append(j); break; } } } System.out.println(sb.charAt((int) k - 1)); } public static void main(String[] args) throws NumberFormatException, IOException { // String fileName = "C://Users/user/eclipse-workspace/algo/example.txt"; // String outFile = "C://Users/user/eclipse-workspace/algo/example-out.txt"; // String fileName = "C://Users/user/eclipse-workspace/algo/A-small-practice.in"; // String outFile = "C://Users/user/eclipse-workspace/algo/A-small-out.txt"; // String fileName = "C://Users/user/eclipse-workspace/algo/A-large-practice.in"; // String outFile = "C://Users/user/eclipse-workspace/algo/A-large-out.txt"; // String fileName = "/Users/mobike/IdeaProjects/algo/B-small-practice.in"; // String outFile = "/Users/mobike/IdeaProjects/algo/B-small-out.txt"; // String fileName = "/Users/mobike/IdeaProjects/algo/B-large-practice.in"; // String outFile = "/Users/mobike/IdeaProjects/algo/B-large-out.txt"; // String fileName = "C://Users/user/eclipse-workspace/algo/C-small-practice.in"; // String outFile = "C://Users/user/eclipse-workspace/algo/C-small-out.txt"; // String fileName = "C://Users/user/eclipse-workspace/algo/D-small-practice.in"; // String outFile = "C://Users/user/eclipse-workspace/algo/D-small-out.txt"; // String fileName = "C://Users/user/eclipse-workspace/algo/D-large-practice.in"; // String outFile = "C://Users/user/eclipse-workspace/algo/D-large-out.txt"; Scanner scanner = new Scanner(System.in); // int T = scanner.nextInt(); // for (int i = 1; i <= T; i++) { CodeForces jam = new CodeForces(); jam.run(scanner); // } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStreamReader; public class B1177 { public static void main(String[] args) throws Exception { // BufferedReader br = new BufferedReader(new FileReader("F:/books/input.txt")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Long n = Long.parseLong(br.readLine()); long[] p = new long[15]; int i; p[0]=1; for(i=1;i<15;p[i]=p[i-1]*10,i++); for(i=1;i*p[i-1]*9L<n;n-=i*p[i-1]*9L,i++); n--; int v = (int) (n%i); n/=i; n+=p[i-1]; String s = n.toString(); System.out.println(s.charAt(v)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static final int MAX_N = 1000010; static final int INF = 0x3f3f3f3f; static final int mod = 1000000007; public static void main(String[] args) throws IOException { initReader(System.in); // int T = nextInt(); // for (int i = 1; i <= T; i++) solve(); pw.flush(); } /*******************************************************************************************************************************/ public static void solve() throws IOException { while (hasNext()) { long n = nextLong() - 1; long k = 1, x = 9; while (n - k * x >= 0) { n -= k * x; k += 1; x *= 10; } if (n == 0) pw.println(1); else { long num = x / 9 + n / k; String s = String.valueOf(num); pw.println(s.charAt((int) (n % k))); } } } /*******************************************************************************************************************************/ static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter pw; public static void initReader(InputStream input) throws IOException { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); // reader = new BufferedReader(new FileReader("ate.in")); // tokenizer = new StringTokenizer(""); // printWriter = new PrintWriter(new BufferedWriter(new FileWriter("ate.out"))); } public static boolean hasNext() { try { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (Exception e) { return false; } return true; } public static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static String nextLine() { try { return reader.readLine(); } catch (Exception e) { return null; } } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static char nextChar() throws IOException { return next().charAt(0); } static class Pair { char first; boolean second; public Pair(char first, boolean second) { // TODO Auto-generated constructor stub this.first = first; this.second = second; } @Override public String toString() { // TODO Auto-generated method stub return "(" + this.first + ", " + this.second + ")"; } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class Main{ final int mod = 1000000007; final int maxn = -1; final double eps = 1e-9; long digits(long n){ if(n == 0) return 0; int p = (int)Math.log10(n); return (p + 1) * (n - (long)Math.pow(10, p) + 1) + digits((long)Math.pow(10, p) - 1); } void solve(){ // freopen("in"); String s = ""; long k = nextLong(); long i = 1; long j = k; while(i < j){ long m = (i + j) / 2; if(digits(m) < k){ i = m + 1; } else{ j = m; } } if(digits(i) >= k) --i; printf("%c\n", String.valueOf(i + 1).charAt((int)(k - digits(i) - 1))); } final double pi = Math.acos(-1.0); final long infl = 0x3f3f3f3f3f3f3f3fl; final int inf = 0x3f3f3f3f; final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; boolean zero(double x){ return x < eps; } /** io **/ PrintWriter out; BufferedReader reader; StringTokenizer tokens; Main(){ long s = System.currentTimeMillis(); tokens = new StringTokenizer(""); reader = new BufferedReader(new InputStreamReader(System.in), 1 << 15); out = new PrintWriter(System.out); Locale.setDefault(Locale.US); // imprime double com ponto solve(); out.close(); debug("Time elapsed: %dms", System.currentTimeMillis() - s); } void freopen(String s){ try{ reader = new BufferedReader(new InputStreamReader(new FileInputStream(s)), 1 << 15); } catch(FileNotFoundException e){ throw new RuntimeException(e); } } /** input -- supõe que não chegou no EOF **/ int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String next(){ readTokens(); return tokens.nextToken(); } String nextLine(){ readTokens(); return tokens.nextToken("\n"); } boolean readTokens(){ while(!tokens.hasMoreTokens()){ // lê os dados, ignorando linhas vazias try{ String line = reader.readLine(); if(line == null) return false; // EOF tokens = new StringTokenizer(line); } catch(IOException e){ throw new RuntimeException(e); } } return true; } /** output **/ void printf(String s, Object... o){ out.printf(s, o); } void debug(String s, Object... o){ if(!ONLINE_JUDGE) System.err.printf((char)27 + "[91m" + s + (char)27 + "[0m", o); } public static void main(String[] args){ new Main(); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class prob1177b { public static void main(String[] args){ Scanner sc=new Scanner(System.in); long k,c,n,d; c=1; d=9; n=1; k= sc.nextLong(); while(k>(c*d)) { k-=(c*d); n*=10; d*=10; c++; } n+=(k-1)/c; char[] num = String.valueOf(n).toCharArray(); System.out.println(num[(int)((k-1)%c)]); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class Digits_Sequence_Hard_Edition_Kamel { public static void main(String [] args) { Scanner sc = new Scanner(System.in); long k = sc.nextLong(); getResult(k); sc.close(); } static void getResult(long k) { long val = 0;; long ten = 1; int i = 1; while(true) { val = 9l*ten*i; if(k<=val) { decompose(k, ten, i); System.exit(0); } else { k-=val; ten = ten*10l; i++; } } } static void decompose(long offset, long ten, int size) { long val = ten - 1 +(long) Math.ceil((double)offset/size); int digit = (int)(((offset%size))-1 + size)%size; String result = String.valueOf(val).substring(digit, digit+1); System.out.print(result); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class prob1177b { public static void main(String[] args){ Scanner sc=new Scanner(System.in); long k,c,n,d; c=1; d=9; n=1; k= sc.nextLong(); while(k>(c*d)) { k-=(c*d); n*=10; d*=10; c++; } n+=(k-1)/c; char[] num = String.valueOf(n).toCharArray(); System.out.println(num[(int)((k-1)%c)]); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class A { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long K = Long.valueOf(br.readLine()); long n = 0; long k = 0; //len * Math.pow(10, len) * 0.9; long len = 0; while(true){ len++; long preK = k; long preN = n; k += len * Math.pow(10, len) * 0.9; n += Math.pow(10, len) * 0.9; if(K < k) { k = preK; n = preN; break; } } long step = len - 1; while(true){ while(k <= K){ long preK = k; long preN = n; if(step == 0){ k += len; n++; }else{ k += len * Math.pow(10, step) * 0.9; n += Math.pow(10, step) * 0.9; } if(k == K || (k >= K && k - K < len)){ //System.out.println(k); //System.out.println(n); String nStr = Long.toString(n); System.out.println(nStr.charAt(nStr.length() - (int)(k-K) - 1)); return; } if(K < k){ k = preK; n = preN; break; } } step--; } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.DataInputStream; import java.io.IOException; import java.io.FileInputStream; 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; Reader in = new Reader(inputStream); PrintWriter out = new PrintWriter(outputStream); BDigitsSequenceHardEdition solver = new BDigitsSequenceHardEdition(); solver.solve(1, in, out); out.close(); } static class BDigitsSequenceHardEdition { public void solve(int testNumber, Reader in, PrintWriter out) { long k = in.nextLong(); long start = 1; long nDigit = 1; while (true) { long curr = start * 9 * nDigit; if (curr >= k) break; start *= 10; nDigit += 1; k -= curr; } if (k % nDigit == 0) { start += (k / nDigit - 1); out.println(start % 10); } else { long n = start + ((k / nDigit)); int off = (int) (k % nDigit); out.println(Long.toString(n).charAt(off - 1)); } } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public Reader(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) { try { din = new DataInputStream(new FileInputStream(file_name)); } catch (IOException e) { throw new RuntimeException(e); } buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } 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; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; } } catch (IOException e) { throw new RuntimeException(e); } } private byte read() { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long itrIdx = 0; long itr = 0; long num = 0; while(itrIdx < n){ itrIdx += (itr+1)*(Math.pow(10,itr+1) - Math.pow(10,itr)); num+= (Math.pow(10,itr+1) - Math.pow(10,itr)); itr++; } itrIdx -= itr*(Math.pow(10,itr)-Math.pow(10,itr-1)); num -= (Math.pow(10,itr)-Math.pow(10,itr-1)); long lastNum = num + ((n-itrIdx)/itr); long lastNumIndex = itrIdx + (itr* (lastNum-num)); if(lastNumIndex == n){ lastNumIndex = lastNumIndex-itr; lastNum -=1; } String nextNum = String.valueOf(lastNum+=1); System.out.println(nextNum.charAt((int) (n-lastNumIndex-1))); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } void work() { long r=in.nextLong(); long b=0; for(;;b++){ long num=9*(long)Math.pow(10,(double)b)*(b+1); if(r-num<=0){ break; } r-=num; } long base=(long)Math.pow(10,(double)b); long c=(r-1)/(b+1); int m=(int)((r-1)%(b+1)); base+=c; String str=base+""; out.println(str.charAt(m)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long itrIdx = 0; long itr = 0; long num = 0; while(itrIdx < n){ itrIdx += (itr+1)*(Math.pow(10,itr+1) - Math.pow(10,itr)); num+= (Math.pow(10,itr+1) - Math.pow(10,itr)); itr++; } itrIdx -= itr*(Math.pow(10,itr)-Math.pow(10,itr-1)); num -= (Math.pow(10,itr)-Math.pow(10,itr-1)); long lastNum = num + ((n-itrIdx)/itr); long lastNumIndex = itrIdx + (itr* (lastNum-num)); if(lastNumIndex == n){ lastNumIndex = lastNumIndex-itr; lastNum -=1; } String nextNum = String.valueOf(lastNum+=1); System.out.println(nextNum.charAt((int) (n-lastNumIndex-1))); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Berland{ public static void main(String[] args) throws NumberFormatException, IOException { new Berland().run(); } public void run() throws NumberFormatException, IOException { BufferedReader file = new BufferedReader(new InputStreamReader(System.in)); long N = Long.parseLong(file.readLine()); long[] cutoff = new long[13]; cutoff[0] = 0; for(int i = 1;i<=12;i++) { cutoff[i] = cutoff[i-1] + (long)(9*Math.pow(10,i-1))*i; } int dig = -1; for(int i = 0;i<12;i++) { if(cutoff[i]>=N) { dig = i; break; } } long sub = N - cutoff[dig-1]-1; long num = (sub)/dig; long number = (long)Math.pow(10,dig-1)+num; int pos = (int)(sub % dig); System.out.println((number+"").charAt(pos)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
// package name; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); long k = s.nextLong(); long dp[] = new long[13]; long x = 9; int i = 1; long ansx = 0; int ansi = 0; for(; i < 13; i++) { dp[i] = dp[i - 1] + x * i; x *= 10; if(k <= dp[i]) { ansx = x; ansi = i; break; } if(dp[i] > 1000000000000l) break; } if(ansi < 2) { System.out.println(k); return; } k -= dp[ansi - 1]; //System.out.println(k); long st = (long)Math.pow(10, ansi - 1); long div = (k / ansi); if(k % ansi == 0) div--; k -= div * ansi; //System.out.println(k); System.out.println(findKthDigit(st + div, k)); } private static Long findKthDigit(long xx, long k) { int z = (int) k; ArrayList<Long> arr = new ArrayList(); while(xx > 0) { arr.add(xx % 10); xx /= 10; } return arr.get(arr.size() - z); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class digits { public static void main(String[] args) { long k = (new Scanner(System.in)).nextLong(); //k = 56 //League 1: 0 - 9 //League 2: 10 - 99 //League 3: 100 - 999.. //System.out.println("k = "+k); long league = 1; long irrelevancy = 0; while(true) { irrelevancy += league * (Math.pow(10, league) - Math.pow(10, league-1)); if(k > irrelevancy) league ++; //league = 1 : k = 56 > 9 //league = 2 : k = 56 < 99 //therefore league = 2 else break; } //System.out.println("League = "+league); irrelevancy = 0; for(long i=1; i<league; i++) irrelevancy += i * (Math.pow(10, i) - Math.pow(10, i-1)); //irrelevancy = 1 * (10^1 - 10^0) = 9 long modified_k = k - irrelevancy; //modified_k = 56 - 9 = 47 //System.out.println("modified k = "+ modified_k); long number = (long)(Math.pow(10, league-1)) - 1 + modified_k / league; //System.out.println("number = "+number); if(modified_k % league == 0) System.out.println(number % 10); else { number ++; long position_of_digit = (long)(modified_k % league); //System.out.println(position_of_digit); //number = 24 //position_of_digit = 47 % 2 = 1 System.out.println((Long.toString(number)).charAt((int)position_of_digit-1)); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { static final int MAX_N = 1000010; static final int INF = 0x3f3f3f3f; static final int mod = 1000000007; public static void main(String[] args) throws IOException { initReader(System.in); // int T = nextInt(); // for (int i = 1; i <= T; i++) solve(); pw.flush(); } /*******************************************************************************************************************************/ public static void solve() throws IOException { while (hasNext()) { long n = nextLong() - 1; long k = 1, x = 9; while (n - k * x >= 0) { n -= k * x; k += 1; x *= 10; } if (n == 0) pw.println(1); else { long num = x / 9 + n / k; String s = String.valueOf(num); pw.println(s.charAt((int) (n % k))); } } } /*******************************************************************************************************************************/ static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter pw; public static void initReader(InputStream input) throws IOException { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); // reader = new BufferedReader(new FileReader("ate.in")); // tokenizer = new StringTokenizer(""); // printWriter = new PrintWriter(new BufferedWriter(new FileWriter("ate.out"))); } public static boolean hasNext() { try { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (Exception e) { return false; } return true; } public static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static String nextLine() { try { return reader.readLine(); } catch (Exception e) { return null; } } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static char nextChar() throws IOException { return next().charAt(0); } static class Pair { char first; boolean second; public Pair(char first, boolean second) { // TODO Auto-generated constructor stub this.first = first; this.second = second; } @Override public String toString() { // TODO Auto-generated method stub return "(" + this.first + ", " + this.second + ")"; } } }
logn
1177_B. Digits Sequence (Hard Edition)
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)); long k=Long.parseLong(br.readLine()); long l=1,h=1000000000000l; long p[]=new long[13]; for(int i=1;i<=12;i++) { long ll=9*i; p[i]=ll*(long)Math.pow(10,i-1); p[i]+=p[i-1]; } while(h-l>1) { long mid=(l+h)/2; long num=(long)(Math.log(mid)/Math.log(10)); long l1=p[(int)num]+(num+1)*(mid-(long)Math.pow(10,num)); long l2=p[(int)num]+(num+1)*(mid-(long)Math.pow(10,num)+1); if(k<=l1) h=mid; else if(k>l2) l=mid; else { l=mid; h=mid; } } if(h-l==1) { long num=(long)(Math.log(h)/Math.log(10)); long l1=p[(int)num]+(num+1)*(h-(long)Math.pow(10,num)); long l2=p[(int)num]+(num+1)*(h-(long)Math.pow(10,num)+1); if(k>l1 && k<=l2) { l=h; } } long n=(long)(Math.log(l)/Math.log(10)); long u=p[(int)n]+(n+1)*(l-(long)Math.pow(10,n)); k-=u; String ss=String.valueOf(l); //System.out.println(l+" "+k); System.out.println(ss.charAt((int)(k-1))); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Queue; import java.util.Scanner; public class Tests { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long inputNum = 0; String finalResult = ""; inputNum = scanner.nextLong(); long upperLimitResult = 0; long lowerLimitResult = 0; int multiplier = 0; do { multiplier++; lowerLimitResult = upperLimitResult; upperLimitResult += 9 * Math.pow(10, multiplier - 1) * (multiplier); } while (inputNum > upperLimitResult); long remainderFromLowerRange = inputNum - lowerLimitResult; long repititions = 0; if (multiplier > 1) repititions = (remainderFromLowerRange - 1 > 0 ? remainderFromLowerRange - 1 : 0) / multiplier; long currentNumber = (long) (Math.pow(10, multiplier - 1) + repititions); remainderFromLowerRange = remainderFromLowerRange - repititions * multiplier; long digitIndex = remainderFromLowerRange < multiplier ? multiplier - remainderFromLowerRange : remainderFromLowerRange % multiplier; if (multiplier == 1) { finalResult = (remainderFromLowerRange % 10) + ""; } else { int charToGet = (int) ((multiplier - 1) - digitIndex); finalResult = (currentNumber + "").charAt(charToGet) + ""; } System.out.print(finalResult); scanner.close(); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=1; while(T-->0) { long k=input.nextLong(); long v=9; long s=0; int x=1; while(true) { if(s+v*x>k) { break; } s+=v*x; v*=10; x++; } if(s==k) { out.println(9); } else { long d=k-s; long u=d/x; long rem=d%x; long nu=(long)Math.pow(10,x-1); nu+=u; if(rem==0) { nu--; out.println(nu%10); } else { String str=String.valueOf(nu); out.println(str.charAt((int)(rem-1))); } } } out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1177b { public static void main(String[] args) throws IOException { long k = rl(), n = -1; for (long l = 0, r = k; l <= r; ) { long m = l + (r - l) / 2; if (f(m) < k) { n = m + 1; l = m + 1; } else { r = m - 1; } } k -= f(n - 1); char[] s = Long.toString(n).toCharArray(); prln(s[(int) k - 1]); close(); } static long f(long x) { if (x < 10) { return x; } long pow10 = 1, cnt = 1; while (x >= pow10 * 10) { pow10 *= 10; ++cnt; } return cnt * (x - pow10 + 1) + f(pow10 - 1); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // graph util static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static void pryesno(boolean b) {prln(b ? "yes" : "no");}; static void pryn(boolean b) {prln(b ? "Yes" : "No");} static void prYN(boolean b) {prln(b ? "YES" : "NO");} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();}}
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class P_1177B { public static void main(String[] args) { Scanner scan = new Scanner(System.in); long k = scan.nextLong(); long k2 = k - 10; int cont = 1, pos; String out; //System.out.println(getString((int)k)); if(k <= 9) System.out.println(k); else { cont++; while(k2 >= cont*(long)(Math.pow(10, cont)-Math.pow(10, cont-1))) { k2 -= cont*(long)(Math.pow(10, cont)-Math.pow(10, cont-1)); cont++; } pos = (int)(k2%cont); k2 /= cont; k2 += (long)Math.pow(10, cont-1); out = String.valueOf(k2); System.out.println(out.charAt(pos)); } } /*public static String getString(int number) { int contador = 1; String salida = ""; while(salida.length() <= number) { salida += contador; contador++; } return salida.substring(0, number); }*/ }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Stack; import java.util.StringTokenizer; import java.util.prefs.BackingStoreException; public class answertillD { static ArrayList<Integer>[] adjlist; static int[][] adjmatrix; static int[][] adjmatrix2; static boolean[] vis; static boolean[] intialvis; static boolean[] vis2; static int[] counter; static int V, E; static Stack<Integer> st; static ArrayList<Integer> arrylist; static boolean flag; static int[] dx = new int[] { 1, -1, 0, 0 }; static int[] dy = new int[] { 0, 0, 1, -1 }; static int[] Arr; static PrintWriter pw; public static long gcd(long u, long v) { if (u == 0) return v; return gcd(v % u, u); } public static int dfs(int u) { vis[u] = true; int a = 0; for (int v : adjlist[u]) if (!vis[v]) a += dfs(v); return 1 + a; } public static void dfs(int u, int num) { vis2[u] = true; counter[u] = num; for (int v : adjlist[u]) if (!vis2[v]) dfs(v, num); } static long diff=Long.MAX_VALUE; static boolean check(long num, long k) { int n=(num+"").length()-1; long m=1; long sum=0;int i=1; while(n-->0) { sum+=9*m*(i++) ; m*=10; } sum+=(num-m)*i+1; if(sum<=k) diff=Math.min(diff, k-sum); return sum<=k; } static long bin(long k) { long left = 1; long right = k+1; long mid; long ans = 1; while (left <= right) { mid = (left + right) / 2; if (check(mid, k)) { ans = mid; left = mid + 1; } else right = mid - 1; } return ans; } public static long power(long x, int i) { long r = 1; while (i-- > 0) { if (r > 1e18 / x) return (long) (1e18 + 5); r = r * x; } return r; } static int m; static int calculate(int[] Arrs, int[] Arre, int index, boolean left, boolean targetleft) { int ans = 0; int n = m + 2; if (left) { ans = Arre[index - 1]; if ((index != E + 1)) ans += (targetleft) ? Arre[index - 1] : n - Arre[index - 1] - 1; } else { ans = n - Arrs[index - 1] - 1; if ((index != E + 1)) ans += ((targetleft) ? Arrs[index - 1] : n - Arrs[index - 1] - 1); } return ans; } static int min = Integer.MAX_VALUE; static void backtrack(int[] Arrs, int[] Arre, int soFarMin, int index, boolean left) { if (index == E) { min = Math.min(min, soFarMin - 1); return; } int newmin1 = calculate(Arrs, Arre, index, left, left); int newmin2 = calculate(Arrs, Arre, index, left, !left); backtrack(Arrs, Arre, soFarMin + newmin1 + 1, index - 1, left); backtrack(Arrs, Arre, soFarMin + newmin2 + 1, index - 1, !left); } public static String add(String str1,String str2){ Stack<String>st=new Stack<String>(); int n=str1.length(); int m=str2.length(); int max=Math.max(n, m); int sum=0,carry=0; for(int i=0;i<max;i++){ int num1=0,num2=0; if(n>=i) num1 = Integer.parseInt(str1.charAt(n-i) + ""); if(m>=i) num2 = Integer.parseInt(str2.charAt(m-i) + ""); int z = num1 + num2 + carry; if (z >= 10) { sum = z / 10; carry = z % 10; } else { sum = z; carry=0; } st.add(sum+""); } StringBuilder sb=new StringBuilder(); while(!st.isEmpty()){ sb.append(st.pop()); } return sb+""; } public static void main(String[] args) throws IOException, InterruptedException { Scanner sc = new Scanner(System.in); long k=sc.nextLong(); long bi=bin(k); String str=bi+""; System.out.println(str.charAt((int) diff)); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { long n = in.nextLong(); long st = 1, en = n, ans = 0, len = 0; while (st <= en) { long mid = (st + en) / 2; long have = 0; int curLen = Long.toString(mid).length(); long bef = 0; for (int i = 1; i < curLen; i++) { long cur = 0; for (int j = 1; j <= i; j++) { cur *= 10; cur += 9; } have += i * (cur - bef); bef = cur; } have += curLen * (mid - bef); if (have < n) { ans = mid; len = have; st = mid + 1; } else en = mid - 1; } String s = Long.toString(ans + 1); for (int i = 0; i < s.length(); i++) { if (len + i + 1 == n) { out.print(s.charAt(i)); return; } } } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class Training { public static void main(String[] args) { Scanner in = new Scanner(System.in); long index = in.nextLong(); if (index < 10) { //one digit System.out.println(index); } else if (index < 190) { //two digits solve(2, index, 10, 10); } else if (index < 2890) { //three digits solve(3, index, 190, 100); } else if (index < 38890) { //four digits solve(4, index, 2890, 1000); //start changing ------------------------------------------------------------ } else if (index < 488890) { //five digits solve(5, index, 38890, 10000); } else if (index < 5888890) { //six digits solve(6, index, 488890, 100000); } else if (index < 68888890) { //seven digits solve(7, index, 5888890, 1000000); } else if (index < 788888890) { //eight digits solve(8, index, 68888890, 10000000); } else if (index < 8888888890l) { //nign digits solve(9, index, 788888890, 100000000); } else if (index < 98888888890l) { //ten digits solve(10, index, 8888888890l, 1000000000); } else { solve(11, index, 98888888890l, 10000000000l); } } static void solve(int length, long index, long lastPoint, long num) { String s = ""; num += (index - lastPoint) / length; s += num; int mod = (int) ((index - lastPoint) % length); System.out.println(s.charAt(mod)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; import java.io.*; public class DigitSequenceA { public static void main(String[] args) throws IOException{ FastReader in = new FastReader(); double digit = in.nextDouble(); double temp = digit; long[] seq = new long[13]; for(int i = 1; i<13; i++){ seq[i] = (9* (long)Math.pow(10,i-1)) * (i) +seq[i-1]; } int power = 0; for(int i = 0; i< 13; i++){ if(temp-seq[i] >0){ continue; } else{ power = i; break; } } long place = (long) Math.ceil(digit - seq[power-1]); place = (long)Math.ceil(place/power); if((digit - seq[power-1])%power>0){ place++; } long num = (long) (place + Math.pow(10,power-1)-1); String num2 = Long.toString(num); long end = seq[power-1] + place*power; long answer = (long)(power-(end - digit)); //System.out.println("Digit is at the " + power + " power"); //System.out.println("Digit is at the " + place + " number of the sequence"); //System.out.println("Number is " + num); //System.out.println("Digit is at the " + answer+ " in that number"); //System.out.println("Answer is " + num2.charAt((int)answer-1)); System.out.println(num2.charAt((int)answer-1)); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class DigitQueries { public static void main(String[] args) throws IOException { FastReader in = new FastReader(); int q = 1; while (q-- > 0) { long k; k = in.nextLong(); Query(k); } } static void Query(long k){ long x=0; long sum=0; while(sum<k){ sum+=9*Math.pow(10, x)*(x+1); if(sum>k){ sum-=9*Math.pow(10, x)*(x+1); break; } x++; } long y = (k-sum); long last = 0; last = (long)Math.pow(10,x)+ (long)y/(x+1)-1; long z =y%(x+1); if(z!=0){ last=(long)(last+1)/(long)Math.pow(10,x+1-z); } System.out.println(last%10); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; import java.io.*; import java.text.*; public class Main { //SOLUTION BEGIN //Into the Hardware Mode void pre() throws Exception{} void solve(int TC) throws Exception { long K = nl(); K--; int sz = 1;long pw = 1; while(K >= pw){ long npw = pw*10; long dig = sz*(npw-pw); if(K >= dig){ K -= dig; sz++;pw *= 10; }else break; } long num = pw+K/sz; int dig = sz-(int)(K%sz)-1; while(dig-->0)num /= 10; pn(num%10); } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} void exit(boolean b){if(!b)System.exit(0);} static void debug(Object... o){System.err.println(Arrays.deepToString(o));} final long IINF = (long)2e18; final int INF = (int)1e9+2; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8; static boolean multipleTC = false, memory = true, fileIO = false; FastReader in;PrintWriter out; void run() throws Exception{ long ct = System.currentTimeMillis(); if (fileIO) { in = new FastReader(""); out = new PrintWriter(""); } else { in = new FastReader(); out = new PrintWriter(System.out); } //Solution Credits: Taranpreet Singh int T = multipleTC? ni():1; pre(); for (int t = 1; t <= T; t++) solve(t); out.flush(); out.close(); System.err.println(System.currentTimeMillis() - ct); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } int[][] make(int n, int e, int[] from, int[] to, boolean f){ int[][] g = new int[n][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = to[i]; if(f)g[to[i]][--cnt[to[i]]] = from[i]; } return g; } int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){ int[][][] g = new int[n][][];int[]cnt = new int[n]; for(int i = 0; i< e; i++){ cnt[from[i]]++; if(f)cnt[to[i]]++; } for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][]; for(int i = 0; i< e; i++){ g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0}; if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1}; } return g; } int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));} int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;} long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.*; import java.util.Scanner; public class Test { public static int digit(long number){ int i = 1; long exp = 1; while(number > i * 9 * exp){ number -= i * 9 * exp; i++; exp *= 10; } return i; } public static int result(long number){ int digit = digit(number); long exp = 1; for(int i = 0; i < (digit - 1); i++){ number -= (i+1) * 9 * exp; exp *= 10; } long b = number / digit; int c = (int)(number % digit); if(c > 0){ String d = Long.toString(exp + b); return d.charAt(c - 1) - '0'; } else{ String d = Long.toString(exp + b - 1); return d.charAt(d.length() - 1) - '0'; } } public static void main(String[] args){ Scanner input = new Scanner(System.in); long k = input.nextLong(); System.out.println(result(k)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; public class Codechef { 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 ni() throws IOException { return Integer.parseInt(next()); } long nl() throws IOException { return Long.parseLong(next()); } double nd() throws IOException { return Double.parseDouble(next()); } char nc() throws IOException { return (char) (br.read()); } String nextLine() throws IOException { return br.readLine(); } int[] niArray(int n) throws IOException{ int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } long[] nlArray(int n) throws IOException { long a[] = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } double[] ndArray(int n)throws IOException { double a[] = new double[n]; for (int i = 0; i < n; i++) a[i] = nd(); return a; } } static long mod=Long.MAX_VALUE; static PrintWriter out=new PrintWriter(System.out); static FastScanner in = new FastScanner(System.in); public static void main (String[] args) throws java.lang.Exception { int i,j; long flag,flag1,flag2,temp,temp2,temp1,count,counter,l; HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); /* if(hm.containsKey(z)) hm.put(z,hm.get(z)+1); else hm.put(z,1); */ ArrayList<Integer> arr=new ArrayList<Integer>(); HashSet<Integer> set=new HashSet<Integer>(); PriorityQueue<Integer> pq=new PriorityQueue<Integer>(); //for(i=1;i<200;i++) //{ long k=in.nl(); temp=9;l=1;temp2=0; while(true) { if(k<=temp2+temp*l) {k-=temp2;break;} else { temp2+=temp*l; temp*=10; l++; } } long z=((k-1)/l); //out.println(i+":- "+l+" "+((k-1)/l)+" "+(k%l==0?l:k%l)); long no=(long)Math.pow(10,(l-1))+z; //out.println(no); int index=(int)(k%l==0?l:k%l)-1; String p=Long.toString(no); //out.println(p+" "+index); out.println(p.charAt(index)); //} out.close(); } static long gcd(long a,long b) { if(b==0) return a; return gcd(b,a%b); } static long exponent(long a,long n) { long ans=1; while(n!=0) { if(n%2==0) ans=(ans*a)%mod; a=(a*a)%mod; n=n>>1; } return ans; } static int binarySearch(int a[], int item, int low, int high) { if (high <= low) return (item > a[low])? (low + 1): low; int mid = (low + high)/2; if(item == a[mid]) return mid+1; if(item > a[mid]) return binarySearch(a, item, mid+1, high); return binarySearch(a, item, low, mid-1); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class cf_contest_1177_problem_B { public static void main(String[] args) { Scanner s = new Scanner(System.in); long k = s.nextLong(); if (k<=9) System.out.println(k); else { int c = 1; while(k>c*((Math.pow(10,c)) - Math.pow(10,c-1))) { k-=c*((Math.pow(10,c)) - Math.pow(10,c-1)); // System.out.println(k + " hello " + c); c++; } // System.out.println("k is " + k); long mo = k%c; // System.out.println("mo is " + mo); k = k/c; if (mo == 0) { mo = c; k--; } mo--; // k = Math.max(k-1,0); // System.out.println("k/c is " + k); long j = (long) (Math.pow(10,c-1) + k); String j1 = "" + j; // System.out.println("j1 is " + j1); // System.out.println("final ans= " + j1.charAt((int)mo)); // System.out.println(); System.out.println(j1.charAt((int)mo)); } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class DigitalSequence { public static void print(String s) { System.out.println(s); } public static void main(String[] args) { long k = new Scanner(System.in).nextLong(); long i = 1,t=0, c = 9,digits = 0,l=0,k2=k; while(t<k){ l = t; t += i*c; i++; c*=10; digits++; } k = k-l; long lastNumber = (long)Math.pow(10,digits-1)-1; long p = k/digits,q=k%digits; long finalNumber =lastNumber+p; if(q!=0){ finalNumber++; } k = k-digits*p; if(k<=0) k+=digits; String ans = ""+finalNumber; int index = (int)(k-1); print(""+ans.charAt(index)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class DigitSeq { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc = new FastReader(); OutputStream outputstream = System.out; PrintWriter out = new PrintWriter(outputstream); long n = sc.nextLong(); long[] arr = new long[14]; for(int i = 1; i <= 13; i++){ arr[i] = (long)Math.pow(10, i)-(long)Math.pow(10, i-1); } long total = 0; /*for(int i = 1; i <= 13; i++) out.print(arr[i] + " "); out.println();*/ for(int i = 1; i <= 13; i++){ if(total+(long)i*arr[i]>=n){ long ans = n-total; long rest = ans; //System.out.println(rest); if(ans%i!=0){ ans /= i; ans++; } else { ans /= i; } ans += (long)Math.pow(10, i-1)-1; String str = Long.toString(ans); int ind = (rest%i==0) ? i-1 : (int)(rest%i)-1; //System.out.println(ind); out.println(str.charAt(ind)); break; } total = total+(long)i*arr[i]; //System.out.println(total); } out.close(); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class A { void solve(){ long k = readLong(); long x = 9; long y = 1; while(k > x * y){ k -= x * y; x *= 10; y++; } long w = k / y + (k % y == 0 ? 0 : 1); long e = (k % y - 1 % y + y) % y; long num = x/9 + w - 1; String s = Long.toString(num); out.print(s.charAt((int) e) - '0'); } public static void main(String[] args) { new A().run(); } void run(){ init(); solve(); out.close(); } BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init(){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } String readLine(){ try{ return in.readLine(); }catch(Exception ex){ throw new RuntimeException(ex); } } String readString(){ while(!tok.hasMoreTokens()){ String nextLine = readLine(); if(nextLine == null) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(); } int readInt(){ return Integer.parseInt(readString()); } long readLong(){ return Long.parseLong(readString()); } double readDouble(){ return Double.parseDouble(readString()); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
// Don't place your source in a package import java.math.BigInteger; import java.util.*; import java.lang.*; import java.io.*; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(System.out); int T=1; for(int t=0;t<T;t++){ long k=Long(); Solution sol=new Solution(out); sol.solution(k); } out.flush(); } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution{ PrintWriter out; public Solution(PrintWriter out){ this.out=out; } long f[]=new long[15]; public void solution(long k){ f[0]=9; for(int i=1;i<f.length;i++){ f[i]=10*f[i-1]; } for(int i=1;i<f.length;i++){ f[i]*=(i+1); } long l=1,r=1000000000000l; long res=-1; long count=0; while(l<=r){ long mid=l+(r-l)/2; long cnt=get(mid); if(cnt>=k){ res=mid; count=cnt; r=mid-1; } else{ l=mid+1; } } int extra=(int)(count-k); String s=res+""; out.println(s.charAt(s.length()-1-extra)); } public long get(long n){ long res=0; long base=0; int i=0; while(true){ if(n<=base*10+9){ res=res+(i+1)*(n-base); break; } res+=(f[i]); i++; base=base*10+9; } return res; } } /* ;\ |' \ _ ; : ; / `-. /: : | | ,-.`-. ,': : | \ : `. `. ,'-. : | \ ; ; `-.__,' `-.| \ ; ; ::: ,::'`:. `. \ `-. : ` :. `. \ \ \ , ; ,: (\ \ :., :. ,'o)): ` `-. ,/,' ;' ,::"'`.`---' `. `-._ ,/ : ; '" `;' ,--`. ;/ :; ; ,:' ( ,:) ,.,:. ; ,:., ,-._ `. \""'/ '::' `:'` ,'( \`._____.-'"' ;, ; `. `. `._`-. \\ ;:. ;: `-._`-.\ \`. '`:. : |' `. `\ ) \ -hrr- ` ;: | `--\__,' '` ,' ,-' free bug dog */
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
//package test_1177a; import java.util.Scanner; import java.util.Scanner; public class test1177b{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); long k = sc.nextLong(); long k1 =0,k2 = 0; long p = 1; String str=""; for (int i=1; i<=12;i++){ if (k>= k1 && k <= k1 + p * 9 *i){ // Нашли порядок long kk = ((k - k1) % i); k2 = p + (k - k1) / i -1; if (kk != 0) k2 ++; str =""+ k2; if(str.length() > i) { k2--; str =""+ k2; kk =0; } if(kk > 0){ System.out.println(str.charAt((int)kk-1)); }else{ System.out.println(str.charAt(i-1)); } break; }else { k1 += p * 9 *i; p = p * 10; } } } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CodeForces1177B { public static char custBinSearch(long lower, long upper, long lowIndex, int ten, long position) { long half = Math.round((lower + upper) / 2.0); long lowBound = lowIndex + (half - lower)*(ten + 1); long upBound = lowBound + ten; if(position < lowBound) { //Less than the lowest index of half return custBinSearch(lower, half - 1, lowIndex, ten, position); } else if (position > upBound) { //Remember to update lowIndex here. lowIndex += (half + 1 - lower)*(ten + 1); return custBinSearch(half + 1, upper, lowIndex, ten, position); } else { return Long.toString(half).charAt((int) (position - lowBound)); //The final number will at max be 11 characters long, thus it is safe to convert and cast. } } public static void main(String[] args) throws IOException { BufferedReader inputs = new BufferedReader(new InputStreamReader(System.in)); long indexPosition = Long.parseLong(inputs.readLine()); inputs.close(); //Isolate possible combinations so that all further numbers will have the same length. int tenFactor = 0; long lowerBound = 1; long upperBound = (long) (Math.pow(10, 12)); long lowerIndexBound = 1; long redIndex = 0; redIndex += indexPosition; while(redIndex > 0) { redIndex -= (long) (9*Math.pow(10, tenFactor)*(tenFactor + 1)); if(redIndex <= 0) { //Stage 1: Completed Successfully. lowerBound = (long) (Math.pow(10, tenFactor)); upperBound = (long) (Math.pow(10, tenFactor + 1) - 1); break; } lowerIndexBound += (long) (9*Math.pow(10, tenFactor)*(tenFactor + 1)); tenFactor++; } System.out.println(custBinSearch(lowerBound, upperBound, lowerIndexBound, tenFactor, indexPosition)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class Main { public static Character solve(long a, long b, long c) { long min = a; long max; long xth = 0; long index; for (index = String.valueOf(a).length() - 1;; index++) { long numOfDigits = 0; max = (long) Math.pow(10, index + 1) - 1; long count = (max - min) / b + 1; numOfDigits += count * (index + 1); if (c - numOfDigits <= 0) { break; } c -= numOfDigits; min = min + count * b; } // find xth if (c % (index + 1) == 0) { xth = c / (index + 1); } else { xth = c / (index + 1) + 1; } long lastNum = min + b * (xth - 1); int pos = (int) (c % (index + 1)); // here is the output if (pos == 0) { return String.valueOf(lastNum).charAt((int) index); } else { return String.valueOf(lastNum).charAt(pos - 1); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); long tc; tc = sc.nextLong(); System.out.println(solve(1, 1, tc)); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class B1177 { public static void main(String[] args) { Scanner in = new Scanner(System.in); long N = in.nextLong(); long answer = solve(N, 0, 1, 1); System.out.println(answer); } static long solve(long N, long offset, long start, int digits) { long thisSection = digits*start*9; long fromOffset = N-offset; if (fromOffset > thisSection) { return solve(N, offset+thisSection, 10*start, digits+1); } long number = start + (fromOffset-1)/digits; long posInNumber = digits - 1 - (fromOffset-1)%digits; while (posInNumber > 0) { posInNumber--; number /= 10; } return number%10; } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.Scanner; public class Solution { public static void main(String[] args) { long b=0;long p=1; Scanner s=new Scanner(System.in); long m=s.nextLong(); long x=1; do{ p=(m+b)/x; b=10*b+10; x++; }while(p/(long)Math.pow(10, x-1)!=0); rest : x--;b=b/10-1; b=x*p-b; b=m-b; b=x-b-1; p/=(long)Math.pow(10, b); p%=10; System.out.println(p); } }
logn
1177_B. Digits Sequence (Hard Edition)
CODEFORCES
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ int q=in.nextInt(); for(int i=0;i<q;i++) { work(); } out.flush(); } long mod=1000000007; long gcd(long a,long b) { return a==0?b:b>a?gcd(b%a,a):gcd(b,a); } void work() { long n=in.nextLong(); long k=in.nextLong(); if(k==0) { out.println("YES"+" "+n); } long a=0,b=0,c=1,d=1; while(--n>=0&&a<=k) { b+=c; c*=4; a+=d; d=d*2+1; long t=count(c-d,n); if(a<=k&&b>=k-t) { out.println("YES"+ " "+n); return; } } out.println("NO"); } private long count(long l, long n) { if(n==0)return 0; n--; long ret=l; for(int i=1;i<=n;i++) { long t=ret; ret*=4; if(ret/4!=t)return Long.MAX_VALUE; } return ret; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Vadim */ 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); D solver = new D(); solver.solve(1, in, out); out.close(); } static class D { public void solve(int testNumber, FastScanner in, PrintWriter out) { int T = in.ni(); for (int t = 0; t < T; t++) { long n = in.nl(), k = in.nl(); if (n == 2 && k == 3) { out.println("NO"); continue; } boolean possible = false; long size = n; long rem = k; for (int i = 0; i <= 31 && size > 0 && rem > 0; i++) { long splits = 1L << (i * 2); //System.out.println("splits = " + splits); rem -= splits; size--; } if (rem > 0) { //System.out.println("rem = " + rem); out.println("NO"); continue; } long path = 1; long i = 0; size = n; long ans = 0; while (path <= k && size > 0) { //System.out.printf("path=%d k=%d size=%d%n", path, k, size); k -= path; path = (1L << i + 2) - 1; size--; i++; } //System.out.printf("size=%d k=%d%n", size, k); out.println("YES " + size); } } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { 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 ni() { return Integer.parseInt(ns()); } public long nl() { return Long.parseLong(ns()); } } }
logn
1080_D. Olya and magical square
CODEFORCES
public class D { public Object solve() { long N = sc.nextLong(), K = sc.nextLong() - 1; if (N >= 32) return print("YES", N-1); long A = 1L << (N-1), C = 4, T = (A*A - 1) / 3; while (A > 1 && K > T) { A /= 2; K -= (C-1); C *= 2; T += (C-3) * (A*A - 1) / 3; } if (K >= 0 && K <= T) return print("YES", Long.numberOfTrailingZeros(A)); else return print("NO"); } private static final boolean ONE_TEST_CASE = false; private static void init() { } //////////////////////////////////////////////////////////////////////////////////// OFF private static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static Object print (Object o, Object ... A) { IOUtils.print(o, A); return null; } private static class IOUtils { public static class MyScanner { public String next() { newLine(); return line[index++]; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = split(readLine()); index = 0; } } private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim(String delim, Object o, Object ... A) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : A) append(b, p, delim); return b.substring(delim.length()); } ////////////////////////////////////////////////////////////////////////////////// private static final java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########"); private static void start() { if (t == 0) t = millis(); } private static void append(java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) f.accept(java.lang.reflect.Array.get(o, i)); } else if (o instanceof Iterable<?>) ((Iterable<?>)o).forEach(f::accept); else g.accept(o instanceof Double ? formatter.format(o) : o); } private static void append(final StringBuilder b, Object o, final String delim) { append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o); } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static Object print(Object o, Object ... A) { pw.println(build(o, A)); if (DEBUG) System.err.println(build(o, A)); return null; } private static void err(Object o, Object ... A) { System.err.println(build(o, A)); } private static boolean PRINT, DEBUG; private static void write(Object o) { err(o, '(', time(), ')'); if (PRINT) pw.println(o); } private static void exit() { IOUtils.pw.close(); System.out.flush(); err("------------------"); err(time()); System.exit(0); } private static long t; private static long millis() { return System.currentTimeMillis(); } private static String time() { return "Time: " + (millis() - t) / 1000.0; } private static void run(int N) { try { DEBUG = System.getProperties().containsKey("DEBUG"); PRINT = System.getProperties().containsKey("PRINT"); } catch (Throwable t) {} for (int n = 1; n <= N; ++n) { Object res = new D().solve(); if (res != null) write("Case #" + n + ": " + build(res)); } exit(); } } //////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { init(); int N = ONE_TEST_CASE ? 1 : sc.nextInt(); IOUtils.run(N); } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author prakharjain */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { long maxk = (long) 1e18; public void solve(int testNumber, InputReader in, OutputWriter out) { int t = in.nextInt(); long maxn = 1; long val = 0; for (long i = 1; ; i++) { val = 1 + 4 * val; if (val >= maxk) { maxn = i; break; } } long[] vala = new long[(int) maxn + 1]; vala[1] = 1; for (int i = 2; i <= maxn; i++) { vala[i] = 1 + 4 * vala[i - 1]; } o: while (t-- > 0) { long n = in.nextInt(); long k = in.nextLong(); if (n - 1 >= maxn) { out.println("YES " + (n - 1)); continue; } k--; if (k <= vala[(int) n - 1]) { out.println("YES " + (n - 1)); continue; } long cs = n - 1; long cc = 3; int ind = 2; long end = -1; while (k > 0) { if (k >= cc && cs > 0) { k -= cc; cc += (1l << ind); cs--; ind++; } else { // if (cs > 0 && k < cc) { // out.println("YES " + cs); // continue o; // } end = ind; break; } } long fcs = cs; if (k == 0) { out.println("YES " + cs); continue; } k -= vala[(int) n - 1]; cs = n - 1; cc = 3; ind = 2; long rv = 5; long sind = 3; while (k > 0 && ind < end) { k -= rv * vala[(int) cs - 1]; rv += (1l << sind); sind++; cs--; ind++; } if (k <= 0) { out.println("YES " + fcs); } else { out.println("NO"); } } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } 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 static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
logn
1080_D. Olya and magical square
CODEFORCES
import javafx.util.*; import java.util.*; import java.io.*; import java.math.*; public class Test4 { PrintWriter pw = new PrintWriter(System.out); InputStream is = System.in; Random rnd = new Random(); int a; void run(){ a = ni(); for(int q=0; q<a; q++){ long nj = ni(), kj = nl(); BigInteger n = BigInteger.valueOf(nj), k = BigInteger.valueOf(kj); if((nj<40 && (k.compareTo(BigInteger.valueOf(2).pow(2*(int)nj).divide(BigInteger.valueOf(3)))>0))){ System.out.println("NO"); continue; } if(nj>=40){ System.out.println("YES "+(nj-1)); continue; } long log=nj; BigInteger maxop = BigInteger.valueOf(2).pow(2*(int)nj).divide(BigInteger.valueOf(3)), pth = BigInteger.ONE; for(BigInteger c = BigInteger.ONE; log>0; log--, c=c.multiply(BigInteger.valueOf(2)).add(BigInteger.ONE)){ if(k.compareTo(c)<0) break; pth = c.multiply(BigInteger.valueOf(2)).add(BigInteger.ONE); k=k.subtract(c); maxop=maxop.subtract(c); } maxop = maxop.subtract(pth.multiply(BigInteger.valueOf(2).pow(2*(int)log).divide(BigInteger.valueOf(3)))); if(k.compareTo(maxop)<=0) System.out.println("YES "+log); else System.out.println("NO"); } pw.flush(); } static class PyraSort { private static int heapSize; public static void sort(int[] a) { buildHeap(a); while (heapSize > 1) { swap(a, 0, heapSize - 1); heapSize--; heapify(a, 0); } } private static void buildHeap(int[] a) { heapSize = a.length; for (int i = a.length / 2; i >= 0; i--) { heapify(a, i); } } private static void heapify(int[] a, int i) { int l = 2 * i + 2; int r = 2 * i + 1; int largest = i; if (l < heapSize && a[i] < a[l]) { largest = l; } if (r < heapSize && a[largest] < a[r]) { largest = r; } if (i != largest) { swap(a, i, largest); heapify(a, largest); } } private static void swap(int[] a, int i, int j) { a[i] ^= a[j] ^= a[i]; a[j] ^= a[i]; } } public static void main(String[] args) { new Test4().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))){ 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(); } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.math.BigInteger; import java.util.ArrayList; import java.util.Scanner; public class Main { static ArrayList<BigInteger> bs = new ArrayList<>(); static void getBs(int n, BigInteger k) { BigInteger four = BigInteger.valueOf(4); BigInteger tmp4 = BigInteger.valueOf(1); BigInteger sum = BigInteger.ZERO; for (int i = 1; i <= n; i++) { sum = sum.add(tmp4); bs.add(sum); if (sum.compareTo(k) >= 0) break; tmp4 = tmp4.multiply(four); } } static int ss(int n, BigInteger k) { bs = new ArrayList<>(); BigInteger two = BigInteger.valueOf(2); BigInteger s1; BigInteger ts = BigInteger.ZERO; getBs(n - 1, k); int idx = bs.size() - 1; BigInteger tx = BigInteger.valueOf(-1); int ans = -1; for (int i = 1; i <= n; i++) { two = two.shiftLeft(1); s1 = two.add(BigInteger.valueOf(-i - 2)); if (idx >= 0) { tx = tx.add(BigInteger.ONE).multiply(BigInteger.valueOf(2)).add(BigInteger.ONE); ts = ts.add(tx.multiply(bs.get(idx--))); } if (k.compareTo(s1) >= 0) { if (k.subtract(s1).compareTo(ts) <= 0) { ans = n - i; break; } } } return ans; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while (T-- > 0) { int n = sc.nextInt(); BigInteger k = sc.nextBigInteger(); int ans = ss(n, k); if (ans == -1) { System.out.println("NO"); } else { System.out.println("YES " + ans); } } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; /** * Created by timur on 28.03.15. */ public class TaskD { boolean eof; BufferedReader br; StringTokenizer st; PrintWriter out; public static void main(String[] args) throws IOException { new TaskD().run(); } 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()); } public long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { return br.readLine(); } void run() throws IOException { InputStream input = System.in; PrintStream output = System.out; try { File f = new File("a.in"); if (f.exists() && f.canRead()) { input = new FileInputStream(f); output = new PrintStream("a.out"); } } catch (Throwable e) { } br = new BufferedReader(new InputStreamReader(input)); out = new PrintWriter(output); solve(); br.close(); out.close(); } long md(long x, long y, long x1, long y1) { return Math.abs(x - x1) + Math.abs(y - y1); } double md(double x, double y, double x1, double y1) { return Math.abs(x - x1) + Math.abs(y - y1); } double ed(double x, double y, double x1, double y1) { return Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1)); } void solve() { int t = nextInt(); long n, k; int m = 34; long[] res = new long[m]; res[1] = 0; res[2] = 1; for (int i = 3; i < m; i++) { res[i] = res[i - 1] * 4L; } long[] l = new long[m]; long[] r = new long[m]; l[0] = 0; l[1] = 1; r[0] = 0; r[1] = 1; for (int i = 2; i < m; i++) { l[i] = l[i - 1] * 2 + 1; r[i] = r[i - 1] * 4; } long[] mi = new long[m]; long[] ma = new long[m]; for (int i = 1; i < m; i++) { mi[i] = mi[i - 1] + l[i]; ma[i] = ma[i - 1] + r[i]; } // for (int i = 0; i < m - 1; i++) { // for (int j = 0; j <= i; j++) { // out.println(i + " " + j + " " + mi[(int)i - j] + " " + (ma[(int)i] - l[(int)i - j + 1] * ma[j])); // } // } for (int i = 0; i < t; i++) { n = nextLong(); k = nextLong(); if (n >= 32) { out.println("YES " + (n - 1)); } else { if (k > ma[(int)n]) { out.println("NO"); } else { for (int j = 0; j <= n; j++) { if (mi[(int)n - j] <= k && ma[(int)n] - l[(int)n - j + 1] * ma[j] >= k) { out.println("YES " + j); break; } if (j == n - 1) { out.println("NO"); } } } } } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.math.*; import java.text.*; import java.util.*; public class Main { public static void main(String args[]) { Scanner sca = new Scanner(System.in); long k,n; long ans; long[] pw = new long[33]; pw[1]=4; pw[0]=1; for(int i=2;i<=31;i++) pw[i]=pw[i-1]<<2; int t; t = sca.nextInt(); for(int cas=1;cas<=t;cas++) { n = sca.nextLong(); k = sca.nextLong(); ans = n; long last, path = 1; for (int i = 0; ; i++) { if ((pw[i + 1] - 1) / 3 > k) { ans -= i; last = k - (pw[i] - 1) / 3; break; } path *= 2; } long sp = path * 2 - 1; if (ans < 0 || (ans == 0 && last > 0)) { System.out.println("NO"); continue; } BigInteger sq = BigInteger.valueOf(path).multiply(BigInteger.valueOf(path)).subtract(BigInteger.valueOf(sp)); if (ans == 1 && sq.compareTo(BigInteger.valueOf(last))==-1 && last < sp) { System.out.println("NO"); continue; } else if (ans == 1 && last >= sp) { ans--; } System.out.println("YES "+ans); } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.*; import java.util.StringTokenizer; import static java.lang.Math.max; import static java.lang.Math.min; public class Main { FastScanner in; PrintWriter out; void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new Main().run(); } void solve() { int t = in.nextInt(); for (int sdfsdf = 0; sdfsdf < t; sdfsdf++) { long n = in.nextLong(); long k = in.nextLong(); if (n == 1) { if (k == 1) { out.println("YES 0"); } else { out.println("NO"); } continue; } if (k == 3) { if (n == 2) { out.println("NO"); } else { out.println("YES " + (n - 1)); } continue; } long cuts = 1; long squares = 4; int zoom = 1; while (k > cuts + squares) { cuts += squares; squares *= 4; zoom++; } if (zoom > n) { out.println("NO"); continue; } if (zoom == n && k > cuts) { out.println("NO"); continue; } long current_cuts = k - cuts; if (current_cuts > squares - (2L * Math.sqrt(squares) - 1L)) { out.println("YES " + (n - zoom - 1L)); } else { out.println("YES " + (n - zoom)); } } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.awt.List; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Random; import java.util.TreeSet; public final class CF_524_D2_D { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} // Global vars static BufferedWriter out; static InputReader reader; static long mod=1000000007; static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader=new InputReader(System.in); long mymax=1L<<62; log(mymax); long cut=0; int it=0; long squares=1; int GX=32; long[] maxgen=new long[GX]; while (cut<2000000000000000000L){ maxgen[it]=cut; //log("squares:"+squares+" cut:"+cut+" it:"+it+" size:"+(1L<<it)); it++; cut=1+4*cut; squares*=4; } //log(maxgen); int T=reader.readInt(); for (int t=0;t<T;t++){ int n=reader.readInt(); long k=reader.readLong(); if (n>=GX){ output("YES "+(n-1)); } else { // do first cut long pieces=3; long minc=1; int size=n-1; long maxc=1+maxgen[size]; while (size>0 && maxc<k){ minc+=pieces; maxc+=pieces+maxgen[size-1]*(2*pieces-1); size--; pieces=2*pieces+1; } if (minc<=k && maxc>=k){ output("YES "+size); } else { output("NO"); //log("//check:"+maxc+" "+maxgen[n]); } //log("size:"+size+" minc:"+minc+" maxc:"+maxc); } } try { out.close(); } catch (Exception EX){} } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res=new StringBuilder(); do { res.append((char)c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
logn
1080_D. Olya and magical square
CODEFORCES
//package round524; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class D { InputStream is; PrintWriter out; String INPUT = ""; long I = 4000000000000000007L; void solve() { // 1 5 13 outer: for(int T = ni();T > 0;T--){ long n = nl(), K = nl(); long inf = 0; long sup = 0; for(int d = 1;d <= n;d++){ inf += pow(2,d)-1; if(inf >= I)inf = I; sup += pow(2,d)-1 + mul(pow(2,d+1)-3, (pow(4,n-d)-1)/3); if(sup >= I)sup = I; // tr(d, inf, sup); if(inf <= K && K <= sup){ out.println("YES " + (n-d)); continue outer; } } out.println("NO"); } } long mul(long a, long b) { if((double)a*b > I)return I; return a*b; } long pow(int b, long d) { long v = 1; for(int i = 1;i <= d;i++){ if((double)v*b > I)return I; v = v * b; } return v; } 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 D().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)); } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.*; import java.math.BigInteger; import java.util.StringTokenizer; import java.util.function.Function; public class D { public static void main(String[] args) throws IOException { try (Input input = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) { long[] s = new long[40]; for (int i = 1; i < s.length; i++) { s[i] = 1 + 4 * s[i - 1]; if (i >= 32) { s[i] = Long.MAX_VALUE; } } Function<Integer, Long> getS = (i) -> (i < s.length) ? s[i] : Long.MAX_VALUE; int t = input.nextInt(); testCase: for (int tt = 0; tt < t; tt++) { int n = input.nextInt(); long k = input.nextLong(); long kk = 1; BigInteger maxDivisions = BigInteger.ZERO; for (int division = 1; division <= n; division++) { long needToDivide = (1L << division) - 1; if (needToDivide > k) { writer.println("NO"); continue testCase; } k -= needToDivide; maxDivisions = maxDivisions.add(BigInteger.valueOf(kk).multiply(BigInteger.valueOf(getS.apply(n - division)))); if (maxDivisions.compareTo(BigInteger.valueOf(k)) >= 0) { writer.println("YES " + (n - division)); continue testCase; } kk += (1L << division + 1); } writer.println("NO"); } } } interface Input extends Closeable { String next() throws IOException; default int nextInt() throws IOException { return Integer.parseInt(next()); } default long nextLong() throws IOException { return Long.parseLong(next()); } } private static class StandardInput implements Input { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer stringTokenizer; @Override public void close() throws IOException { reader.close(); } @Override public String next() throws IOException { if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.*; import java.util.*; import java.util.LinkedList; import java.math.*; import java.lang.*; import java.util.PriorityQueue; import static java.lang.Math.*; @SuppressWarnings("unchecked") public class Solution implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long min(long a,long b) { if(a>b) { return b; } return a; } public static int min(int a,int b) { if(a>b) { return b; } return a; } public static long max(long a,long b) { if(a>b) { return a; } return b; } public static int max(int a,int b) { if(a>b) { return a; } return b; } static class pair { long x; long y; pair(long x,long y) { this.x = x; this.y = y; } public String toString() { return x+" "+y; } } public static int gcd(int a,int b) { if(a==0) return b; if(b==0) return a; while((a%=b)!=0&&(b%=a)!=0); return a^b; } static int num = (int)1e6; public static int random(int min,int max) { return min+(int)((max-min)*Math.random()); } float min(float a,float b) { if(a>b) { return b; } return a; } float dist(float x1,float y1,float x2,float y2) { return (float)Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); } float mod(float x) { if(x>0) { return x; } return -x; } public static long pow(long n,int pow) { long res = 1; while(pow!=0) { if((pow&1)==1) { res *= n; } n *= n; pow = pow>>1; } return res; } public static int bsearch(int n,long k) { int l = 1; int r = n; while(r>l) { int mid = (l+r+1)>>1; if(pow(2,mid+1)-mid-2<=k) { l = mid; } else { r = mid-1; } } if(pow(2,l+1)-l-2==0&&pow(2,l+1)-l-2==k) { return 0; } else if(pow(2,l+1)-l-2<=k) { return l; } return 0; } public static boolean valid(int n,long k,int steps) { long total_max = (pow(4,n)-1)/3; long cant_be = ((pow(4,n-steps)-1)/3)*(pow(2,steps+1)-1); long available = total_max-cant_be; if(available>=k) { return true; } return false; } public static void main(String args[]) throws Exception { new Thread(null, new Solution(),"Main",1<<26).start(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t1 = sc.nextInt(); while(t1-->0) { int n = sc.nextInt(); long k = sc.nextLong(); if(n>31) { out.println("YES "+(n-1)); continue; } int steps = bsearch(n,k); if(steps==0) { if(k==0) out.println("YES "+n); else out.println("NO"); } if(valid(n,k,steps)) { out.println("YES "+(n-steps)); } else { out.println("NO"); } } out.close(); } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; public class Main { static class Task { int NN = 500005; int MOD = 1000000007; int INF = 2000000000; long INFINITY = 2000000000000000000L; public void solve(InputReader in, PrintWriter out) { int t = in.nextInt(); while(t-->0) { long n = in.nextLong(); long k = in.nextLong(); if(n < 32 && k > ((1L<<(2L*n))-1L)/3L) { out.println("NO");continue; } if(n == 2 && k == 3) { out.println("NO");continue; } if(n >= 32) { out.println("YES "+ (n-1));continue; } boolean done = false; for(long i=1;i<=n;++i) { if(k < (1L<<(i+2L))-i-3L) { done = true; out.println("YES " + (n - i));break; } } if(!done) { out.println("YES 0"); } } } } static void prepareIO(boolean isFileIO) { //long t1 = System.currentTimeMillis(); Task solver = new Task(); // Standard IO if(!isFileIO) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver.solve(in, out); //out.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0); out.close(); } // File IO else { String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in"; String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out"; InputReader fin = new InputReader(IPfilePath); PrintWriter fout = null; try { fout = new PrintWriter(new File(OPfilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } solver.solve(fin, fout); //fout.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0); fout.close(); } } public static void main(String[] args) { prepareIO(false); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public InputReader(String filePath) { File file = new File(filePath); try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class OlyaAndMagicalSquare { public static void solveCase(FastIO io) { int N = io.nextInt(); long K = io.nextLong(); CountMap cm = new CountMap(); cm.increment(N, BigInteger.ONE); long rem = K; int moves = 1; int sqSize = N; while (sqSize > 0) { long need = (1L << moves) - 1; BigInteger biNeed = BigInteger.valueOf(need); cm.decrement(sqSize, biNeed); if (need > rem) { break; } cm.increment(sqSize - 1, biNeed.multiply(BigInteger.valueOf(4))); rem -= need; ++moves; --sqSize; } BigInteger biRem = BigInteger.valueOf(rem); for (int i = N; i > 0; --i) { BigInteger have = cm.getCount(i); if (have.compareTo(biRem) >= 0) { biRem = BigInteger.ZERO; break; } biRem = biRem.subtract(have); cm.decrement(i, have); cm.increment(i - 1, have.multiply(BigInteger.valueOf(4))); } if (biRem.equals(BigInteger.ZERO)) { io.printf("YES %d\n", sqSize); } else { io.println("NO"); } } private static class CountMap extends HashMap<Integer, BigInteger> { public void increment(int k, BigInteger v) { put(k, getCount(k).add(v)); } public void decrement(int k, BigInteger v) { BigInteger next = getCount(k).subtract(v); if (next.equals(BigInteger.ZERO)) { remove(k); } else { put(k, next); } } public BigInteger getCount(int k) { return getOrDefault(k, BigInteger.ZERO); } } public static void solve(FastIO io) { int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin (t.me/musin_acm) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); DOlyaIMagicheskiiKvadrat solver = new DOlyaIMagicheskiiKvadrat(); solver.solve(1, in, out); out.close(); } static class DOlyaIMagicheskiiKvadrat { long inf = (long) 1e18 + 1; long[] maxLen; public void solve(int testNumber, InputReader in, OutputWriter out) { maxLen = new long[100]; maxLen[1] = 0; for (int i = 1; i < maxLen.length; i++) { maxLen[i] = Math.min(inf, maxLen[i - 1] * 4 + 1); } if (false) { for (int n = 1; n <= 3; n++) { for (int k = 1; k <= maxSplitCount(n) + 20; k++) { out.print(n + " " + k + " "); int res = solve(n, k); if (res == -1) { out.printLine("NO"); } else { out.printLine("YES " + res); } } } return; } int q = in.readInt(); while (q-- > 0) { int n = in.readInt(); long k = in.readLong(); int res = solve(n, k); if (res == -1) { out.printLine("NO"); continue; } out.printLine("YES " + res); } } long maxSplitCount(int n) { if (n >= maxLen.length) { return inf; } return maxLen[n]; } int solve(int n, long k) { if (maxSplitCount(n) < k) { return -1; } int at = 0; while (maxSplitCount(at + 1) <= k) { at++; } int curSideLog = n - at; k -= maxSplitCount(at); double sideLen = Math.pow(2, n - curSideLog); double pathLen = sideLen * 2 - 1; if (curSideLog > 0 && pathLen <= k) { return curSideLog - 1; } double area = sideLen * sideLen; double otherArea = area - pathLen; if (otherArea * (double) maxSplitCount(curSideLog) >= k) { return curSideLog; } return -1; } } 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 long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author kessido */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DOlyaAndMagicalSquare solver = new DOlyaAndMagicalSquare(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class DOlyaAndMagicalSquare { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.NextInt(); long k = in.NextLong(); if (k == 0) { out.println("YES " + n); return; } long operationTillNow = 0, numberOfCubeOnTheSide = 1; ArrayList<CubeCount> cubes = new ArrayList<>(); for (int i = n - 1; i >= 0; i--) { cubes.add(new CubeCount(i, (numberOfCubeOnTheSide - 1) * 2 * 2 + 1)); operationTillNow = operationTillNow + 2 * numberOfCubeOnTheSide - 1; numberOfCubeOnTheSide *= 2; long operationLeft = k - operationTillNow; if (operationLeft == 0) { out.println("YES " + i); return; } else if (operationLeft < 0) { out.println("NO"); return; } for (CubeCount c : cubes) { if (!c.hasLessThen(operationLeft)) { out.println("YES " + i); return; } else { operationLeft = c.removeMeFrom(operationLeft); } } if (operationLeft <= 0) { out.println("YES " + i); return; } } out.println("NO"); return; } class CubeCount { int sideSizeLogScale; long repeats; public CubeCount(int sideSizeLogScale, long repeats) { this.repeats = repeats; this.sideSizeLogScale = sideSizeLogScale; } public boolean hasLessThen(long k) { return hasLessThen(k, sideSizeLogScale, repeats); } private boolean hasLessThen(long k, int sideLog, long repeats) { while (true) { if (k <= 0) return false; if (sideLog == 0) return true; k -= repeats; sideLog--; repeats *= 4; } } public long removeMeFrom(long k) { return removeMeFrom(k, sideSizeLogScale, repeats); } private long removeMeFrom(long k, int sideLog, long repeats) { while (true) { if (sideLog == 0) return k; k -= repeats; sideLog--; repeats *= 4; } } } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine(), " \t\n\r\f,"); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int NextInt() { return Integer.parseInt(next()); } public long NextLong() { return Long.parseLong(next()); } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); // System.err.println(f(1)); // System.err.println(f(4)); int tc = sc.nextInt(); out: while(tc-->0){ long n = sc.nextInt(); long k = sc.nextLong(); if(n >= 32){ pw.println("YES " + (n-1)); continue; } long steps = 0; for (int i = 1;; i++) { long cnt = ((1l<<(i+1))-1); steps += ((1l<<(i))-1); if(steps > k) break; if(steps > f(n)) break; // long rem = k-((1<<i)-1); long rem = k-steps; // System.err.println("steps:" + steps + " cnt:" + cnt + " f:" + f(n-i)); // System.err.println("rem: " + (f(n) - steps - cnt*f(n-i))); if(rem <= f(n) - steps - cnt*f(n-i)){ pw.println("YES " + (n-i)); continue out; } } pw.println("NO"); } pw.flush(); pw.close(); } static long f(long n){ if(n == 0) return 0; long ans = 0; for (int i = 0; i < n; i++) { ans += 1l<<(2*i); } return ans; } static int[][] matMul(int[][] A, int[][] B, int p, int q, int r) //C(p x r) = A(p x q) x (q x r) -- O(p x q x r) { int[][] C = new int[p][r]; for(int i = 0; i < p; ++i) for(int j = 0; j < r; ++j) for(int k = 0; k < q; ++k) C[i][j] += A[i][k] * B[k][j]; return C; } /* * 4. Square Matrix Exponentiation */ static int[][] matPow(int[][] base, int p) { int n = base.length; int[][] ans = new int[n][n]; for(int i = 0; i < n; i++) ans[i][i] = 1; while(p != 0) { if((p & 1) == 1) ans = matMul(ans, base, n, n, n); base = matMul(base, base, n, n, n); p >>= 1; } return ans; } static int[][] packU(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) p[f]++; for (int t : to) p[t]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } static int pow(int n, int p){ int ans = 1; for (int i = 0; i < p; i++) { ans *= n; } return ans; } static int[][] packD(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) if(f != -1) p[f]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) if(from[i] != -1) {g[from[i]][--p[from[i]]] = to[i];} return g; } static void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int)(Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s)));} public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();} public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class OlyaAndMagicalSquare { public static void solveCase(FastIO io) { int N = io.nextInt(); long K = io.nextLong(); CountMap cm = new CountMap(); cm.increment(N, BigInteger.ONE); long rem = K; int moves = 1; int sqSize = N; while (sqSize > 0) { long need = (1L << moves) - 1; BigInteger biNeed = BigInteger.valueOf(need); cm.decrement(sqSize, biNeed); if (need > rem) { break; } cm.increment(sqSize - 1, biNeed.multiply(BigInteger.valueOf(4))); rem -= need; ++moves; --sqSize; } BigInteger biRem = BigInteger.valueOf(rem); for (int i = N; i > 0; --i) { BigInteger have = cm.getCount(i); if (have.compareTo(biRem) >= 0) { biRem = BigInteger.ZERO; break; } biRem = biRem.subtract(have); cm.decrement(i, have); cm.increment(i - 1, have.multiply(BigInteger.valueOf(4))); } if (biRem.equals(BigInteger.ZERO)) { io.printf("YES %d\n", sqSize); } else { io.println("NO"); } // long N = io.nextLong(); // long K = io.nextLong(); // // io.println(1L << 62); // boolean good; // if (N >= 31) { // good = true; // } else { // good = ((1L << (N << 1)) / 3 >= K); // } // if (!good) { // io.println("NO"); // return; // } // int split = getMaxSplit(K); // if (N >= 40) { // io.printf("YES %d\n", N - split); // return; // } // long used = (1L << split) - 1; // long rem = K - used; } private static class CountMap extends HashMap<Integer, BigInteger> { public void increment(int k, BigInteger v) { put(k, getCount(k).add(v)); } public void decrement(int k, BigInteger v) { BigInteger next = getCount(k).subtract(v); if (next.equals(BigInteger.ZERO)) { remove(k); } else { put(k, next); } } public BigInteger getCount(int k) { return getOrDefault(k, BigInteger.ZERO); } } private static int getMaxSplit(long k) { for (int i = 1;; ++i) { if ((1L << (i + 1)) - 2 - i > k) { return i - 1; } } } public static void solve(FastIO io) { int T = io.nextInt(); for (int t = 0; t < T; ++t) { solveCase(io); } } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.util.Scanner; public class Solution { public static void main(String[] args) { Solution solution = new Solution(); solution.solve(); } private void solve() { Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t -- > 0) { long n = in.nextLong(); long k = in.nextLong(); System.out.println(solve(n, k)); } } private String solve(long n, long k) { if (n > 31) return "YES " + (n - 1); if (k > f(n)) return "NO"; long square = 1; long splitDone = 0; long size = n; long splitLeft = 0; while (splitDone + square <= k && size > 0) { splitDone += square; --size; splitLeft += (square * 2 - 1) * f(size); square = square * 2 + 1; } // System.out.println(square + " " + splitDone + " " + size + " " + splitLeft); if (k > splitDone + splitLeft) return "NO"; else return "YES " + size; } private long f(long x) { return ((1L << (2 * x)) - 1) / 3; } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.util.*; import java.io.*; // Solution public class Main { public static void main (String[] argv) { new Main(); } boolean test = false; final int MOD = 998244353; public Main() { FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); //FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in"))); final int N = 50; //big enough long[] f = new long[N]; int maxN = 50; f[0] = 0; for (int i = 1; i < N; i++) { if (Long.MAX_VALUE / 4 <= f[i-1]) { maxN = i - 1; break; } f[i] = f[i-1] * 4 + 1; } long[] a = new long[N]; long[] b = new long[N]; int nt = in.nextInt(); for (int ii = 1; ii <= nt; ii++) { int n = in.nextInt(); long k = in.nextLong(); if (k == 0) { System.out.println("YES " + n); continue; } if (n - 1> maxN || k <= 1 + f[n-1]) { System.out.println("YES " + (n - 1)); continue; } if (n - 1 == maxN) { System.out.println("YES " + (n - 2)); continue; } // now: n <= maxN if (k > f[n]) { System.out.println("NO"); continue; } if (n == 2) { if (k==3) System.out.println("NO"); else System.out.println("YES 0"); continue; } a[1] = 1; b[1] = f[n-1]; int ret = 0; for (int i = 2; i <= n; i++) { a[i] = a[i-1] + (1L << i) - 1; b[i] = b[i-1] + (2 * (1L << i) - 3) * f[n-i]; if (a[i] + b[i] >= k) { ret = n - i; break; } } System.out.println("YES " + ret); } } private int dist(int x, int y, int xx, int yy) { return abs(x - xx) + abs(y - yy); } private boolean less(int x, int y, int xx, int yy) { return x < xx || y > yy; } private int mul(int x, int y) { return (int)(1L * x * y % MOD); } private int add(int x, int y) { return (x + y) % MOD; } private int nBit1(int v) { int v0 = v; int c = 0; while (v != 0) { ++c; v = v & (v - 1); } return c; } private long abs(long v) { return v > 0 ? v : -v; } private int abs(int v) { return v > 0 ? v : -v; } private int common(int v) { int c = 0; while (v != 1) { v = (v >>> 1); ++c; } return c; } private void reverse(char[] a, int i, int j) { while (i < j) { swap(a, i++, j--); } } private void swap(char[] a, int i, int j) { char t = a[i]; a[i] = a[j]; a[j] = t; } private int gcd(int x, int y) { if (y == 0) return x; return gcd(y, x % y); } private long gcd(long x, long y) { if (y == 0) return x; return gcd(y, x % y); } private int max(int a, int b) { return a > b ? a : b; } private long max(long a, long b) { return a > b ? a : b; } private int min(int a, int b) { return a > b ? b : a; } private long min(long a, long b) { return a > b ? b : a; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(BufferedReader in) { br = in; } String next() { while (st == null || !st.hasMoreElements()) { try { String line = br.readLine(); if (line == null || line.length() == 0) return ""; st = new StringTokenizer(line); } catch (IOException e) { return ""; //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) { return ""; //e.printStackTrace(); } return str; } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class OlyaAndMagicalSquare { void solve() { long[] dp = new long[32]; dp[0] = 0; for (int i = 1; i < 32; i++) { dp[i] = 4 * dp[i - 1] + 1; } int T = in.nextInt(); L: while (T-- > 0) { int n = in.nextInt(); long k = in.nextLong(); if (n > 31) { out.println("YES " + (n - 1)); continue; } long tot = 0; for (int a = n - 1; a >= 0; a--) { k -= (1L << (n - a)) - 1; if (k < 0) break; if (k == 0) { out.println("YES " + a); continue L; } long limit = (1L << (n + 1 - a)) - 3; if (k <= tot || dp[a] > 0 && (k - tot + dp[a] - 1) / dp[a] <= limit) { out.println("YES " + a); continue L; } tot += dp[a] * limit; } out.println("NO"); } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new OlyaAndMagicalSquare().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()); } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws FileNotFoundException { ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out)); // String fileName = "C-large-practice"; // ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".out"))); new Main(io).solve(); // new Main(io).solveLocal(); io.close(); } ConsoleIO io; Main(ConsoleIO io) { this.io = io; } ConsoleIO opt; Main(ConsoleIO io, ConsoleIO opt) { this.io = io; this.opt = opt; } List<List<Integer>> gr = new ArrayList<>(); long MOD = 1_000_000_007; public void solve() { StringBuilder sb = new StringBuilder(); int q = io.ri(); for(int i = 0; i < q; i++){ long n = io.readLong(); long k = io.readLong(); if(i>0)sb.append(System.lineSeparator()); boolean done = false; if(n==2 && k == 3){ sb.append("NO"); done = true; } for(int p = 0;n>0 && !done;p++, n--){ long count = (1L << (p*2)); if(k>count){ k-=count; }else{ long path = p==0?1:(1L<<(p-1))*2+((1L<<(p-1))-1)*2+1; if(k<path){ sb.append("YES " + n); }else{ sb.append("YES " + (n-1)); } done = true; } } if(!done){ sb.append("NO"); } } io.writeLine(sb.toString()); } } class ConsoleIO { BufferedReader br; PrintWriter out; public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;} public void flush(){this.out.flush();} public void close(){this.out.close();} public void writeLine(String s) {this.out.println(s);} public void writeInt(int a) {this.out.print(a);this.out.print(' ');} public void writeWord(String s){ this.out.print(s); } public void writeIntArray(int[] a, int k, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { if (i > 0) sb.append(separator); sb.append(a[i]); } this.writeLine(sb.toString()); } public void writeLongArray(long[] a, int k, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { if (i > 0) sb.append(separator); sb.append(a[i]); } this.writeLine(sb.toString()); } public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }} public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}} public long[] readLongArray() { String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length]; for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]); return r; } public int[] readIntArray() { String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length]; for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]); return r; } public int[] readIntArray(int n) { int[] res = new int[n]; char[] all = this.readLine().toCharArray(); int cur = 0;boolean have = false; int k = 0; boolean neg = false; for(int i = 0;i<all.length;i++){ if(all[i]>='0' && all[i]<='9'){ cur = cur*10+all[i]-'0'; have = true; }else if(all[i]=='-') { neg = true; } else if(have){ res[k++] = neg?-cur:cur; cur = 0; have = false; neg = false; } } if(have)res[k++] = neg?-cur:cur; return res; } public int ri() { try { int r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public long readLong() { try { long r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public String readWord() { try { boolean start = false; StringBuilder sb = new StringBuilder(); while (true) { int c = br.read(); if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') { sb.append((char)c); start = true; } else if (start || c == -1) return sb.toString(); } } catch (Exception ex) { return ""; } } public char readSymbol() { try { while (true) { int c = br.read(); if (c != ' ' && c != '\r' && c != '\n' && c != '\t') { return (char) c; } } } catch (Exception ex) { return 0; } } //public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }} } class Pair { public Pair(int a, int b) {this.a = a;this.b = b;} public int a; public int b; } class PairLL { public PairLL(long a, long b) {this.a = a;this.b = b;} public long a; public long b; } class Triple { public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;} public int a; public int b; public int c; }
logn
1080_D. Olya and magical square
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 x1080D { public static void main(String hi[]) throws Exception { long[] dp = new long[32]; for(int i=1; i <= 31; i++) dp[i] = 1+4*dp[i-1]; BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); matcha:while(T-->0) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); long K = Long.parseLong(st.nextToken()); if(N >= 32 || K == 1) sb.append("YES "+(N-1)+"\n"); else if(dp[N] == K) sb.append("YES 0\n"); else if(dp[N] < K) sb.append("NO\n"); else { long total = 3L; long length = 2; for(int res=N-1; res >= 0; res--) { long min = 1+3*dp[N-1-res]; long max = min+dp[N-1]; long cansplit = total-2*length+1; max += dp[res]*cansplit; if(min <= K && K <= max) { sb.append("YES "+res+"\n"); continue matcha; } length <<= 1; total *= 4; } sb.append("NO\n"); } } System.out.print(sb); } }
logn
1080_D. Olya and magical square
CODEFORCES
//package que_a; import java.io.*; import java.util.*; import java.math.*; public class utkarsh { InputStream is; PrintWriter out; long mod = (long)(1e9 + 7), inf = (long)(3e18); void solve() { //SZ = sieve(); //SZ = 1000001; int q = ni(); while(q-- > 0) { long n = nl(), k = nl(); if(n <= 31) { long m = (long)(Math.pow(4, n)); long x = (m - 1) / 3; if(k > x) { out.println("NO"); continue; } long b = 0, p = 1, d = 1; x = 2; while(k > b) { n--; k -= p; m /= 4; if(m == 0) break; b += d * (m - 1) / 3; p += x; x <<= 1; d += x; } out.println((n >= 0 && k >= 0 && k <= b) ? ("YES "+ n) : "NO"); } else { out.println("YES "+ (n-1)); } } } long mp(long b, long e, long mod) { b %= mod; long r = 1; while(e > 0) { if((e & 1) == 1) { r *= b; r %= mod; } b *= b; b %= mod; e >>= 1; } return r; } //---------- I/O Template ---------- public static void main(String[] args) { new utkarsh().run(); } void run() { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.io.*; import java.util.*; public class E implements Runnable { public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();} long oo = (long)2e18; public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println("Go!"); int t = fs.nextInt(); while(t-->0) { int n = fs.nextInt(); long k = fs.nextLong(); long toCut = 1, numSquares = 1, free = 0; int cuts = 0; while(true) { if(cuts >= n) { k = oo; break; } k -= toCut; if(k < 0) { k = oo; break; } cuts++; try { free = Math.addExact(free, Math.multiplyExact(numSquares, getVal(n-cuts))); } catch (Exception e) { k = 0; break; } if(free >= k) { k = 0; break; } toCut += (1L<<cuts); numSquares += (1L<<(cuts+1)); } if(k == 0) { out.printf("YES %d\n", n-cuts); } else { out.printf("NO\n"); } } out.close(); } long getVal(int n) { if(n > 31) return oo; long last = 0, cur = 0; for(int i = 1; i <= n; i++) { cur = 1 + 4*last; last = cur; } return cur; } 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) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } } }
logn
1080_D. Olya and magical square
CODEFORCES
import java.util.*; import java.io.*; public class code { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int q = sc.nextInt(); long[] d = new long[30]; d[0] = 1; for(int i=1;i<30;i++) d[i] = d[i-1]*4; for(int z=0;z<q;z++){ long r = 0; long n = sc.nextLong(); long k = sc.nextLong(); long c = 1; while(k>0&&n>=1){ if(k<=r) { k=0; break; } n--; k-=c; if(k<=0) break; if(n>30) { k=0; break; } for(int i=0;i<(int)n;i++){ r += d[i]*(c*2-1); if(k<=r) { k=0; break; } } if(k<=r) { k=0; break; } c*=2; c++; } if(k==0) System.out.println("YES "+n); else System.out.println("NO"); } } } /* NO YES 0 YES 0 NO NO YES 999999942 YES 59 YES 63 YES 2 NO YES 1 YES 1 NO NO YES 0 YES 0*/
logn
1080_D. Olya and magical square
CODEFORCES
//package round503; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class B2 { Scanner in; PrintWriter out; String INPUT = ""; // 12123432 // 12343212 int qc = 0; int n; int[] table; int val(int x) { if(table[x] != Integer.MIN_VALUE)return table[x]; if(qc > 60)throw new RuntimeException(); out.println("? " + (x+1)); out.flush(); table[x] = ni(); if(table[x] == table[(x+table.length/2) % table.length]){ if(x >= n/2)x -= n/2; out.println("! " + (x+1)); out.flush(); throw new IllegalStateException(); } return table[x]; } void solve() { n = ni(); if(n % 4 != 0){ out.println("! -1"); out.flush(); return; } table = new int[n]; Arrays.fill(table, Integer.MIN_VALUE); Random gen = new Random(1); try{ outer: while(true){ int pu = gen.nextInt(n); int pd = (pu+n/2)%n; int pl = (pu + gen.nextInt(n/2-1)+1)%n; int pr = (pl+n/2)%n; int vu = val(pu), vd = val(pd); int vl = val(pl), vr = val(pr); if(cross(vu, vl, vd, vr)){ }else if(cross(vu, vr, vd, vl)){ int npu = pr, npl = pu; int npd = pl, npr = pd; pu = npu; pl = npl; pd = npd; pr = npr; vu = val(pu); vl = val(pl); vd = val(pd); vr = val(pr); }else{ continue outer; } // u-l d-r while(true){ int pul = h(pu, pl, n); int vul = val(pul); int pdr = h(pd, pr, n); int vdr = val(pdr); if(cross(vul, vu, vdr, vd)){ pl = pul; vl = vul; pr = pdr; vr = vdr; }else{ pu = pul; vu = vul; pd = pdr; vd = vdr; } } } }catch(IllegalStateException e) { } } int h(int a, int b, int n) { if(a > b){ b += n; } int u = (a+b)/2; if(u >= n)u -= n; return u; } boolean cross(int a, int b, int c, int d) { return Integer.signum(c-a) != Integer.signum(d-b); } void run() throws Exception { in = oj ? new Scanner(System.in) : new Scanner(INPUT); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new B2().run(); } int ni() { return Integer.parseInt(in.next()); } long nl() { return Long.parseLong(in.next()); } double nd() { return Double.parseDouble(in.next()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } } //
logn
1019_B. The hat
CODEFORCES
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class B { public static PrintWriter out; public static BufferedReader bf; public static int n; public static int[] a; public static void main(String[] args) throws Exception { bf = new BufferedReader(new InputStreamReader(System.in)); // Scanner scan = new Scanner(System.in); out = new PrintWriter(new OutputStreamWriter(System.out)); n = Integer.parseInt(bf.readLine()); a = new int[n]; Arrays.fill(a, Integer.MAX_VALUE); if((n/2) % 2 != 0) { out.println("! " + (-1)); out.flush(); out.close(); System.exit(0); } ask(0); ask(opp(0)); int low = 0; int high = opp(0); while(true) { int test = (low + high)/2; ask(test); ask(opp(test)); int l_1 = a[low]; int l_2 = a[test]; int r_1 = a[opp(low)]; int r_2 = a[opp(test)]; if(1L*(l_1 - r_1)*(l_2 - r_2) < 0L) { high = test; } else low = test; } // StringTokenizer st = new StringTokenizer(bf.readLine()); // int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); // int n = Integer.parseInt(st.nextToken()); // int n = scan.nextInt(); //out.close(); System.exit(0); } public static int ask(int i) throws Exception { // 0 thru n-1; out.println("? " + (i+1)); out.flush(); int k = Integer.parseInt(bf.readLine()); a[i] = k; if(a[i] == a[opp(i)]) { out.println("! " + (i+1)); out.flush(); out.close(); System.exit(0); } return k; } public static int opp(int k) { return ((k + n/2) % n); } }
logn
1019_B. The hat
CODEFORCES
import java.util.*; import java.io.*; public class CFB { static int n; static FastScanner in; public static void main(String[] args) throws Exception { in = new FastScanner(System.in); n = in.nextInt(); int a = query(1); if(((a % 2)+2) % 2== 1){ System.out.println("! -1"); return; } if(a == 0){ System.out.println("! 1"); return; } bins(1 , n/2 + 1 , a , -a); } static void bins(int lo , int hi , int losign , int hisign){ int mid = (lo + hi)/2; int k = query(mid); if(k == 0){ System.out.println("! " + mid); System.exit(0); } if(k > 0 && losign > 0 || k < 0 && losign < 0){ bins(mid , hi , k , hisign); } else { bins(lo , mid , losign , k); } } static int query(int i){ System.out.println("? " + i); int a1 = in.nextInt(); System.out.println("? " + ((i + (n/2)) > n ? (i - (n/2)) : (i + (n/2)))); int a2 = in.nextInt(); return a1 - a2; } static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
logn
1019_B. The hat
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author lewin */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); BTheHat solver = new BTheHat(); solver.solve(1, in, out); out.close(); } static class BTheHat { InputReader in; OutputWriter out; int n; int ask(int student) { student %= n; out.println("? " + (student + 1)); out.flush(); return in.nextInt(); } public void solve(int testNumber, InputReader in, OutputWriter out) { this.in = in; this.out = out; n = in.nextInt(); int a = ask(0), b = ask(n / 2); if ((a + b) % 2 != 0) { out.println("! -1"); out.flush(); return; } if (a == b) { out.println("! 1"); out.flush(); return; } int lo = 0, hi = n / 2; while (lo < hi) { int mid = (lo + hi) / 2; int f1 = ask(mid), f2 = ask(mid + n / 2); if (f1 == f2) { out.println("! " + (mid + 1)); return; } if ((a > b) == (f1 > f2)) { lo = mid + 1; } else { hi = mid - 1; } } out.println("! " + (lo + 1)); out.flush(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
logn
1019_B. The hat
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.BufferedReader; import java.io.Reader; 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; MyInput in = new MyInput(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { int n; MyInput in; PrintWriter out; public void solve(int testNumber, MyInput in, PrintWriter out) { this.in = in; this.out = out; n = in.nextInt(); if (n / 2 % 2 == 1) { answer(-1); return; } int low = 0, high = n / 2; int diff = query(low + n / 2) - query(low); while (diff != 0) { int mid = (low + high) / 2; int d = query(mid + n / 2) - query(mid); if (d == 0 || diff > 0 == d > 0) { diff = d; low = mid; } else { high = mid; } } answer(low); } int query(int i) { out.println("? " + (i % n + 1)); out.flush(); return in.nextInt(); } void answer(int i) { out.println("! " + (i < 0 ? i : (i % n + 1))); } } static class MyInput { private final BufferedReader in; private static int pos; private static int readLen; private static final char[] buffer = new char[1024 * 8]; private static char[] str = new char[500 * 8 * 2]; private static boolean[] isDigit = new boolean[256]; private static boolean[] isSpace = new boolean[256]; private static boolean[] isLineSep = new boolean[256]; static { for (int i = 0; i < 10; i++) { isDigit['0' + i] = true; } isDigit['-'] = true; isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true; isLineSep['\r'] = isLineSep['\n'] = true; } public MyInput(InputStream is) { in = new BufferedReader(new InputStreamReader(is)); } public int read() { if (pos >= readLen) { pos = 0; try { readLen = in.read(buffer); } catch (IOException e) { throw new RuntimeException(); } if (readLen <= 0) { throw new MyInput.EndOfFileRuntimeException(); } } return buffer[pos++]; } public int nextInt() { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); int i = 0; int ret = 0; if (str[0] == '-') { i = 1; } for (; i < len; i++) ret = ret * 10 + str[i] - '0'; if (str[0] == '-') { ret = -ret; } return ret; } public char nextChar() { while (true) { final int c = read(); if (!isSpace[c]) { return (char) c; } } } int reads(int len, boolean[] accept) { try { while (true) { final int c = read(); if (accept[c]) { break; } if (str.length == len) { char[] rep = new char[str.length * 3 / 2]; System.arraycopy(str, 0, rep, 0, str.length); str = rep; } str[len++] = (char) c; } } catch (MyInput.EndOfFileRuntimeException e) { } return len; } static class EndOfFileRuntimeException extends RuntimeException { } } }
logn
1019_B. The hat
CODEFORCES