src
stringlengths
95
64.6k
complexity
stringclasses
7 values
problem
stringlengths
6
50
from
stringclasses
1 value
import java.lang.*; import java.math.BigInteger; import java.io.*; import java.util.*; public class Solution implements Runnable{ public static BufferedReader br; public static PrintWriter out; public static StringTokenizer stk; public static boolean isStream = true; public static void main(String[] args) throws IOException { if (isStream) { br = new BufferedReader(new InputStreamReader(System.in)); } else { br = new BufferedReader(new FileReader("in.txt")); } out = new PrintWriter(System.out); new Thread(new Solution()).start(); } public void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } public String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public String nextWord() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return stk.nextToken(); } public Integer nextInt() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Integer.valueOf(stk.nextToken()); } public Long nextLong() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Long.valueOf(stk.nextToken()); } public Double nextDouble() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Double.valueOf(stk.nextToken()); } public Float nextFloat() { while (stk==null||!stk.hasMoreTokens()) loadLine(); return Float.valueOf(stk.nextToken()); } public void run() { int n = nextInt(); int[] arr = new int[n]; for (int i = 0; i < n;i++) { arr[i] = nextInt(); } Arrays.sort(arr); if (arr[n-1] != 1) arr[n-1] = 1; else arr[n-1] = 2; Arrays.sort(arr); for (int i = 0; i < n; i++) { out.print(arr[i]+" "); } out.println(); out.flush(); } }
nlogn
135_A. Replacement
CODEFORCES
//package round97; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = new int[n]; for(int i = 0;i < n;i++){ a[i] = ni(); } Arrays.sort(a); if(a[n-1] > 1){ a[n-1] = 1; Arrays.sort(a); }else{ a[n-1] = 2; } for(int i = 0;i < n;i++){ if(i > 0)out.print(" "); out.print(a[i]); } out.println(); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } public int ni() { try { int num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public long nl() { try { long num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public String ns() { try{ int b = 0; StringBuilder sb = new StringBuilder(); while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' ')); if(b == -1)return ""; sb.append((char)b); while(true){ b = is.read(); if(b == -1)return sb.toString(); if(b == '\r' || b == '\n' || b == ' ')return sb.toString(); sb.append((char)b); } } catch (IOException e) { } return ""; } public char[] ns(int n) { char[] buf = new char[n]; try{ int b = 0, p = 0; while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n')); if(b == -1)return null; buf[p++] = (char)b; while(p < n){ b = is.read(); if(b == -1 || b == ' ' || b == '\r' || b == '\n')break; buf[p++] = (char)b; } return Arrays.copyOf(buf, p); } catch (IOException e) { } return null; } double nd() { return Double.parseDouble(ns()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
nlogn
135_A. Replacement
CODEFORCES
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class C { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new C().run(); } public void run(){ try{ long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } void solve() throws IOException{ int n = readInt(); int[] a = new int[n]; for(int i = 0; i < n; i++){ a[i] = readInt(); } boolean c = true; for(int i = 0; i < n; i++){ if(a[i] != 1){ c = false; break; } } if(c){ for(int i = 0; i < n-1; i++){ out.print(a[i] + " "); } out.println(2); return; } Utils.mergeSort(a); out.print(1 + " "); for(int i = 1; i < n; i++){ out.print(a[i-1] + " "); } } int[] zFunction(char[] s){ int[] z = new int[s.length]; z[0] = 0; for (int i=1, l=0, r=0; i<s.length; ++i) { if (i <= r) z[i] = min (r-i+1, z[i-l]); while (i+z[i] < s.length && s[z[i]] == s[i+z[i]]) ++z[i]; if (i+z[i]-1 > r){ l = i; r = i+z[i]-1; } } return z; } int[] prefixFunction(char[] s){ int[] pr = new int[s.length]; for (int i = 1; i< s.length; ++i) { int j = pr[i-1]; while (j > 0 && s[i] != s[j]) j = pr[j-1]; if (s[i] == s[j]) ++j; pr[i] = j; } return pr; } int ModExp(int a, int n, int mod){ int res = 1; while (n!=0) if ((n & 1) != 0) { res = (res*a)%mod; --n; } else { a = (a*a)%mod; n >>= 1; } return res; } static class Utils { private Utils() {} public static void mergeSort(int[] a) { mergeSort(a, 0, a.length - 1); } private static void mergeSort(int[] a, int leftIndex, int rightIndex) { final int MAGIC_VALUE = 50; if (leftIndex < rightIndex) { if (rightIndex - leftIndex <= MAGIC_VALUE) { insertionSort(a, leftIndex, rightIndex); } else { int middleIndex = (leftIndex + rightIndex) / 2; mergeSort(a, leftIndex, middleIndex); mergeSort(a, middleIndex + 1, rightIndex); merge(a, leftIndex, middleIndex, rightIndex); } } } private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) { int length1 = middleIndex - leftIndex + 1; int length2 = rightIndex - middleIndex; int[] leftArray = new int[length1]; int[] rightArray = new int[length2]; System.arraycopy(a, leftIndex, leftArray, 0, length1); System.arraycopy(a, middleIndex + 1, rightArray, 0, length2); for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) { if (i == length1) { a[k] = rightArray[j++]; } else if (j == length2) { a[k] = leftArray[i++]; } else { a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++]; } } } private static void insertionSort(int[] a, int leftIndex, int rightIndex) { for (int i = leftIndex + 1; i <= rightIndex; i++) { int current = a[i]; int j = i - 1; while (j >= leftIndex && a[j] > current) { a[j + 1] = a[j]; j--; } a[j + 1] = current; } } } boolean isPrime(int a){ for(int i = 2; i <= sqrt(a); i++) if(a % i == 0) return false; return true; } static double distance(long x1, long y1, long x2, long y2){ return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } static long gcd(long a, long b){ if(min(a,b) == 0) return max(a,b); return gcd(max(a, b) % min(a,b), min(a,b)); } static long lcm(long a, long b){ return a * b /gcd(a, b); } }
nlogn
135_A. Replacement
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class A { static final Scanner sc = new Scanner(System.in); void run() { int n = sc.nextInt(); int[] xs = new int[n]; for(int i = 0; i < n; i++) { xs[i] = sc.nextInt(); } Arrays.sort(xs); xs[n-1] = xs[n-1] == 1 ? 2 : 1; Arrays.sort(xs); for(int i = 0; i < n; i++) System.out.print(xs[i] + " "); } public static void main(String[] args) { new A().run(); } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.*; import java.util.*; public class Replacement { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader r=new BufferedReader(new InputStreamReader(System.in)); String s=r.readLine(); int n=new Integer(s); int[]arr=new int[n]; String[]sp=r.readLine().split("[ ]+"); for (int i = 0; i < sp.length; i++) { arr[i]=new Integer(sp[i]); } Arrays.sort(arr); if(arr[arr.length-1]==1){ arr[arr.length-1]=2; Arrays.sort(arr); for (int i = 0; i < n; i++) { if(i==n-1){ System.out.println(arr[i]); }else System.out.print(arr[i]+" "); } return; } arr[arr.length-1]=1; Arrays.sort(arr); for (int i = 0; i < n; i++) { if(i==n-1){ System.out.println(arr[i]); }else System.out.print(arr[i]+" "); } } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.*; import java.awt.geom.Point2D; import java.text.*; import java.math.*; import java.util.*; public class Main implements Runnable { final String filename = ""; public void solve() throws Exception { int n = iread(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = iread(); Arrays.sort(a); boolean test = true; for (int i = 0; i < n; i++) { if (a[i] != 1) test = false; int min = (i == 0) ? 1 : a[i - 1]; if (test && i == n - 1) out.write((min + 1) + ""); else out.write(min + ""); if (i == n - 1) out.write("\n"); else out.write(" "); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter(System.out)); // in = new BufferedReader(new FileReader(filename+".in")); // out = new BufferedWriter(new FileWriter(filename+".out")); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public int iread() throws Exception { return Integer.parseInt(readword()); } public double dread() throws Exception { return Double.parseDouble(readword()); } public long lread() throws Exception { return Long.parseLong(readword()); } BufferedReader in; BufferedWriter out; public String readword() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return ""; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) { try { Locale.setDefault(Locale.US); } catch (Exception e) { } // new Thread(new Main()).start(); new Thread(null, new Main(), "1", 1 << 25).start(); } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.*; import java.util.*; public class A { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void solve() throws IOException { int n = nextInt(); int[] a = new int[n]; boolean onlyOnes = true; for (int i = 0; i < n; i++) { a[i] = nextInt(); if (a[i] != 1) onlyOnes = false; } Arrays.sort(a); if (onlyOnes) { for (int i = 0; i < n - 1; i++) out.print("1 "); out.print(2); } else { out.print("1 "); for (int i = 0; i < n - 1; i++) out.print(a[i] + " "); } } void inp() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new A().inp(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "0"; } } return st.nextToken(); } String nextString() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return "0"; } } return st.nextToken("\n"); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
nlogn
135_A. Replacement
CODEFORCES
import java.io.*; import java.util.*; /* * Raudel Ravelo Suarez * Problem: */ public class C { Scanner sc; BufferedReader in; PrintStream out; StringTokenizer tok; public C() throws NumberFormatException, IOException { //sc = new Scanner(System.in); //sc = new Scanner(new FileReader("in.txt")); in = new BufferedReader(new InputStreamReader(System.in)); //in = new BufferedReader(new FileReader("in.txt")); out = System.out; run(); } void run() throws NumberFormatException, IOException { //Add your code here int[] array; int n = nextInt(); array = new int[n]; int max = 0; int pos = 0; for(int i = 0; i <n; i++) { int l = nextInt(); if(l > max) { pos = i; max = l; } array[i] = l; } if(max == 1)array[pos] = 2; else array [pos] = 1; Arrays.sort(array); out.print(array[0]); for(int i = 1; i < n; i++) out.print(" " + array[i]); out.println(); } public static void main(String[] args) throws NumberFormatException, IOException { new C(); } String nextToken() throws IOException { if(tok ==null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
nlogn
135_A. Replacement
CODEFORCES
import java.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.Collections; import java.util.Scanner; import java.util.StringTokenizer; public class c { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); int n = in.nextInt(), m = in.nextInt(); long bounty = in.nextInt(), increase = in.nextInt(); int damage = in.nextInt(); int[] mh = new int[n]; int[] sh = new int[n]; int[] reg = new int[n]; long countKilled = 0; ArrayList<Event> es = new ArrayList<>(); Event[] regen = new Event[n]; for(int i=0;i<n;i++) { mh[i] = in.nextInt(); sh[i] = in.nextInt(); reg[i] = in.nextInt(); if(sh[i] <= damage) countKilled++; if(reg[i] > 0) { int time = (damage+1 - sh[i]+reg[i]-1)/reg[i]; if(time > 0 && mh[i] >= damage+1) { Event e2 = new Event(time, i, damage+1); regen[i] = e2; es.add(e2); } } } for(int i=0;i<m;i++) { Event e = new Event(in.nextInt(), in.nextInt()-1, in.nextInt()); es.add(e); if(reg[e.e] > 0) { int time = (damage+1 - e.h+reg[e.e]-1)/reg[e.e]; if(time > 0 && mh[e.e] >= damage+1) { Event e2 = new Event(e.t + time, e.e, damage+1); e.regen = e2; es.add(e2); } } } Collections.sort(es, (a,b) -> a.t-b.t); long ans = countKilled*bounty; int lastTime = 0; for(Event e : es) { if(e.t == -1) continue; if(regen[e.e] != e && regen[e.e] != null) { regen[e.e].t = -1; regen[e.e] = null; } if(lastTime != e.t) { ans = Math.max(ans, countKilled*(bounty+(e.t-1)*increase)); } if(sh[e.e] <= damage) countKilled--; sh[e.e] = e.h; if(sh[e.e] <= damage) countKilled++; if(e.regen != null) { regen[e.e] = e.regen; } lastTime = e.t; } if(countKilled != 0) { if(increase > 0) ans = -1; else ans = Math.max(ans, countKilled*bounty); } System.out.println(ans); } static class Event { int t; int e; int h; Event regen; public Event(int tt, int ee, int hh) { t = tt; e = ee; h = hh; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = new StringTokenizer(""); } public String next() throws IOException { if(st.hasMoreTokens()) return st.nextToken(); else st = new StringTokenizer(br.readLine()); return next(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
nlogn
912_C. Perun, Ult!
CODEFORCES
import java.util.*; import java.io.*; import java.lang.reflect.Array; public class codeforces { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(); long U = in.nextLong(); long[] E = new long[n]; double max = -1; for(int i=0;i<n;i++) E[i] = in.nextLong(); for(int k=1;k<n-1;k++) { int i = k + 1, j = n - 1, mid = 0; double T = 0; while(i < j) { mid = (int)Math.ceil((double)(i+j)/2); if(E[mid] - E[k-1] <= U) i = mid; else j = mid - 1; } j = k; k = i; i = j - 1; T = E[k] - E[j]; T /= E[k] - E[i]; if(E[k] - E[i] <= U) max = Math.max(max, T); k = j; } pw.println(max); pw.flush(); pw.close(); } /* public static void DFS(int sourse) { int count = 0; visited[sourse] = true; for(int u : adj[sourse]) { if(!visited[u]) { DFS(u); } } }*/ public static ArrayList Divisors(long n) { ArrayList<Long> div = new ArrayList<>(); for (long i=1; i<=Math.sqrt(n); i++) { if (n%i == 0) { div.add(i); if(n/i != i) div.add(n/i); } } return div; } public static int BinarySearch(long[] a, long k) { int n = a.length; int i = 0, j = n-1; int mid = 0; if(k < a[0]) return 0; else if(k >= a[n-1]) return n; else { while(j - i > 1) { mid = (i+j)/2; if(k >= a[mid]) i = mid; else j = mid; } } return i+1; } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x - x == 0 && p.y - y == 0 ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class CodeX { public static void sort(long arr[]) { merge_sort(arr, 0, arr.length - 1); } private static void merge_sort(long A[], long start, long end) { if (start < end) { long mid = (start + end) / 2; merge_sort(A, start, mid); merge_sort(A, mid + 1, end); merge(A, start, mid, end); } } private static void merge(long A[], long start,long mid, long end) { long p = start, q = mid + 1; long Arr[] = new long[(int)(end - start + 1)]; long k = 0; for (int i = (int)start; i <= end; i++) { if (p > mid) Arr[(int)k++] = A[(int)q++]; else if (q > end) Arr[(int)k++] = A[(int)p++]; else if (A[(int)p] < A[(int)q]) Arr[(int)k++] = A[(int)p++]; else Arr[(int)k++] = A[(int)q++]; } for (int i = 0; i < k; i++) { A[(int)start++] = Arr[i]; } } } }
nlogn
957_C. Three-level Laser
CODEFORCES
import java.util.*; import java.io.*; public class Three{ public static void main(String[] args) { Scanner in = new Scanner (System.in); PrintWriter out = new PrintWriter(System.out); pair[] points = new pair [3]; for (int i = 0; i < 3; ++i) { int x = in.nextInt(); int y = in.nextInt(); points[i] = new pair (x, y); } Arrays.sort(points); int MaxY = Math.max(Math.max(points[0].y, points[1].y), points[2].y); int MinY = Math.min(Math.min(points[0].y, points[1].y), points[2].y); out.println(MaxY - MinY + points[2].x - points[0].x + 1); for (int i = MinY; i <= MaxY; ++i) out.println(points[1].x + " " + i); for (int i = points[0].x; i < points[1].x; ++i) out.println(i + " " + points[0].y); for (int i = points[1].x + 1; i <= points[2].x; ++i) out.println(i + " " + points[2].y); out.close(); } public static class pair implements Comparable<pair> { int x, y; public pair (int x_, int y_) { x = x_; y = y_; } @Override public int compareTo(pair o) { return x - o.x; } } }
nlogn
1086_A. Connect Three
CODEFORCES
import java.util.*; import java.io.*; import java.math.BigInteger; public class Problem { static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; static int[] rt; static int[] size; static void initialize(int n){ rt = new int[n + 1]; size = new int[n + 1]; for(int i = 0; i < rt.length; i++){ rt[i] = i; size[i] = 1; } } static int root(int x){ while(rt[x] != x){ rt[x] = rt[rt[x]]; x = rt[x]; } return x; } static long union(int x,int y){ int root_x = root(x); int root_y = root(y); if(root_x == root_y) return 0; long val = size[root_x] *1l* size[root_y]; if(size[root_x]<size[root_y]){ rt[root_x] = rt[root_y]; size[root_y] += size[root_x]; } else{ rt[root_y] = rt[root_x]; size[root_x] += size[root_y]; } return val; } static void solve() { in = new InputReader(System.in); out = new PrintWriter(System.out); int t = 1; while(t-- > 0){ int n = in.nextInt(); int[] arr = in.nextIntArray(n); ArrayList<Pair> list = new ArrayList<>(); for(int i = 1; i < n; i++){ int u = in.nextInt() - 1; int v = in.nextInt() - 1; list.add(new Pair(u, v, Math.max(arr[u],arr[v]))); } list.sort((p1,p2) -> Integer.compare(p1.i, p2.i)); initialize(n); long s1 = 0; for(int i = 0; i < list.size(); i++){ s1 += union(list.get(i).x, list.get(i).y) * list.get(i).i; } for(int i = 0; i < list.size(); i++){ Pair p = list.get(i); p.i = Math.min(arr[p.x],arr[p.y]); } list.sort((p1,p2) -> -Integer.compare(p1.i, p2.i)); initialize(n); long s2 = 0; for(int i = 0; i < list.size(); i++){ s2 += union(list.get(i).x, list.get(i).y) * list.get(i).i; } out.println(s1 - s2); } out.close(); } public static void main(String[] args) { new Thread(null ,new Runnable(){ public void run(){ try{ solve(); } catch(Exception e){ e.printStackTrace(); } } },"1",1<<26).start(); } static class Pair implements Comparable<Pair> { int x,y; int i; Pair (int x,int y) { this.x = x; this.y = y; } Pair (int x,int y, int i) { this.x = x; this.y = y; this.i = i; } public int compareTo(Pair o) { if(this.x != o.x) return -Integer.compare(this.x, o.y); return -Integer.compare(this.y,o.y); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y==y; } return false; } @Override public String toString() { return x + " "+ y + " "+i; } /*public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); }*/ } static long add(long a,long b){ long x=(a+b); while(x>=mod) x-=mod; return x; } static long sub(long a,long b){ long x=(a-b); while(x<0) x+=mod; return x; } static long mul(long a,long b){ long x=(a*b); while(x>=mod) x-=mod; return x; } static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } static long gcd(long x,long y) { if(y==0) return x; else return gcd(y,x%y); } static int gcd(int x,int y) { if(y==0) return x; else return gcd(y,x%y); } static long pow(long n,long p,long m) { long result = 1; if(p==0){ return n; } while(p!=0) { if(p%2==1) result *= n; if(result >= m) result %= m; p >>=1; n*=n; if(n >= m) n%=m; } return result; } static long pow(long n,long p) { long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
nlogn
915_F. Imbalance Value of a Tree
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Solution { private static int[] a; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(); a = new int[101]; for (int i = 0; i < m; i++) { int type = sc.nextInt(); a[type] = a[type] + 1; } int lo=1, hi=100, max=0; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (check(n, mid)) { max = mid; lo = mid+1; } else { hi = mid -1; } } System.out.println(max); } public static boolean check(int n, int target) { int result = 0; for (int i=0; i <a.length; i++) { result = result + (a[i] / target); } if (result >= n) {return true;} return false; } }
nlogn
1011_B. Planning The Expedition
CODEFORCES
import java.util.Arrays; import java.util.Scanner; public class Solution { private static int[] a; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(); a = new int[101]; for (int i = 0; i < m; i++) { int type = sc.nextInt(); a[type] = a[type] + 1; } int lo=1, hi=100, max=0; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (check(n, mid)) { max = mid; lo = mid+1; } else { hi = mid -1; } } System.out.println(max); } public static boolean check(int n, int target) { int result = 0; for (int i=0; i <a.length; i++) { result = result + (a[i] / target); } if (result >= n) {return true;} return false; } }
nlogn
1011_B. Planning The Expedition
CODEFORCES
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Solution { public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.solve()); } private int solve() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] a = new int[m]; for (int i = 0; i < m; ++i) a[i] = in.nextInt(); if (n > m) return 0; Map<Integer, Integer> map = new HashMap<>(); for (int k: a) map.put(k, map.getOrDefault(k, 0) + 1); List<Integer> keySet = new ArrayList<>(map.keySet()); int end = m / n; keySet.sort((u, v) -> -Integer.compare(u, v)); do { int count = 0; for (int k: keySet) { count += map.get(k) / end; if (count >= n) return end; } } while (--end > 0); return 0; } }
nlogn
1011_B. Planning The Expedition
CODEFORCES
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Solution { public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.solve()); } private int solve() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] a = new int[m]; for (int i = 0; i < m; ++i) a[i] = in.nextInt(); if (n > m) return 0; Map<Integer, Integer> map = new HashMap<>(); for (int k: a) map.put(k, map.getOrDefault(k, 0) + 1); List<Integer> keySet = new ArrayList<>(map.keySet()); int end = m / n; keySet.sort((u, v) -> -Integer.compare(u, v)); do { int count = 0; for (int k: keySet) { count += map.get(k) / end; if (count >= n) return end; } } while (--end > 0); return 0; } }
nlogn
1011_B. Planning The Expedition
CODEFORCES
import java.io.*; import java.util.*; public class p7{ 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(); //PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int k = sc.nextInt(); long one = (long)Math.pow(2, k) - 1; long[] arr = new long[n+1]; arr[0] = 0; for(int i=1;i<=n;i++){ arr[i] = sc.nextLong(); arr[i] ^= arr[i-1]; } Map<Long, Long> count = new HashMap<>(); for(int i=0;i<=n;i++){ Long key = Math.min(arr[i], (arr[i]^one)); Long val = count.get(key); if(val==null) val = 0L; count.put(key, val+1); } long num = n; long ans = num*(num+1)/2; for(Map.Entry<Long, Long> ent: count.entrySet()){ Long cnt = ent.getValue(); long num1 = cnt/2; long num2 = (cnt+1)/2; ans -= ( (num1*(num1-1))/2 ); ans -= ( (num2*(num2-1))/2 ); } System.out.println(ans); } }
nlogn
1054_D. Changing Array
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author caoash */ 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); BObtainingTheString solver = new BObtainingTheString(); solver.solve(1, in, out); out.close(); } static class BObtainingTheString { public void solve(int testNumber, FastScanner br, PrintWriter pw) { int n = br.nextInt(); String s = br.nextString(); String t = br.nextString(); char[] sarr = new char[n]; char[] tarr = new char[n]; int[] sAppear = new int[26]; int[] tAppear = new int[26]; for (int i = 0; i < s.length(); i++) { sarr[i] = s.charAt(i); tarr[i] = t.charAt(i); sAppear[s.charAt(i) - 'a']++; tAppear[t.charAt(i) - 'a']++; } for (int i = 0; i < 26; i++) { if (sAppear[i] != tAppear[i]) { pw.println(-1); pw.close(); } } ArrayList<Integer> ans = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { char curr = tarr[i]; for (int j = i + 1; j < n; j++) { if (sarr[j] == curr) { for (int k = j; k > i; k--) { ans.add(k); char temp = sarr[k - 1]; sarr[k - 1] = sarr[k]; sarr[k] = temp; } break; } } } pw.println(ans.size()); for (int e : ans) { pw.print(e + " "); } pw.close(); } } static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastScanner.SpaceCharFilter filter; public FastScanner(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
quadratic
1015_B. Obtaining the String
CODEFORCES
import java.util.Scanner; public class A961_Tetris { public static void main(String[] args) { Scanner input = new Scanner(System.in); int platforms = input.nextInt(); int in = input.nextInt(); int[] cols = new int[platforms]; int[] squares = new int[in]; for (int i = 0; i < in; i ++) { squares[i] = input.nextInt(); } boolean hi = false; int score = 0; for (int i = 0; i < in; i ++) { cols[squares[i] - 1] ++; hi = checkscore(cols); if (hi == true) { hi = false; score ++; for (int j = 0; j < cols.length; j ++) { cols[j] --; } } } System.out.println(score); } public static boolean checkscore(int[] cols) { for (int i = 0; i < cols.length; i ++) { if (cols[i] == 0) { return false; } } return true; } }
quadratic
961_A. Tetris
CODEFORCES
import java.util.*; import java.io.*; public class RGBSubstring { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int Q = scanner.nextInt(); while(Q-->0) { int N = scanner.nextInt(); int K = scanner.nextInt(); String s1 = "RGB"; String s2 = "GBR"; String s3 = "BRG"; char[] arr = scanner.next().toCharArray(); int[] cnts = new int[3]; for(int i = 0; i < K; i++) { int ind = i % 3; if (arr[i] != s1.charAt(ind)) cnts[0]++; if (arr[i] != s2.charAt(ind)) cnts[1]++; if (arr[i] != s3.charAt(ind)) cnts[2]++; } int ans = Math.min(Math.min(cnts[0], cnts[1]), cnts[2]); for(int i = K; i < N; i++) { int ind = (K-1)%3; int[] nextCnts = new int[3]; nextCnts[1] = cnts[0]; nextCnts[2] = cnts[1]; nextCnts[0] = cnts[2]; if ('R' != arr[i-K]) nextCnts[1]--; if ('G' != arr[i-K]) nextCnts[2]--; if ('B' != arr[i-K]) nextCnts[0]--; if (arr[i] != s1.charAt(ind)) nextCnts[0]++; if (arr[i] != s2.charAt(ind)) nextCnts[1]++; if (arr[i] != s3.charAt(ind)) nextCnts[2]++; cnts = nextCnts; for(int j = 0; j < 3; j++) ans = Math.min(ans, cnts[j]); } out.println(ans); } out.flush(); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } } }
quadratic
1196_D1. RGB Substring (easy version)
CODEFORCES
// discussed with rainboy import java.io.*; import java.util.*; public class CF915D { static ArrayList[] aa; static boolean[] visited, instack; static int[] stack; static int cnt, h_, i_, j_; static boolean dfs1(int i) { if (visited[i]) { if (instack[i]) { h_ = i; return true; } return false; } visited[i] = instack[i] = true; stack[cnt++] = i; ArrayList<Integer> adj = aa[i]; for (int j : adj) if (dfs1(j)) return true; instack[i] = false; cnt--; return false; } static boolean dfs2(int i) { if (visited[i]) return instack[i]; visited[i] = instack[i] = true; ArrayList<Integer> adj = aa[i]; for (int j : adj) if (!(i == i_ && j == j_) && dfs2(j)) return true; instack[i] = false; return false; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); aa = new ArrayList[n]; for (int i = 0; i < n; i++) aa[i] = new ArrayList<Integer>(); while (m-- > 0) { st = new StringTokenizer(br.readLine()); int i = Integer.parseInt(st.nextToken()) - 1; int j = Integer.parseInt(st.nextToken()) - 1; aa[i].add(j); } visited = new boolean[n]; instack = new boolean[n]; stack = new int[n]; for (int i = 0; i < n; i++) if (dfs1(i)) break; if (cnt == 0) { System.out.println("YES"); return; } for (j_ = h_, i_ = stack[--cnt]; ; j_ = i_, i_ = stack[--cnt]) { Arrays.fill(visited, false); Arrays.fill(instack, false); boolean cycle = false; for (int i = 0; i < n; i++) if (dfs2(i)) { cycle = true; break; } if (!cycle) { System.out.println("YES"); return; } if (i_ == h_) break; } System.out.println("NO"); } }
quadratic
915_D. Almost Acyclic Graph
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskG solver = new TaskG(); solver.solve(1, in, out); out.close(); } static class TaskG { static final long MODULO = (long) 1e9 + 7; static final long BIG = Long.MAX_VALUE - Long.MAX_VALUE % MODULO; static final int[] ONE = new int[]{1}; int k; int n; long[] globalRes; int[] p2; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); k = in.nextInt(); globalRes = new long[k + 1]; p2 = new int[n + 1]; p2[0] = 1; for (int i = 1; i <= n; ++i) p2[i] = (int) (2 * p2[i - 1] % MODULO); Vertex[] vs = new Vertex[n]; for (int i = 0; i < n; ++i) vs[i] = new Vertex(); for (int i = 0; i < n - 1; ++i) { Vertex a = vs[in.nextInt() - 1]; Vertex b = vs[in.nextInt() - 1]; a.adj.add(b); b.adj.add(a); } vs[0].dfs(null); long[][] ways = new long[k + 1][k + 1]; ways[0][0] = 1; for (int i = 1; i <= k; ++i) { for (int j = 1; j <= k; ++j) { ways[i][j] = j * (ways[i - 1][j] + ways[i - 1][j - 1]) % MODULO; } } long sum = 0; for (int i = 1; i <= k; ++i) { long s = globalRes[i]; s %= MODULO; sum = (sum + s * ways[k][i]) % MODULO; } out.println(sum); } class Vertex { int[] res; int subtreeSize; List<Vertex> adj = new ArrayList<>(); public void dfs(Vertex parent) { subtreeSize = 1; int[] prod = ONE; for (Vertex child : adj) if (child != parent) { child.dfs(this); subtreeSize += child.subtreeSize; } int mult = 2;//p2[n - subtreeSize]; for (Vertex child : adj) if (child != parent) { int[] c = child.res; prod = mul(prod, c); subFrom(globalRes, c, 1); } addTo(globalRes, prod, mult); res = insertEdge(prod); } private int[] insertEdge(int[] a) { int len = a.length + 1; if (len > k) len = k + 1; int[] b = new int[len]; b[0] = a[0] * 2; if (b[0] >= MODULO) b[0] -= MODULO; for (int i = 1; i < len; ++i) { long s = a[i - 1]; if (i < a.length) s += a[i]; if (s >= MODULO) s -= MODULO; s = s * 2; if (s >= MODULO) s -= MODULO; b[i] = (int) s; } b[1] -= 1; if (b[1] < 0) b[1] += MODULO; return b; } private void addTo(long[] a, int[] b, int mult) { for (int i = 0; i < b.length; ++i) { long s = a[i] + b[i] * (long) mult; if (s < 0) s -= BIG; a[i] = s; } } private void subFrom(long[] a, int[] b, int mult) { for (int i = 0; i < b.length; ++i) { long s = a[i] + (MODULO - b[i]) * (long) mult; if (s < 0) s -= BIG; a[i] = s; } } private int[] mul(int[] a, int[] b) { int len = a.length + b.length - 1; if (len > k) len = k + 1; int[] c = new int[len]; for (int i = 0; i < len; ++i) { long s = 0; int left = Math.max(0, i - (b.length - 1)); int right = Math.min(a.length - 1, i); for (int ia = left; ia <= right; ++ia) { int ib = i - ia; s += a[ia] * (long) b[ib]; if (s < 0) s -= BIG; } c[i] = (int) (s % MODULO); } return c; } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
quadratic
1097_G. Vladislav and a Great Legend
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); E solver = new E(); solver.solve(1, in, out); out.close(); } static class E { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.ni(), K = in.ni(); long mod = 998244353; long[][] dp = new long[n + 1][n + 1]; for (int lim = 1; lim <= n; lim++) { long sum = 1; dp[0][lim] = 1; for (int i = 1; i <= n; i++) { dp[i][lim] = (dp[i][lim] + sum) % mod; sum = (sum + dp[i][lim]) % mod; if (i >= lim) sum = (sum - dp[i - lim][lim] + mod) % mod; } } long ans = 0; for (int k = 1; k < Math.min(K, n + 1); k++) { long h = dp[n][k] - dp[n][k - 1]; int lim = K / k; if (K % k == 0) lim--; if (lim > n) lim = n; ans += dp[n][lim] * h % mod; } out.println(2 * ans % mod); } } 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()); } } }
quadratic
1027_E. Inverse Coloring
CODEFORCES
/** * @author: Mehul Raheja */ import java.util.*; import java.io.*; public class p3{ /* Runtime = O() */ static int N, M, K; static String s; static StringTokenizer st; static int[] d; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int R = Integer.parseInt(st.nextToken()); double[] x = new double[N]; st = new StringTokenizer(br.readLine()); for (int i = 0; i < N; i++) { x[i] = Double.parseDouble(st.nextToken()); } double[] y = new double[N]; for (int i = 0; i < N; i++) { // int found = -1; double maxy = R; for (int j = i-1; j >= 0; j--) { if(Math.abs(x[j] - x[i]) <= 2 * R){ maxy = Math.max(y[j] + inc(x[j] - x[i],R), maxy); } } y[i] = maxy; } for (int i = 0; i < y.length-1; i++) { System.out.print(y[i] + " "); } System.out.println(y[y.length-1]); // System.out.println(Arrays.toString(y)); } public static double inc(double x, double R){ return Math.sqrt((4*R*R)-(x*x)); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { FastScanner sc=new FastScanner(); PrintWriter pw=new PrintWriter(System.out); double eps=1e-12; while(sc.hasNext()){ int n=sc.nextInt(); int r=sc.nextInt(); double[]shu=new double[n]; for(int i=0;i<n;i++)shu[i]=sc.nextDouble(); double[]res=new double[n]; for(int i=0;i<n;i++){ for(int j=0;j<i;j++){ double temp=Math.abs(shu[i]-shu[j]); if(temp<2*r||Math.abs(temp-2*r)<eps){ res[i]=Math.max(res[i],res[j]+Math.sqrt(4*r*r-temp*temp)); } } res[i]=Math.max(res[i],r); } for(int i=0;i<n;i++){ pw.print(res[i]+" "); } pw.flush(); } } } class FastScanner{ BufferedReader br; StringTokenizer st; FastScanner(){ br=new BufferedReader(new InputStreamReader(System.in)); st=new StringTokenizer(""); } String nextLine(){ String s=""; try { s=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } boolean hasNext(){ String s=""; while(!st.hasMoreTokens()){ s=nextLine(); if(s==null)return false; st=new StringTokenizer(s); } return true; } String next(){ String s=""; while(!st.hasMoreTokens()){ s=nextLine(); st=new StringTokenizer(s); } return st.nextToken(); } int nextInt(){ return Integer.valueOf(next()); } long nextLong(){ return Long.valueOf(next()); } double nextDouble(){ return Double.valueOf(next()); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; public class Main { public static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { // InputStream inputStream = System.in; // Useful when taking input other than // console eg file handling // check ctor of inputReader InputReader scn = new InputReader(); int n = scn.nextInt(), r = scn.nextInt(); double[] y = new double[n]; int[] x = new int[n]; boolean[] mark = new boolean[n]; for(int i = 0; i < n; i++) { x[i] = scn.nextInt(); } for(int i = 0; i < n; i++) { double yc = r; for(int j = 0; j < n; j++) { if(i == j || !mark[j]) { continue; } if(x[i] + r < x[j] - r || x[i] - r > x[j] + r) { continue; } yc = Math.max(yc, y[j] + Math.sqrt(Math.abs(Math.pow(x[i] - x[j], 2) - 4 * r * r))); } y[i] = yc; mark[i] = true; } for(int i = 0; i < n; i++) { System.out.print(y[i] + " "); } System.out.println(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int r = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); double[] ans = new double[n]; for (int i = 0; i < n; i++) { double max = 0; for (int j = 0; j < i; j++) { int difx = Math.abs(arr[i] - arr[j]); if (difx <= 2 * r) { max = Math.max(max, ans[j] + Math.sqrt(4 * r * r - difx * difx)); } } ans[i] = max; } PrintWriter pw = new PrintWriter(System.out); for (int i = 0; i < n; i++) pw.print(ans[i] + r + " "); pw.flush(); } 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 { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; import java.lang.reflect.Array; public class C { FastScanner in; PrintWriter out; boolean systemIO = true; public static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } public void solve() { int n = in.nextInt(); int r = 2 * in.nextInt(); int[] x = new int[n]; for (int i = 0; i < x.length; i++) { x[i] = in.nextInt(); } double[] y = new double[n]; for (int i = 0; i < y.length; i++) { y[i] = r / 2; } for (int i = 0; i < y.length; i++) { for (int j = 0; j < i; j++) { if (Math.abs(x[i] - x[j]) == r) { y[i] = Math.max(y[i], y[j]); } else if (Math.abs(x[i] - x[j]) < r) { y[i] = Math.max(y[i], y[j] + Math.sqrt(r * r - (x[j] - x[i]) * (x[j] - x[i]))); } } } for (int i = 0; i < y.length; i++) { out.print(y[i] + " "); } } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("segments.in")); out = new PrintWriter(new File("segments.out")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA public static void main(String[] arg) { new C().run(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class C{ static int n; static double sqr(double v) {return (v*v);} static double sqrt(double v) {return Math.sqrt(v);} static double r,x[],res[]; static void MainMethod()throws Exception{ n=reader.nextInt(); r=reader.nextDouble(); int i,j; x=new double[n]; res=new double[n]; for (i=0;i<n;i++)x[i]=reader.nextDouble(); res[0]=r; for (i=1;i<n;i++) { res[i]=r; for (j=0;j<i;j++) { if (Math.abs(x[i]-x[j])<=(2*r)) { res[i]=Math.max(res[i], sqrt(sqr(2*r)-sqr(x[i]-x[j]))+res[j] ); } } } for (i=0;i<n;i++) printer.print(res[i]+" "); } public static void main(String[] args)throws Exception{ MainMethod(); printer.close(); } static void halt(){ printer.close(); System.exit(0); } static PrintWriter printer=new PrintWriter(new OutputStreamWriter(System.out)); static class reader{ static BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer token=new StringTokenizer(""); static String readNextLine() throws Exception{ return bReader.readLine(); } static String next() throws Exception{ while (token.hasMoreTokens()==false){ token=new StringTokenizer(bReader.readLine()); } return token.nextToken(); } static int nextInt()throws Exception{ while (token.hasMoreTokens()==false){ token=new StringTokenizer(bReader.readLine()); } return Integer.parseInt(token.nextToken()); } static long nextLong()throws Exception{ while (token.hasMoreTokens()==false){ token=new StringTokenizer(bReader.readLine()); } return Long.parseLong(token.nextToken()); } static double nextDouble()throws Exception{ while (token.hasMoreTokens()==false){ token=new StringTokenizer(bReader.readLine()); } return Double.parseDouble(token.nextToken()); } } static class MyMathCompute{ static long [][] MatrixMultiplyMatrix(long [][] A, long [][] B, long mod) throws Exception{ int n=A.length, m=B[0].length; int p=A[0].length; int i,j,k; if (B.length!=p) throw new Exception("invalid matrix input"); long [][] res=new long [n][m]; for (i=0;i<n;i++) for (j=0;j<m;j++){ if (A[i].length!=p) throw new Exception("invalid matrix input"); res[i][j]=0; for (k=0;k<p;k++) res[i][j]=(res[i][j]+((A[i][k]*B[k][j])% mod))% mod; } return res; } static double [][] MatrixMultiplyMatrix(double [][] A, double [][] B ) throws Exception{ int n=A.length, m=B[0].length; int p=A[0].length; int i,j,k; if (B.length!=p) throw new Exception("invalid matrix input"); double [][] res=new double [n][m]; for (i=0;i<n;i++) for (j=0;j<m;j++){ if (A[i].length!=p) throw new Exception("invalid matrix input"); res[i][j]=0; for (k=0;k<p;k++) res[i][j]=res[i][j]+(A[i][k]*B[k][j]); } return res; } static long [][] MatrixPow(long [][] A,long n, long mod) throws Exception{ if (n==1) return A; long [][] res=MatrixPow(A, n/2, mod); res=MatrixMultiplyMatrix(res, res, mod); if ((n % 2) == 1) res=MatrixMultiplyMatrix(A,res, mod); return res; } static double [][] MatrixPow(double [][] A,long n) throws Exception{ if (n==1) return A; double[][] res=MatrixPow(A, n/2); res=MatrixMultiplyMatrix(res, res); if ((n % 2) == 1) res=MatrixMultiplyMatrix(A,res); return res; } static long pow(long a,long n,long mod){ a= a % mod; if (n==0) return 1; long k=pow(a,n/2,mod); if ((n % 2)==0) return ((k*k)%mod); else return (((k*k) % mod)*a) % mod; } static double pow(double a,long n){ if (n==0) return 1; double k=pow(a,n/2); if ((n % 2)==0) return (k*k); else return (((k*k) )*a) ; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class Solution{ public static void main(String[] args) throws Exception { int n=nextInt(); int r=nextInt(); int x[]=new int[n]; double y[]=new double[n]; for(int i=0;i<n;i++) x[i]=nextInt(); for(int i=0;i<n;i++){ //(x1-x2)2+(y1-y2)2=r2 y[i]=r; for(int j=0;j<i;j++){ int d=sq(2*r)-sq(x[i]-x[j]); if(d>=0){ double y1=Math.sqrt(d)+y[j]; y[i]=Math.max(y1,y[i]); } } } for(int i=0;i<n;i++) System.out.printf("%.12g ",y[i]); } static int sq(int a){ return a*a; } static int nextInt()throws IOException{ InputStream in=System.in; int ans=0; boolean flag=true; byte b=0; while ((b>47 && b<58) || flag){ if(b>=48 && b<58){ ans=ans*10+(b-48); flag=false; } b=(byte)in.read(); } return ans; } static String next()throws Exception{ StringBuilder sb=new StringBuilder(1<<16); InputStream in=System.in; byte b=0; do{ if(!isWhiteSpace(b)) sb.append((char)b); b=(byte)in.read(); }while(!isWhiteSpace(b) || sb.length()==0); return sb.toString(); } static boolean isWhiteSpace(byte b){ char ch=(char)b; return ch=='\0' || ch==' ' || ch=='\n'; } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.math.*; import java.util.*; public class Main{ public static void main(String[] args){ InputReader reader = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = reader.nextInt(); int r = reader.nextInt(); int[] x = new int[n]; double[] y = new double[n]; for(int i=0;i<n;++i){ int iniX = reader.nextInt(); double bestY = (double)r; for(int j=0;j<i;++j){ // pw.printf("testing %d %d\n", i, j); if(Math.abs(iniX - x[j]) < 2*r){ // pw.printf("on colision %d %d\n", i, j); bestY = Math.max(bestY, collisionY((double)x[j], y[j], (double)iniX, r)); } if(Math.abs(iniX - x[j]) == 2*r){ // pw.printf("touvhing %d %d\n", i, j); bestY = Math.max(bestY, y[j]); } } x[i] = iniX; y[i] = bestY; } for(int i=0;i<n;++i){ pw.printf("%.9f ", y[i]); } pw.flush(); pw.close(); } public static double collisionY(double x1, double y1, double x2, double r){ double dhsq = r*r*4-(x1-x2)*(x1-x2); return y1+Math.sqrt(dhsq); } public static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader (InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream)); } public String next(){ while(tokenizer == null || !tokenizer.hasMoreTokens()){ try{ String line = reader.readLine(); if(line == null){ return "0"; } tokenizer = new StringTokenizer(line); } catch(IOException ioe){ throw new RuntimeException(ioe); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public Long nextLong(){ return Long.parseLong(next()); } public BigInteger nextBigInteger(){ return new BigInteger(next()); } public String nextLine(){ String line = ""; try{ while(line.equals("")){ line = reader.readLine(); } } catch(IOException ioe){ throw new RuntimeException(ioe); } return line; } } public static class MultiSet<E> { HashMap<E, Integer> map = new HashMap<E, Integer>(); int multiSize = 0; public int add(E key){ multiSize ++; Integer amount = map.get(key); if(amount == null){ map.put(key, 1); return 1; } map.put(key, amount+1); return amount+1; } public int remove(E key){ Integer amount = map.get(key); if(amount == null){ return -1; } multiSize --; if(amount == 1){ map.remove(key); } else { map.put(key, amount-1); } return amount-1; } public ArrayList<E> elems(){ ArrayList<E> ret = new ArrayList<E>(multiSize); for(Map.Entry<E, Integer> e : map.entrySet()){ E key = e.getKey(); int v = e.getValue(); while(v-->0){ ret.add(key); } } return ret; } public int getMultiSize(){ return multiSize; } } public static class MaxBIT{ int n; int[]t; public MaxBIT(int n){ this.n = Integer.highestOneBit(n)<<1; this.t = new int[this.n<<1]; for(int i=0;i<2*this.n;++i){ t[i] = -1; } } public void setMax(int p, int val){ p+=n; while(p>1){ t[p] = Math.max(t[p], val); p>>=1; } } public int getMax(int p, int q){ p+=n; q+=n; int ret = -1; while(p<q){ if((p&1)==1){ ret=Math.max(t[p++], ret); } if((q&1)==1){ ret=Math.max(t[--q], ret); } p = p>>1; q = q>>1; } return ret; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.awt.geom.Point2D; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class C { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] line = in.readLine().split(" "); int n = Integer.parseInt(line[0]); int r= Integer.parseInt(line[1]); line = in.readLine().split(" "); double[] x = new double[n]; double[] y= new double[n]; for(int i = 0; i<n; i++) { y[i] = r; x[i] = Integer.parseInt(line[i]); } for(int i = 1; i<n; i++) { for(int j = 0; j<i; j++) { if(Math.abs(x[i]-x[j])>r*2) { continue; } double low = y[j]; double high = y[j]+(double)r*2.0; for(int k = 0; k<85 && low<high; k++) { double mid = (low+high)/2.0; if(Point2D.distance(x[j], y[j], x[i], mid)<(double)r*2.0) { low = mid; } else { high = mid; } } y[i] = Math.max(y[i], low); } } System.out.printf("%.15f",y[0]); for(int i = 1; i<n; i++) { System.out.printf(" %.15f",y[i]); } System.out.print("\n"); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; public class utkarsh { InputStream is; PrintWriter out; double x[], y[], R; boolean game(double x1, double y1, double x2, double y2){ double dis = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); //if(x2 == 12 && x1 == 8 && y1 > 13 && y1 < 14) out.println(dis +" "+ y2); return dis <= 4.0 * R * R; } void play(int n){ double l, r, m; double a[] = new double[n]; for(int i = 0; i < n; i++){ l = 0.0; r = 1000000.0; for(int j = 0; j < 50; j++){ m = (l + r) / 2; if(game(x[i], 0, x[n], m)) l = m; else r = m; } a[i] = l; } for(int i = 0; i < n; i++){ //if(n == 4) out.println(a[i] +" "+ y[i]); if(a[i] > 0.0 && (y[i] + a[i]) > y[n]) y[n] = y[i] + a[i]; } } void solve(){ //Enter code here utkarsh int i, j, n; n = ni(); R = nd(); x = new double[n]; y = new double[n]; for(i = 0; i < n; i++) x[i] = nd(); for(i = 0; i < n; i++){ play(i); } for(i = 0; i < n; i++) out.print((R + y[i]) +" "); } 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(); } 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; } 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); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; import java.math.*; // import java.awt.Point; public class Main { InputStream is; PrintWriter out; String INPUT = ""; long MOD = 1_000_000_007; int inf = Integer.MAX_VALUE; void solve(){ int n = ni(); int r = ni(); int[] x = new int[n]; for(int i = 0; i < n; i++){ x[i] = ni(); } double[] y = new double[n]; Arrays.fill(y,-1); for(int i = 0; i < n; i++){ for(int j = 0; j < i; j++){ double res = 4*r*r - (x[i]-x[j])*(x[i]-x[j]); if(res < 0) continue; else{ double tmp = Math.sqrt(res) + y[j]; if(tmp > y[i]){ y[i] = tmp; } } } if(y[i]==-1) y[i] = r; } for(int i = 0; i < n; i++){ out.print(y[i]+" "); } } class Permutation{ // max=10 // n=10: 160ms // n=11: 1600-1700ms int n; int max; BitSet used; int[] p; public Permutation(int n, int max){ this.n = n; this.max = max; used = new BitSet(n); p = new int[n]; } public boolean next(){ if(used.cardinality() == 0){ for(int i=0; i<n; i++){ p[i] = i; } used.set(0, n); return true; } int i; for(i=n-1; i>=0; i--){ used.clear(p[i]); if((used.nextClearBit(p[i]+1)) < max) break; } if(i<0) return false; p[i] = used.nextClearBit(p[i]+1); used.set(p[i]); int idx = i+1; for(i=used.nextClearBit(0); i<max && idx<n; i=used.nextClearBit(i+1)){ p[idx++] = i; used.set(i); } return true; } public String toString(){ StringBuilder sb = new StringBuilder(); for(int i=0; i<n; i++){ sb.append(p[i]+" "); } return sb.toString(); } } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; private 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) && 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 static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; public class NewYearAndCurling { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer t = new StringTokenizer(in.readLine()); int N = Integer.parseInt(t.nextToken()); int R = Integer.parseInt(t.nextToken()); int[] x = new int[N]; t = new StringTokenizer(in.readLine()); for(int i = 0; i < N; ++i) x[i] = Integer.parseInt(t.nextToken()); double[] y = new double[N]; for(int i = 0; i < N; ++i) { double max = R; for(int j = 0; j < i; ++j ) { int xDiff = Math.abs(x[i] - x[j]); if(xDiff <= 2 * R) max = Math.max(max, y[j] + Math.sqrt(4*R*R - xDiff*xDiff)); } y[i] = max; } out.print(y[0]); for(int i = 1; i < N; ++i) out.print(" " + y[i]); out.println(); in.close(); out.close(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.*; import java.util.*; /** * * @author kamranmaharov */ public class Main { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); String[] line = in.readLine().split(" "); int n = Integer.parseInt(line[0]); int r = Integer.parseInt(line[1]); line = in.readLine().split(" "); int[] x = new int[n+1]; double[] y = new double[n+1]; for (int i=1; i<=n; ++i) { x[i] = Integer.parseInt(line[i-1]); double maxy = -1.0; for (int j=1; j<i; ++j) { double x2 = x[i]; double x1 = x[j]; double y1 = y[j]; double a = 1; double b = -2 * y1; double c = x1 * x1 + x2 * x2 - 2 * x1 * x2 + y1 * y1 - 4.0 * r * r; double D = b * b - 4 * a * c; //System.out.println(i + " " + j + " " + D); if (D >= 0) { double y2 = (-b + Math.sqrt(D)) / (2 * a); maxy = Math.max(maxy, y2); } } if (maxy < 0) { maxy = r; } y[i] = maxy; if (i>1) {System.out.print(" ");} System.out.printf("%.13f", y[i]); } System.out.println(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Main { public static String taskName = ""; public class Task { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int r = in.nextInt(); int[] x = new int[n]; for(int i = 0; i < n; i++) x[i] = in.nextInt(); double[] y = new double[n]; for(int i = 0; i < n; i++) { y[i] = r; for(int j = 0; j < i; j++) { int dx = Math.abs(x[i] - x[j]); if(dx <= 2 * r) y[i] = Math.max(y[i], y[j] + Math.abs(Math.sqrt(4 * r * r - dx * dx))); } System.out.print(y[i] + " "); } System.out.println(); } } public static void main(String[] args) throws FileNotFoundException { if(!taskName.isEmpty()) { System.setIn(new BufferedInputStream(new FileInputStream(taskName + ".in"))); System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(taskName + ".out")))); } InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Main main = new Main(); main.run(in, out); out.close(); } public void run(InputReader in, PrintWriter out) { Task solver = new Task(); solver.solve(1, in, out); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while(tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(reader.readLine()); } catch(IOException e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public double nextShort() { return Short.parseShort(next()); } public double nextByte() { return Byte.parseByte(next()); } public double nextFloat() { return Float.parseFloat(next()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; public class C { public static void main(String[] args) { Scanner qwe = new Scanner(System.in); int n = qwe.nextInt(); double r = qwe.nextDouble(); double[] fy = new double[n]; Arrays.fill(fy, r); double[] xs = new double[n]; for (int i = 0; i < xs.length; i++) { xs[i] = qwe.nextDouble(); } for(int i =0; i < n; i++){ for(int j = i+1; j < n; j++){ double dx = xs[j]-xs[i]; if(Math.abs(dx) > 2*r) continue; fy[j] = Math.max(fy[j], Math.sqrt(4*r*r-dx*dx)+fy[i]); } } StringBuilder stb = new StringBuilder(); for (int i = 0; i < xs.length; i++) { stb.append(fy[i]+" "); } System.out.println(stb); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; import static java.lang.Math.*; public class ProblemC { public static void main(String[] args) { FastScanner input = new FastScanner(); int n = input.nextInt(); int radius = input.nextInt(); ArrayList<Integer> diskXToFall = new ArrayList<Integer>(); for (int a = 0; a < n; a++) { diskXToFall.add(input.nextInt()); } ArrayList<P> stationaryDisks = new ArrayList<P>(); for (int a = 0; a < n; a++) { double highCollision = radius; for (P i : stationaryDisks) { if (Math.abs(diskXToFall.get(a) - i.x) - 1e-8 <= 2 * radius) { double hypot = 2 * radius; double leg = Math.abs(diskXToFall.get(a) - i.x); double yOffset = Math.sqrt(Math.abs(hypot * hypot - leg * leg)); highCollision = Math.max(highCollision, yOffset + i.y); } } stationaryDisks.add(new P(diskXToFall.get(a), highCollision)); } for(int a = 0; a < n; a++) { System.out.print(stationaryDisks.get(a).y + " "); } } static class P implements Comparable<P> { final double x, y; P(double x, double y) { this.x = x; this.y = y; } P sub(P that) { return new P(x - that.x, y - that.y); } P add(P that) { return new P(x + that.x, y + that.y); } double dot(P that) { return x * that.x + y * that.y; } P scale(double s) { return new P(x * s, y * s); } // Use hypot() only if intermediate overflow must be avoided; very slow double length() { return sqrt(x * x + y * y); } double length2() { return x * x + y * y; } P leftNormal() { return new P(-y, x); } // rotateCCW(90deg) P rightNormal() { return new P(y, -x); } // rotateCW(90deg) P normalize() { double n = length(); return n > 0 ? new P(x / n, y / n) : origin(); } P scaleToLength(double l) { return normalize().scale(l); } P project(P a) { return scale(a.dot(this) / length2()); } P reflect(P a) { return project(a).scale(2.0).sub(a); } // use if sin, cos are known P rotateCCW(double sinT, double cosT) { return new P(x * cosT - y * sinT, x * sinT + y * cosT); } P rotateCW(double sinT, double cosT) { return rotateCCW(-sinT, cosT); } P rotate(double theta) { return rotateCCW(sin(theta), cos(theta)); } // angle to horizontal (1, 0); result is in [-pi, pi] rad or (-180-180) deg double theta() { return atan2(y, x); } // angle between two vectors, result is in [0, pi] rad (0-180 deg) double angleTo(P a) { return acos(this.dot(a) / this.length() / a.length()); } boolean isOrigin() { return x == 0 && y == 0; } public String toString() { return String.format("(%f,%f)", this.x, this.y); } static P read(Scanner s) { return new P(s.nextDouble(), s.nextDouble()); } static P origin() { return new P(0, 0); } double det(P that) { return this.x * that.y - this.y * that.x; } double crossproduct(P that) { return this.det(that); } P half(P q) { return normalize().add(q.normalize()); } double dist(P to) { return sub(to).length(); } double signedParallelogramArea(P b, P c) { return (b.sub(this).crossproduct(c.sub(this))); } boolean isCollinearWith(P b, P c) { return abs(signedParallelogramArea(b, c)) <= EPS; } // is going from this to b to c a CCW turn? Do not use if points may be // collinear boolean isCCW(P b, P c) { return signedParallelogramArea(b, c) > 0; } double signedTriangleArea(P b, P c) { return signedParallelogramArea(b, c) / 2.0; } // memory-optimized version of this.sub(to).length2() that avoids an // intermediate object double dist2(P to) { double dx = this.x - to.x; double dy = this.y - to.y; return dx * dx + dy * dy; } /** * Compute x for a * x + b = 0 and ||x|| = C where 'this' is a. Care must be * taken to handle the case where either a.x or a.y is near zero. */ P[] solveDotProductConstrainedByNorm(double b, double C) { P a = this; if (a.isOrigin()) throw new Error("degenerate case"); boolean transpose = abs(a.x) > abs(a.y); a = transpose ? new P(a.y, a.x) : a; Double[] x = solvequadratic(a.length2(), 2.0 * b * a.x, b * b - a.y * a.y * C * C); P[] p = new P[x.length]; for (int i = 0; i < x.length; i++) { double x1 = x[i]; double x2 = ((-b - a.x * x1) / a.y); p[i] = transpose ? new P(x2, x1) : new P(x1, x2); } return p; } @Override public int compareTo(P that) { if (abs(this.x - that.x) > EPS) return Double.compare(this.x, that.x); return Double.compare(this.y, that.y); } } static class HP extends P { // Hashable Point HP(double x, double y) { super(x, y); } @Override public int hashCode() { return Double.hashCode(x + 32768 * y); } @Override public boolean equals(Object _that) { HP that = (HP) _that; return this.x == that.x && this.y == that.y; } } /** * Sort points by polar angle relative to center, using trig. This is a * counter-clockwise sort with zero at 3 o'clock. */ static Comparator<P> makePolarAngleComparatorTrig(final P center) { return new Comparator<P>() { public int compare(P a, P b) { double thetaa = a.sub(center).theta(); double thetab = b.sub(center).theta(); if (thetaa < 0) thetaa += 2 * PI; if (thetab < 0) thetab += 2 * PI; int c = Double.compare(thetaa, thetab); if (c != 0) return c; return Double.compare(b.x, a.x); // arbitrary tie-breaker } }; } /** * Sort points by polar angle relative to center, w/o trig. This is a * counter-clockwise sort with zero at 3 o'clock. */ static Comparator<P> makePolarAngleComparator(final P center) { return new Comparator<P>() { public int compare(P a, P b) { // orientation() requires that a and b lie in the same half-plane if (a.y >= center.y && b.y < center.y) return -1; if (b.y >= center.y && a.y < center.y) return 1; int orientation = (int) Math.signum(center.signedParallelogramArea(b, a)); if (orientation != 0) return orientation; return Double.compare(b.x, a.x); // arbitrary tie-breaker } }; } /* * Solve a * x^2 + b * x + c == 0 Returns 0, 1, or 2 solutions. If 2 solutions * x1, x2, guarantees that x1 < x2 */ static Double[] solvequadratic(double a, double b, double c) { double D = b * b - 4 * a * c; if (D < -EPS) return new Double[] {}; D = max(D, 0); if (D == 0) return new Double[] { -b / 2.0 / a }; double d = sqrt(D); // Numerically more stable, see // https://en.wikipedia.org/wiki/Loss_of_significance#A_better_algorithm if (signum(b) == 0) return new Double[] { d / 2.0 / a, -d / 2.0 / a }; double x1 = (-b - signum(b) * d) / (2 * a); double x2 = c / (a * x1); return new Double[] { Math.min(x1, x2), Math.max(x1, x2) }; } /* * The Line/Circle classes provide a number of methods that require dealing with * floating point precision issues. Default EPS to a suitable value, such as * 1e-6, which should work for many problems in which the input coordinates are * in integers and subsequently inexact floating point values are being * computed. */ static double EPS = 1e-6; /* * A line denoted by two points p and q. For internal computations, we use the * parametric representation of the line as p + t d where d = q - p. For * convenience, we compute and store d in the constructor. Most methods hide the * parametric representation of the line, but it is exposed via * getPointFromParameter and intersectionParameters for those problems that need * it. * * The line may be interpreted either as a line segment denoted by the two end * points, or as the infinite line determined by these two points. Intersection * methods are provided for both cases. */ static class Line { P p, q, d; Line(P p, P q) { this.p = p; this.q = q; d = q.sub(p); } P getPointFromParameter(double t) { return p.add(d.scale(t)); } // reflect vector across vector (as if line originated at (0, 0)) P reflect(P d2) { return d.reflect(d2); } // reflect point across (infinite) line P reflectPoint(P r) { return reflect(r.sub(p)).add(p); } // project p onto this (infinite) line. Returns point on line P project(P a) { return p.add(d.project(a.sub(p))); } // return distance of point P from this (infinite) line. double distance(P a) { return project(a).dist(a); } @Override public String toString() { return String.format("[%s => %s]", p, q); } /* * Point of intersection of this line segment with another line segment. Returns * only points that lie inside both line segments, else null. * * Result may include points "just outside" the bounds, given EPS. */ P intersectsInBounds(Line l) { double[] st = intersectionParameters(l); if (st == null) return null; // check that point of intersection is in direction 'd' // and within segment bounds double s = st[0]; double t = st[1]; if (s >= -EPS && s <= 1 + EPS && -EPS <= t && t <= 1 + EPS) return getPointFromParameter(s); return null; } /* * Point of intersection of this (infinite) line with other (infinite) line. * Return null if collinear. */ P intersects(Line l) { double[] st = intersectionParameters(l); if (st != null) return getPointFromParameter(st[0]); return null; } /* * Intersect this line with that line Solves: this.p + s * this.d == l.p + t l.d * Return null if lines are collinear Else returns [s, t]. */ double[] intersectionParameters(Line l) { P dneg = p.sub(q); double D = l.d.det(dneg); // Use Cramer's rule; see text if (D == 0.0) return null; P rp = p.sub(l.p); return new double[] { l.d.det(rp) / D, rp.det(dneg) / D }; } /* * Compute points of intersection of this infinite line with a circle. Computes * projection 'x' of c.c onto line, then computes x +/- d.scaleToLength(h) where * h is computed via Pythagoras. Sorted by decreasing 't' (as would be used in * getPointFromParameter) * * May return two points even if line is a tangent. */ P[] intersectsCircle(Circle c) { P x = project(c.c); double D = x.dist(c.c); // outside by more than EPS if (D > c.R + EPS) return new P[0]; double h = sqrt(max(0, c.R * c.R - D * D)); if (h == 0) return new P[] { x }; // EPS (!?) return new P[] { x.add(d.scaleToLength(h)), x.add(d.scaleToLength(-h)) }; } /* * Compute points of intersection of this infinite line with a circle. * * Solves a + t * b = c + r subject to ||r|| = R Returns zero, one, or two * points on the periphery, e.g. c + r[0,1], sorted by decreasing 't'. * Alternative version which requires solving quadratic equation. * * Careful: set EPS if you need to handle round-off error in discriminant. */ P[] intersectsCircleAlternative(Circle c) { P ca = c.c.sub(p); P d = q.sub(p); Double[] t = solvequadratic(d.length2(), -2 * d.dot(ca), ca.length2() - c.R * c.R); P[] r = new P[t.length]; for (int i = 0; i < t.length; i++) r[i] = p.add(d.scale(t[i])); return r; } /** * Is r contained within the line segment spanned by p/q, including their * endpoints? */ boolean isInBounds(P r) { return abs(p.dist(q) - p.dist(r) - q.dist(r)) <= EPS; } /** * Is r on the infinite line? */ boolean isOnLine(P r) { return r.isCollinearWith(p, q); } } /** * Alternative line implementation using the "general form" equation. * * a * x + b * y + c = 0 * * This is provided for problems in which a line may be given in general form in * the input. Compared to class Line, GLine: - is shorter, particularly when * only line/line and line/circle intersections are required. - does not support * those functions of Line that relate to LineSegment. */ static class GLine { // we represent a, b as a vector to benefit from the available dot/det routines. P n; // n = new P(a, b) --- this is the (right) normal vector to the line double c; GLine(double a, double b, double c) { this.n = new P(a, b); if (a == 0 && b == 0) throw new Error("a and b cannot both be zero"); this.c = c; } GLine(P p, P q) { this(p.y - q.y, q.x - p.x, p.det(q)); } P intersects(GLine that) { double D = n.det(that.n); if (D == 0.0) return null; return new P((this.n.y * that.c - that.n.y * this.c) / D, (that.n.x * this.c - this.n.x * that.c) / D); } double signedDistance(P p) { return (n.dot(p) + c) / n.length(); } double distance(P p) { return abs(signedDistance(p)); } // checks if on (infinite) line. boolean isOnLine(P p) { return signedDistance(p) <= EPS; } // checks if on the same side, no EPS boolean onSameSide(P p, P q) { return signum(signedDistance(p)) == signum(signedDistance(q)); } // angle of inclination to horizontal; result is in [0, pi] rad // XXX untested double theta() { double angle = atan2(n.x, -n.y); return angle < 0 ? (angle + PI) : angle; } // XXX untested boolean parallelWith(GLine that) { return n.det(that.n) <= EPS; } // XXX untested boolean perpendicularTo(GLine that) { return n.dot(that.n) <= EPS; } // circle-line intersection, refactored from // https://e-maxx-eng.appspot.com/geometry/circle-line-intersection.html P[] intersectsCircle(Circle C) { // shift line to center, this is undone by adding C.c before returning. double c = n.dot(C.c) + this.c; double n2 = n.length2(); double r = C.R; P p = n.scale(-c / n2).add(C.c); // undo shift to center if (c * c > r * r * n2 + EPS) { return new P[] {}; } else if (abs(c * c - r * r * n2) < EPS) { return new P[] { p }; } else { double d = r * r - c * c / n2; double m = sqrt(d / n2); P q = n.rightNormal().scale(m); return new P[] { p.add(q), p.sub(q) }; } } @Override public String toString() { return String.format("Line:(n=%s C=%f)", n, c); } } static class Circle { P c; double R; Circle(P c, double R) { this.c = c; this.R = R; } @Override public String toString() { return String.format("{%s, %.03f}", c, R); } /* Is this point inside the circle */ boolean isInside(P p) { return R > p.dist(c) - EPS; } /* Is this point on the circle's periphery */ boolean isOnCircle(P p) { return abs(p.dist(c) - R) <= EPS; } /* * a line segment is outside a circle if both end points are outside and if any * intersection points are outside the bounds of the line segment. */ boolean isOutside(Line l) { if (isInside(l.p) || isInside(l.q)) return false; P[] _is = l.intersectsCircle(this); if (_is.length > 1) for (P is : _is) if (l.isInBounds(is)) return false; return true; } /* Returns the tangent lines that the point p makes with this circle, if any. */ Line[] tangentLines(P p) { // Let c +/- r be the tangent points. Then there's a 'd' such that // p + d - r = c // Since d r = 0, we multiply by r and get // (p - c) r - ||r|| = 0 subject to ||r|| = R P[] r = p.sub(c).solveDotProductConstrainedByNorm(-R * R, R); Line[] tangents = new Line[r.length]; for (int i = 0; i < tangents.length; i++) tangents[i] = new Line(p, c.add(r[i])); return tangents; } /* * Compute points of intersection of this circle (c1, r1) with that circle (c2, * r2). Model as triangle equation m = c2 - c1 = r1 - r2 m = r1 - r2 -> m^2 = * r1^2 + r2^2 - 2 r1 r2 (squaring) -> r1 r2 = (r1^2 + r2^2 - m^2)/2 and by * multiplying by r1 we obtain m = r1 - r2 -> m r1 = r1^2 - r1 r2 -> m r1 = r1^2 * - (r1^2 + r2^2 - m^2)/2 -> m r1 + (r2^2 - r1^2 - m^2)/2 = 0 and ready for * solveDotProductConstrainedByNorm * * Note that if the circles are (apprx) touching, this function may return 0, 1, * or 2 intersection points, depending on which side of 0 the discriminant * falls. You will not get NaN. * * If the circles coincidence (same center and radius) this will throw an * 'degenerate case' error in solveDotProductConstrainedByNorm !!! */ P[] intersectsCircle(Circle that) { double r1 = this.R; double r2 = that.R; P m = that.c.sub(this.c); P[] r1sol = m.solveDotProductConstrainedByNorm((r2 * r2 - r1 * r1 - m.length2()) / 2, r1); // compute [c +/- r1] to obtain intersection points P[] is = new P[r1sol.length]; for (int i = 0; i < r1sol.length; i++) is[i] = this.c.add(r1sol[i]); return is; } /* * Shorter version of intersectsCircle that solves quadratic equation inline. * Assumes there are 2 intersection points. The vector 'mid' is where the * altitude of the triangle formed by the centers and the intersection point * hits the line connecting the centers. Its length is e. midn is normal to it * and its length is f. */ P[] intersectsCircleAlternative(Circle that) { P m = that.c.sub(this.c); double b = this.R * this.R; // div-by-zero if circles share center double e = (m.length2() + b - that.R * that.R) / 2 / m.length(); double f = sqrt(b - e * e); // NaN if circles don't intersect P[] is = new P[2]; P mid = this.c.add(m.scaleToLength(e)); P midn = m.rightNormal(); for (int i = 0; i < is.length; i++) { is[i] = mid.add(midn.scaleToLength(f)); f *= -1; } return is; } // returns true if this circle is outside that circle boolean isOutside(Circle that) { return this.c.dist(that.c) > (this.R + that.R); } // returns true if this circle is entirely contained inside that circle boolean isContainedIn(Circle that) { // extend line from that.c to this.c by radius R P m = this.c.sub(that.c); return that.isInside(this.c.add(m.scaleToLength(this.R))); } /* Construct smallest circle that circumscribes 2 points a and b. */ static Circle getCircumCircle(P a, P b) { P c = a.add(b).scale(.5); return new Circle(c, c.dist(a)); } /* Construct circle circumscribed by 3 points a, b, c */ static Circle getCircumCircle(P a, P b, P c) { P B = b.sub(a); P C = c.sub(a); double d = 2 * B.crossproduct(C); if (abs(d) < EPS) // points are collinear return getCircumCircle(new P(min(a.x, min(b.x, c.x)), min(a.y, min(b.y, c.y))), new P(max(a.x, max(b.x, c.x)), max(a.y, max(b.y, c.y)))); double z1 = B.length2(); double z2 = C.length2(); P cc = new P(C.y * z1 - B.y * z2, B.x * z2 - C.x * z1).scale(1.0 / d); return new Circle(cc.add(a), cc.length()); } /* * Find minimum enclosing circle for a set of points. Peter, we need a source * for this algorithm and its expected complexity. */ static Circle minEnclosingCircle(P[] p) { if (p.length == 0) return new Circle(new P(0, 0), 0); if (p.length == 1) return new Circle(p[0], 0); Collections.shuffle(Arrays.asList(p)); Circle circle = getCircumCircle(p[0], p[1]); for (int i = 2; i < p.length; i++) { if (!circle.isInside(p[i])) { circle = getCircumCircle(p[0], p[i]); for (int j = 1; j < i; j++) { if (!circle.isInside(p[j])) { circle = getCircumCircle(p[j], p[i]); for (int k = 0; k < j; k++) { if (!circle.isInside(p[k])) { circle = getCircumCircle(p[i], p[j], p[k]); } } } } } } return circle; } } /** * Some basic operations on Polygons. */ static class Polygon { P[] p; // open form, p[0] connects to p[n-1] // Constructors clone original array/collection Polygon(Collection<P> c) { this.p = c.toArray(new P[c.size()]); } Polygon(P[] p) { this.p = (P[]) p.clone(); } /* Absolute of signed triangle areas */ double signedArea() { double area = 0.0; for (int i = 0; i < p.length; i++) { area += p[i].det(p[(i + 1) % p.length]); } return area / 2.0; } double absoluteArea() { return abs(signedArea()); } /* * Returns an P[] array representing an open shape that is the convex hull of * the given array of points, or null if less than 2 points were given. */ public Polygon convexHull() { if (p.length < 2) return null; // (0) find the lowest point, breaking ties to the right final P min = Collections.min(Arrays.asList(p), new Comparator<P>() { public int compare(P p1, P p2) { int y = Double.valueOf(p1.y).compareTo(p2.y); return y != 0 ? y : Double.valueOf(p1.x).compareTo(p2.x); } }); // (1) sort points by angle from pivot Arrays.sort(p, new Comparator<P>() { public int compare(P p1, P p2) { double o = min.signedParallelogramArea(p1, p2); // crossproduct if (o != 0) return -(int) Math.signum(o); // if collinear, use distance to break tie return Double.valueOf(min.dist(p1)).compareTo(min.dist(p2)); } }); // (3) create stack Stack<P> hull = new Stack<P>(); assert p[0] == min; hull.push(p[0]); hull.push(p[1]); // (4) select points that maintain left turns for (int i = 2; i < p.length; i++) { P next = p[i]; while (hull.size() >= 2) { P snd = hull.get(hull.size() - 2); P top = hull.peek(); if (snd.isCCW(top, next)) // keep break; hull.pop(); // discard } // keep current point hull.push(next); } return new Polygon(hull); } /* * "Point-in-Polygon" PIP tests. Return true if point is contained in this * polygon * * All of these tests may return 0 or 1 for points on the boundary. A separate * test is required to determine if a point is on the boundary. */ public boolean contains(P q) { return contains_WN(q); } /* * Crossing-number based algorith due to Wm. Randolph Franklin. Works only for * simple polygons. */ private boolean contains_CN(P q) { boolean c = false; for (int i = 0, j = p.length - 1; i < p.length; j = i++) { if ((((p[i].y <= q.y) && (q.y < p[j].y)) || ((p[j].y <= q.y) && (q.y < p[i].y))) && (q.x < (p[j].x - p[i].x) * (q.y - p[i].y) / (p[j].y - p[i].y) + p[i].x)) c = !c; } return c; } /* * Winding numbers based algorithm, which also works for self-intersecting * polygons. http://geomalgorithms.com/a03-_inclusion.html describes this as the * always preferred algorithm. * * Return: wn = the winding number (=0 only when P is outside) */ public boolean contains_WN(P q) { int wn = 0; // the winding number counter // loop through all edges of the polygon int n = p.length; for (int i = 0; i < n; i++) { // edge from V[i] to V[i+1] P p = this.p[i], pn = this.p[(i + 1) % n]; if (p.y <= q.y) { // start y <= P.y if (pn.y > q.y) // an upward crossing if (p.isCCW(pn, q)) // P left of edge ++wn; // have a valid up intersect } else { // start y > P.y (no test needed) if (pn.y <= q.y) // a downward crossing if (!p.isCCW(pn, q)) // P right of edge --wn; // have a valid down intersect } } return wn != 0; } /** * Is q on the boundary of this polygon? */ public boolean onBoundary(P q) { int n = p.length; for (int i = 0; i < n; i++) { P pi = this.p[i], pj = this.p[(i + 1) % n]; if (new Line(pi, pj).isInBounds(q)) return true; } return false; } @Override public String toString() { return Arrays.toString(p); } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /* public class _908C { } */ public class _908C { public void solve() throws FileNotFoundException { InputStream inputStream = System.in; InputHelper in = new InputHelper(inputStream); // actual solution int n = in.readInteger(); double r = in.readInteger(); double[] x = new double[n]; for (int i = 0; i < n; i++) { x[i] = in.readInteger(); } double[] ans = new double[n]; ans[0] = r; for (int i = 1; i < n; i++) { double cans = r; for (int j = 0; j < i; j++) { double dis = Math.abs(x[j] - x[i]); if (dis <= 2 * r) { if (dis == 2 * r) { cans = Math.max(cans, ans[j]); continue; } else if (x[i] == x[j]) { cans = Math.max(cans, ans[j] + 2 * r); continue; } cans = Math.max(cans, ans[j] + Math.sqrt((4 * (r * r)) - dis * dis)); } } ans[i] = cans; } for (int i = 0; i < n; i++) { System.out.print(ans[i] + " "); } // end here } public static void main(String[] args) throws FileNotFoundException { (new _908C()).solve(); } class InputHelper { StringTokenizer tokenizer = null; private BufferedReader bufferedReader; public InputHelper(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader, 16384); } public String read() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = bufferedReader.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } public Integer readInteger() { return Integer.parseInt(read()); } public Long readLong() { return Long.parseLong(read()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int r = in.nextInt(); int[] xs = new int[n]; for (int i = 0; i < n; i++) xs[i] = in.nextInt(); double[] ys = new double[n]; for (int i = 0; i < n; i++) { int x = xs[i]; double y = r; for (int j = 0; j < i; j++) { y = Math.max(y, calc(xs[j], ys[j], x, r)); } ys[i] = y; } for (int i = 0; i < n; i++) { out.printf("%.10f ", ys[i]); } out.println(); } private double calc(int x, double y, int x1, int r) { int dx = Math.abs(x - x1); if (dx > 2 * r) return 0; double dy = Math.sqrt(4 * r * r - dx * dx); return y + dy; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in), 32768); } public String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } public boolean hasNext() { while (st == null || !st.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; st = new StringTokenizer(s); } return true; } public String next() { hasNext(); return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Codeforces { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); final double eps = 1e-7; String toks[] = in.readLine().split(" "); int n = Integer.parseInt(toks[0]); double r = Double.parseDouble(toks[1]); double x[] = new double[n]; toks = in.readLine().split(" "); for (int i = 0; i < n; i++) { x[i] = Double.parseDouble(toks[i]); } double lo, hi, mid; double y[] = new double[n]; y[0] = r; for (int i = 1; i < n; i++) { y[i] = r; for(int j=0; j<i; j++) { lo = y[j]; hi = 2000*2000; while( Math.abs(hi-lo) >= eps ) { mid = (hi+lo)/2; if( Math.sqrt( (x[i]-x[j])*(x[i]-x[j]) + (y[j]-mid)*(y[j]-mid) ) + eps > 2*r ) { hi = mid; } else { lo = mid; } } if(Math.sqrt( (x[i]-x[j])*(x[i]-x[j]) + (y[j]-lo)*(y[j]-lo) ) < 2*r + eps) { y[i] = Math.max(y[i], lo); } } } for (double z : y) { System.out.printf(Locale.US, "%.7f ", z); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.io.BufferedOutputStream; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Aeroui */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Kattio in = new Kattio(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Kattio in, PrintWriter out) { int n = in.nextInt(); int r = in.nextInt(); double[] xs = new double[n]; double[] ys = new double[n]; TreeSet<TaskC.Pair> set = new TreeSet<>(); for (int i = 0; i < n; ++i) { xs[i] = in.nextDouble(); ys[i] = (double) Integer.MIN_VALUE; if (i == 0) { // the first one out.printf("%f", (double) r); ys[i] = (double) r; set.add(new TaskC.Pair(xs[i], ys[i])); } else { for (TaskC.Pair p : set) { double maximum = p.x; double diffX = (xs[i] - maximum) * (xs[i] - maximum); if (diffX <= r * r * 4.0) { ys[i] = Math.max(ys[i], p.y + Math.sqrt(r * r * 4.0 - diffX)); continue; } } if (ys[i] < 0) ys[i] = (double) r; set.add(new TaskC.Pair(xs[i], ys[i])); out.printf(" %f", ys[i]); } } } private static class Pair implements Comparable<TaskC.Pair> { double x; double y; public Pair(double x, double y) { this.x = x; this.y = y; } public int compareTo(TaskC.Pair p) { if (this.y - p.y < 0) return 1; return -1; } } } static class Kattio extends PrintWriter { private BufferedReader r; private String line; private StringTokenizer st; private String token; public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = in.nextInt(); double r = in.nextInt(); double[] x = new double[n+1]; double[] y = new double[n+1]; for (int i = 1; i <= n; i++) { x[i] = in.nextInt(); } int[] lastx = new int[1001]; for (int i = 1; i <= n; i++) { double s = x[i] - r, e = x[i] + r; for (int j = (int)Math.max(0, s); j <= (int)Math.min(1000, e); j++) { if (lastx[j] == 0) { y[i] = Math.max(y[i], findY(x[i], x[i], 0 - r, 2 * r)); } else { y[i] = Math.max(y[i], findY(x[lastx[j]], x[i], y[lastx[j]], 2 * r)); } lastx[j] = i; } } for (int i = 1; i <= n; i++) { out.println(y[i]); } out.close(); } public static double findY(double x1, double x2, double y1, double d) { return Math.max(y1 + Math.sqrt(-1 * Math.pow(x1, 2) + 2 * x1 * x2 + Math.pow(d, 2) - Math.pow(x2, 2)), y1 - Math.sqrt(-1 * Math.pow(x1, 2) + 2 * x1 * x2 + Math.pow(d, 2) - Math.pow(x2, 2))); } static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.math.BigInteger; import java.util.Scanner; public class c { public static void main(String[] args) { Scanner in = new Scanner(System.in); int num = in.nextInt(); int rad = in.nextInt(); int[] start = new int[num]; for(int i=0; i<num; i++) start[i] = in.nextInt(); // If you can hack doubles that's dumb double[] finalY = new double[num]; double hyp = rad*2; for(int cur=0; cur<num; cur++){ double stopAt = rad; for(int comp=0; comp<cur; comp++){ if(Math.abs(start[comp]-start[cur]) > rad*2) continue; double base = Math.abs(start[comp]-start[cur]); double ny = Math.sqrt(hyp*hyp - base*base) + finalY[comp]; stopAt = Math.max(ny, stopAt); } finalY[cur] = stopAt; } for(int i=0; i<num; i++) System.out.print(finalY[i]+" "); System.out.println(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import static java.lang.Math.*; public class C { public C () { int N = sc.nextInt(); int R = sc.nextInt(); int [] X = sc.nextInts(); double [] res = new double [N]; for (int i : rep(N)) { res[i] = R; for (int j : rep(i)) { int D = abs(X[i] - X[j]); if (D <= 2*R) { double H = sqrt(4.0*R*R - 1.0*D*D); res [i] = max(res[i], res[j] + H); } } } exit(res); } private static int [] rep(int N) { return rep(0, N); } private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } //////////////////////////////////////////////////////////////////////////////////// private final static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static void exit (Object o, Object ... A) { IOUtils.print(o, A); IOUtils.exit(); } private static class IOUtils { public static class MyScanner { public String next() { newLine(); return line[index++]; } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { line = null; return readLine(); } public String [] nextStrings() { return split(nextLine()); } public int [] nextInts() { String [] L = nextStrings(); int [] res = new int [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final 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 void start() { if (t == 0) t = millis(); } private static void append(StringBuilder b, Object o, String delim) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) append(b, java.lang.reflect.Array.get(o, i), delim); } else if (o instanceof Iterable<?>) for (Object p : (Iterable<?>) o) append(b, p, delim); else { if (o instanceof Double) o = new java.text.DecimalFormat("#.############").format(o); b.append(delim).append(o); } } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void print(Object o, Object ... A) { pw.println(build(o, A)); } private static void err(Object o, Object ... A) { System.err.println(build(o, A)); } private static void exit() { IOUtils.pw.close(); System.out.flush(); err("------------------"); err(IOUtils.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; } } public static void main (String[] args) { new C(); IOUtils.exit(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; import java.lang.*; import java.math.*; public class USACO { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(reader.readLine()," "); int n= Integer.parseInt(st.nextToken()); int r= Integer.parseInt(st.nextToken()); StringTokenizer st2 = new StringTokenizer(reader.readLine()," "); double[][] coord = new double[n][2]; for (int i=0;i<n;i++) { coord[i][0] = Integer.parseInt(st2.nextToken()); double y=r; for (int j=0;j<i;j++) { if (coord[j][0]<=coord[i][0]+2*r&&coord[j][0]>=coord[i][0]-2*r) { if (coord[j][1]+Math.sqrt(4*r*r-(coord[i][0]-coord[j][0])*(coord[i][0]-coord[j][0]))>y) { y=coord[j][1]+Math.sqrt(4*r*r-(coord[i][0]-coord[j][0])*(coord[i][0]-coord[j][0])); } } } coord[i][1]=y; } for (int i=0;i<n;i++) { System.out.print(coord[i][1]); if (i<n-1) { System.out.print(" "); } else { System.out.print("\n"); } } reader.close(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.Optional; import java.util.Scanner; import java.util.StringJoiner; public class Main { public static void main(String[] args) { Main main = new Main(); main.solveC(); } private void solveA() { Scanner sc = new Scanner(System.in); String str = sc.next(); long answer = str.chars().filter( asc -> asc == 'a' || asc == 'i' || asc == 'u' || asc == 'e' || asc == 'o' || asc == '1' || asc == '3' || asc == '5' || asc == '7' || asc == '9').count(); System.out.println(answer); } private void solveB() { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); sc.nextLine(); char[][] map = new char[N + 2][M + 2]; map[0] = new char[M + 2]; map[N + 1] = new char[M + 2]; int s_r = -1; int s_c = -1; for (int c = 0; c < M + 2; c++) { map[0][c] = '#'; map[N + 1][c] = '#'; } for (int r = 1; r <= N; r++) { map[r][0] = '#'; String line = sc.nextLine(); for (int c = 1; c <= M; c++) { map[r][c] = line.charAt(c - 1); if (map[r][c] == 'S') { s_r = r; s_c = c; } } map[r][M + 1] = '#'; } String inst = sc.next(); long ans = 0L; for (int left = 0; left < 4; left++) { for (int up = 0; up < 4; up++) { for (int right = 0; right < 4; right++) { for (int down = 0; down < 4; down++) { if (left == up || left == right || left == down || up == right || up == down || right == down) { continue; } int r_r = s_r; int r_c = s_c; for (int i = 0; i < inst.length(); i++) { char asc = inst.charAt(i); if (asc == '0' + left) { r_c--; } if (asc == '0' + up) { r_r--; } if (asc == '0' + right) { r_c++; } if (asc == '0' + down) { r_r++; } if (map[r_r][r_c] == '#') { break; } if (map[r_r][r_c] == 'E') { ans++; break; } } } } } } System.out.println(ans); } private void solveC() { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); double R = 0.0 + sc.nextInt(); double[] x = new double[N]; double[] y = new double[N]; for (int i = 0; i < N; i++) { x[i] = 0.0 + sc.nextInt(); double max_y = R; for (int j = 0; j < i; j++) { double dy = 4 * R * R - (x[i] - x[j]) * (x[i] - x[j]); if (dy >= 0) { double tmp_y = y[j] + Math.sqrt(dy); if (max_y < tmp_y) { max_y = tmp_y; } } } y[i] = max_y; } StringJoiner sj = new StringJoiner(" "); for (int i = 0; i < N; i++) { sj.add(String.valueOf(y[i])); } System.out.println(sj.toString()); } private void solveD() { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); System.out.println(N); } private void solveE() { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); System.out.println(N); } private void solveF() { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); System.out.println(N); } interface Graph { void link(int from, int to, long cost); Optional<Long> getCost(int from, int to); int getVertexNum(); } interface FlowResolver { long maxFlow(int from, int to); } /** * グラフの行列による実装 * 接点数の大きいグラフで使うとMLEで死にそう */ class ArrayGraph implements Graph { private Long[][] costArray; private int vertexNum; public ArrayGraph(int n) { costArray = new Long[n][]; for (int i = 0; i < n; i++) { costArray[i] = new Long[n]; } vertexNum = n; } @Override public void link(int from, int to, long cost) { costArray[from][to] = new Long(cost); } @Override public Optional<Long> getCost(int from, int to) { return Optional.ofNullable(costArray[from][to]); } @Override public int getVertexNum() { return vertexNum; } } /** * DFS(深さ優先探索)による実装 * 計算量はO(E*MaxFlow)のはず (E:辺の数, MaxFlow:最大フロー) */ class DfsFlowResolver implements FlowResolver { private Graph graph; public DfsFlowResolver(Graph graph) { this.graph = graph; } /** * 最大フロー(最小カット)を求める * @param from 始点(source)のID * @param to 終点(target)のID * @return 最大フロー(最小カット) */ public long maxFlow(int from, int to) { long sum = 0L; long currentFlow; do { currentFlow = flow(from, to, Long.MAX_VALUE / 3, new boolean[graph.getVertexNum()]); sum += currentFlow; } while (currentFlow > 0); return sum; } /** * フローの実行 グラフの更新も行う * @param from 現在いる節点のID * @param to 終点(target)のID * @param current_flow ここまでの流量 * @param passed 既に通った節点か否かを格納した配列 * @return 終点(target)に流した流量/戻りのグラフの流量 */ private long flow(int from, int to, long current_flow, boolean[] passed) { passed[from] = true; if (from == to) { return current_flow; } for (int id = 0; id < graph.getVertexNum(); id++) { if (passed[id]) { continue; } Optional<Long> cost = graph.getCost(from, id); if (cost.orElse(0L) > 0) { long nextFlow = current_flow < cost.get() ? current_flow : cost.get(); long returnFlow = flow(id, to, nextFlow, passed); if (returnFlow > 0) { graph.link(from, id, cost.get() - returnFlow); graph.link(id, from, graph.getCost(id, from).orElse(0L) + returnFlow); return returnFlow; } } } return 0L; } } /** * 1-indexedのBIT配列 */ class BinaryIndexedTree { private long[] array; public BinaryIndexedTree(int size) { this.array = new long[size + 1]; } /** * 指定した要素に値を加算する * 計算量はO(logN) * @param index 加算する要素の添字 * @param value 加算する量 */ public void add(int index, long value) { for (int i = index; i < array.length; i += (i & -i)) { array[i] += value; } } /** * 1〜指定した要素までの和を取得する * 計算量はO(logN) * @param index 和の終端 * @return 1〜indexまでの和 */ public long getSum(int index) { long sum = 0L; for (int i = index; i > 0; i -= (i & -i)) { sum += array[i]; } return sum; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author phantom11 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int N = in.nextInt(); int r = in.nextInt(); int i, j; BigDecimal initial = new BigDecimal(10); initial = initial.pow(100); int x[] = new int[N]; BigDecimal y[] = new BigDecimal[N]; Arrays.fill(y, initial); for (i = 0; i < N; i++) { x[i] = in.nextInt(); } for (i = 0; i < N; i++) { BigDecimal y2 = new BigDecimal(r); for (j = 0; j < i; j++) { if (Math.abs(x[i] - x[j]) <= 2 * r) { double xDiff = x[i] - x[j]; xDiff *= xDiff; xDiff = 4 * r * r - xDiff; xDiff = Math.sqrt(xDiff); BigDecimal yNew = new BigDecimal(xDiff); yNew = yNew.add(y[j]); if (yNew.compareTo(y2) > 0) { y2 = yNew; } } } y[i] = y2; } for (i = 0; i < N; i++) { out.print(y[i] + " "); } } } static class InputReader { BufferedReader in; StringTokenizer tokenizer = null; public InputReader(InputStream inputStream) { in = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } catch (IOException e) { return null; } } public int nextInt() { return Integer.parseInt(next()); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void close() { writer.close(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
//package GoodBye2017; import java.io.*; import java.util.*; public class c { public static void main(String[] args) throws Exception{ new c(new Reader()); } public c(Reader rr) throws IOException{ int n=rr.ni(); double r=rr.nd(); HashMap<Integer, Double> disk=new HashMap<Integer, Double>(); for(int i=0; i<n; i++){ int next=rr.ni(); if(disk.isEmpty()){ disk.put(next, r); System.out.print(r+" "); } else{ double high=r; for(Map.Entry<Integer, Double> it: disk.entrySet()){ if(2*r<next-it.getKey()) continue; double tempHigh=pyth(Math.abs(next-it.getKey()),r*2)+it.getValue(); if(tempHigh>high){ high=tempHigh; } } disk.put(next, high); System.out.print(high+" "); } } } public double pyth(double a, double c){ return Math.sqrt(Math.pow(c, 2)-Math.pow(a, 2)); } static class Reader{ private DataInputStream din; private byte[] buffer=new byte[1024]; private int bufP, bytR; public Reader() throws IOException{ din=new DataInputStream(System.in); bufP=bytR=0; } public Reader(String file) throws IOException{ din=new DataInputStream(new FileInputStream(file)); bufP=bytR=0; } private String rl() throws IOException{ byte[] buf=new byte[1024]; int cnt=0, c; while((c=read())!=-1){ if(c=='\n') break; buf[cnt++]=(byte)c; } return new String(buf, 0, cnt); } private int ni() throws IOException{ int num=0; byte c=read(); while(c<=' ') c=read(); boolean neg=(c=='-'); if(neg) c=read(); do{ num=num*10+c-'0'; } while((c=read())>='0'&&c<='9'); if(neg) return -num; return num; } private long nl() throws IOException{ long num=0; byte c=read(); while(c<=' ') c=read(); boolean neg=(c=='-'); if(neg) c=read(); do{ num=num*10+c-'0'; } while((c=read())>='0'&&c<='9'); if(neg) return -num; return num; } private double nd() throws IOException{ return Double.parseDouble(ns()); } private char nc() throws IOException{ return (char)next(); } private String ns() throws IOException{ int c=next(); StringBuilder sb=new StringBuilder(); while(!(isChar(c))){ sb.appendCodePoint(c); c=read(); } return sb.toString(); } private char[] ns(int n) throws IOException{ char[] buf=new char[n]; int c=next(), r=0; while(r<n&&!(isChar(c))){ buf[r++]=(char)c; c=next(); } return n==r?buf:Arrays.copyOf(buf, r); } private char[][] nm(int n, int m) throws IOException{ char[][] map=new char[n][]; for(int i=0; i<n; i++) map[i]=ns(m); return map; } private int[] na(int n) throws IOException{ int[] a=new int[n]; for(int i=0; i<n; i++) a[i]=ni(); return a; } private boolean isChar(int c) throws IOException{ return !(c>=33&&c<=126); } private int next() throws IOException{ int c; while((c=read())!=-1&&isChar(c)); return c; } private byte read() throws IOException{ if(bufP==bytR){ bytR=din.read(buffer, bufP=0, 1024); if(bytR==-1) buffer[0]=-1; } return buffer[bufP++]; } public void close() throws IOException{ if(din==null) return; din.close(); } } }
quadratic
908_C. New Year and Curling
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.HashMap; import java.util.HashSet; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class c { public static void main(String args[]) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); //BEGIN HERE int n = in.nextInt(); int r = in.nextInt(); int xs[] = new int[n]; for(int i = 0; i < n; i++) xs[i] = in.nextInt(); double ys[] = new double[n]; ys[0] = r; for(int i = 1; i < n; i++) { double worst = r; for(int j = 0; j < i; j++) { if(xs[i] == xs[j]) { worst = Math.max(worst, ys[j] + r + r); }else if((xs[i] - xs[j]) * (xs[i] - xs[j]) <= 4*r*r ) { double hypot = r + r; double adj = Math.abs((xs[i] - xs[j])); double theta = Math.acos(adj/hypot); worst = Math.max(hypot * Math.sin(theta) + ys[j], worst); } } ys[i] = worst; } for(int i = 0; i < n; i++) out.printf("%.10f ",ys[i]); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = null; } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { if (st == null) { st = new StringTokenizer(br.readLine()); } String line = st.nextToken("\n"); st = null; return line; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } public static class combinatorics { static long modInv(long a, long b) { return 1 < a ? b - modInv(b % a, a) * b / a : 1; } static long factorial[], mod; combinatorics(int n, long MOD) { mod = MOD; factorial = new long[n + 1]; factorial[0] = 1; for (int i = 1; i <= n; i++) { factorial[i] = i * factorial[i - 1]; factorial[i] %= mod; } } static long nCr(int n, int r) { if (r > n) return 0; return (factorial[n] * modInv((factorial[n - r] * factorial[r]) % mod, mod)) % mod; } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return a * (b / gcd(a, b)); } } public static class DisjointSet { int p[], r[], s[]; int numDisjoint; DisjointSet(int N) { numDisjoint = N; r = new int[N]; s = new int[N]; p = new int[N]; for (int i = 0; i < N; i++) p[i] = i; } int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } void unionSet(int i, int j) { if (!isSameSet(i, j)) // if from different set { numDisjoint--; int x = findSet(i), y = findSet(j); if (r[x] > r[y]) { p[y] = x; // rank keeps the tree short s[x] += s[y]; } else { p[x] = y; if (r[x] == r[y]) r[y]++; s[y] += s[x]; } } } int sizeOfSet(int i) { return s[findSet(i)]; } }; }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pradyumn */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastReader in, PrintWriter out) { Debug debug = new Debug(out); int n = in.nextInt(); TaskC.Circle[] c = new TaskC.Circle[n]; double rr = in.nextInt(); for (int i = 0; i < n; ++i) { c[i] = new TaskC.Circle(); c[i].x = in.nextInt(); } ArrayList<TaskC.Circle> done = new ArrayList<>(); for (int i = 0; i < n; ++i) { TaskC.Circle cur = c[i]; double ans = Double.MIN_VALUE; for (int j = 0; j < done.size(); ++j) { TaskC.Circle dd = done.get(j); if (Double.compare(2 * rr, Math.abs(dd.x - cur.x)) < 0) continue; double temp = Math.sqrt(4 * rr * rr - (cur.x - dd.x) * (cur.x - dd.x)) + dd.y; ans = Math.max(ans, temp); } if (ans == Double.MIN_VALUE) ans = rr; cur.y = ans; done.add(cur); } for (TaskC.Circle cc : done) { out.printf("%.12f ", cc.y); } } static class Circle implements Comparable<TaskC.Circle> { double x; double y; public boolean equals(Object o) { if (o == null) return false; if (o == this) return true; if (o.getClass() != this.getClass()) return false; TaskC.Circle c = (TaskC.Circle) o; return Double.compare(x, c.x) == 0 && Double.compare(y, c.y) == 0; } public int compareTo(TaskC.Circle o) { if (Double.compare(o.x, x) != 0) { return Double.compare(x, o.x); } return Double.compare(y, o.y); } } } static class Debug { PrintWriter out; boolean oj; long timeBegin; Runtime runtime; public Debug(PrintWriter out) { oj = System.getProperty("ONLINE_JUDGE") != null; this.out = out; this.timeBegin = System.currentTimeMillis(); this.runtime = Runtime.getRuntime(); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
/** * Created by Ariana Herbst on 12/29/17. */ import java.util.*; import java.io.*; /** * Created by Ariana Herbst on 12/29/17 */ public class GB2017C { static int n, r; static int[] x; static Map<Integer, Double> horo; public static void main(String[] args) { FastScanner sc = new FastScanner(); StringBuilder sb = new StringBuilder(); n = sc.nextInt(); r = sc.nextInt(); x = new int[n]; horo = new HashMap<Integer, Double>(); for (int x = 0; x <= r*2; x++) { double y = 2.0 *Math.sqrt(r * r - (r - x/2.0) * (r - x/2.0)); horo.put(x, y); } for (int i = 0; i < n; i++) { x[i] = sc.nextInt(); } List<Double> y = new ArrayList<Double>(); for (int i = 0; i < n; i++) { double max = r; for (int j = 0; j < y.size(); j++) { int dx = intersects(i, j); if (dx >= 0) { double dy = horo.get(dx); max = Math.max(max, dy + y.get(j)); } } y.add(max); } for (int i = 0; i < n; i++) { sb.append(y.get(i) + " "); } System.out.println(sb); } static int intersects(int i, int j) { if (Math.abs(x[i] - x[j]) <= 2*r) { return 2*r - Math.abs(x[i] - x[j]); } else return -1; } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.InputMismatchException; public class Solution1 implements Runnable { static final int MAX = 1000000007; static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Solution1(),"Solution1",1<<26).start(); } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } static int lcm(int a, int b) { return (a*b)/gcd(a, b); } static int max= -1; public void run() { InputReader sc= new InputReader(System.in); PrintWriter w= new PrintWriter(System.out); int n = sc.nextInt(); int r = sc.nextInt(); int[] arr= new int[n]; for(int i = 0;i < n;i++){ arr[i] = sc.nextInt(); } double sqr = 2*r*2*r; double[] ans= new double[n]; for(int i = 0;i < arr.length;i++){ ans[i] = r*1.0; for(int j = 0;j < i;j++){ if(Math.abs(arr[i] - arr[j]) < 2*r){ ans[i] = Math.max(ans[i],Math.sqrt(sqr - Math.abs(arr[i] - arr[j])*Math.abs(arr[i]-arr[j])) + ans[j]); }else if(Math.abs(arr[i]-arr[j]) == 2*r){ ans[i] = Math.max(ans[i],ans[j]); } } } for(int i = 0;i < ans.length;i++){ System.out.printf("%.7f ",ans[i]); } w.close(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputScanner in = new InputScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputScanner in, PrintWriter out) { int[] arr = in.readIntArr(); int n = arr[0]; int r = arr[1]; int[] x = in.readIntArr(); for (int i = 0; i < n; i++) { x[i] += 999; } double[] h = new double[n]; int dsk[] = new int[3000]; Arrays.fill(dsk, -1); for (int i = 0; i < r; i++) { dsk[x[0] + i] = 0; dsk[x[0] - i - 1] = 0; } int rs = 4 * r * r; h[0] = r; for (int i = 1; i < n; i++) { double ch = r; for (int j = 0; j < r; j++) { if (dsk[x[i] + j] != -1) { int ind = dsk[x[i] + j]; int diff = x[ind] - x[i]; int diffs = diff * diff; int hs = rs - diffs; ch = Math.max(ch, h[ind] + Math.sqrt(hs)); } if (dsk[x[i] - j - 1] != -1) { int ind = dsk[x[i] - j - 1]; int diff = x[ind] - x[i]; int diffs = diff * diff; int hs = rs - diffs; ch = Math.max(ch, h[ind] + Math.sqrt(hs)); } } if (x[i] + r < 3000) { if (dsk[x[i] + r] != -1) { ch = Math.max(ch, h[dsk[x[i] + r]]); } } if (x[i] - r - 1 > 0) { if (dsk[x[i] - r - 1] != -1) { ch = Math.max(ch, h[dsk[x[i] - r - 1]]); } } for (int j = 0; j < r; j++) { dsk[x[i] + j] = i; dsk[x[i] - j - 1] = i; } h[i] = ch; } for (int i = 0; i < n; i++) { out.print(h[i] + " "); } out.println(); } } static class InputScanner { BufferedReader br; public InputScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String readLine() { String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } public String[] readStringArr() { return readLine().split(" "); } public int[] readIntArr() { String[] str = readStringArr(); int arr[] = new int[str.length]; for (int i = 0; i < arr.length; i++) arr[i] = Integer.parseInt(str[i]); return arr; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class C { private static double r, EPS=1e-10; public static void solve(FastScanner fs) { int n=fs.nextInt(); r=fs.nextInt(); int[] xCoords=fs.readArray(n); ArrayList<Point> placed=new ArrayList<>(); for (int x:xCoords) { double maxY=r; for (Point p:placed) maxY=Math.max(maxY, getNewY(p, x)); placed.add(new Point(x, maxY)); } for (Point p:placed) { System.out.printf("%.9f ", p.y); } } private static double getNewY(Point circleCenter, int x) { double dx=Math.abs(x-circleCenter.x); if (dx>r+r) return 0; if (dx<EPS) return circleCenter.y+r+r; double hypot=r+r; return circleCenter.y+Math.sqrt(hypot*hypot-(double)dx*dx); } static class Point { double x; double y; public Point(double x, double y) { this.x=x; this.y=y; } } public static void main(String[] args) throws NumberFormatException, IOException { FastScanner scanner = new FastScanner(System.in); solve(scanner); } private static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(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; } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; 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 Wolfgang Beyer */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int r = in.nextInt(); int[] x = in.readIntArray(n); double[] y = new double[n]; for (int i = 0; i < n; i++) { y[i] = r; for (int j = 0; j < i; j++) { double d = Math.abs(x[j] - x[i]); if (d <= 2 * r) { double yy = Math.sqrt(4.0 * r * r - d * d); y[i] = Math.max(y[i], y[j] + yy); } } } for (int i = 0; i < n; i++) { out.print(y[i] + " "); } } } static class InputReader { private static BufferedReader in; private static StringTokenizer tok; public InputReader(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public int[] readIntArray(int n) { int[] ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = nextInt(); } return ar; } public String next() { try { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); //tok = new StringTokenizer(in.readLine(), ", \t\n\r\f"); //adds commas as delimeter } } catch (IOException ex) { System.err.println("An IOException was caught :" + ex.getMessage()); } return tok.nextToken(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static ArrayList<ArrayList<Integer>> list; static HashSet<Integer> hs; static ArrayList<Integer> tmp; //int n=Integer.parseInt(br.readLine()); //int n=Integer.parseInt(st.nextToken()); //StringTokenizer st = new StringTokenizer(br.readLine()); public static double cal(int a,double b,int x,int r) { r*=2; double dis=(r*r) - Math.pow(Math.abs(a-x),2); dis=Math.sqrt(dis); dis+=b; return dis; } public static void main (String[] args) throws java.lang.Exception { int n,r; StringTokenizer st = new StringTokenizer(br.readLine()); n=Integer.parseInt(st.nextToken()); r=Integer.parseInt(st.nextToken()); int arr[] = new int[n+1]; double cen[] = new double[n+1]; int i,j; for(i=1;i<=n;i++) cen[i]=-1.0; st = new StringTokenizer(br.readLine()); for(i=1;i<=n;i++)arr[i]=Integer.parseInt(st.nextToken()); for(i=1;i<=n;i++) { int f=0; double max=-1.0; for(j=1;j<=n;j++) { if(i!=j && cen[j]!=-1.0 && (Math.abs(arr[i]-arr[j])<=2*r)) { max=Math.max(max,cal(arr[j],cen[j],arr[i],r)); f=1; } } // System.out.println(i+" "+max); if(f==1) cen[i]=max; else cen[i]=r*1.0; } for(i=1;i<=n;i++) System.out.print(cen[i]+" "); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.File; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.UnsupportedEncodingException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author MaxHeap */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastReader in, OutputWriter out) { int n = in.nextInt(); double r = in.nextInt(); double[] x = new double[n]; for (int i = 0; i < n; i++) { x[i] = in.nextDouble(); } double[] ans = new double[n]; ans[0] = r; for (int i = 1; i < n; i++) { ans[i] = r; double maxY = 0; for (int j = 0; j < i; j++) { if (Math.abs(x[j] - x[i]) <= 2.0 * r) { double y = ans[j] + Math.sqrt(4 * r * r - (x[j] - x[i]) * (x[j] - x[i])); ans[i] = Math.max(ans[i], y); } } } for (int i = 0; i < n; i++) { if (i > 0) out.print(" "); out.printf("%.8f", ans[i]); } } } static class FastReader { BufferedReader reader; StringTokenizer st; public FastReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { String line = reader.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static class OutputWriter extends PrintWriter { public OutputWriter(OutputStream os, boolean autoFlush) { super(os, autoFlush); } public OutputWriter(Writer out) { super(out); } public OutputWriter(Writer out, boolean autoFlush) { super(out, autoFlush); } public OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } public OutputWriter(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException { super(fileName, csn); } public OutputWriter(File file) throws FileNotFoundException { super(file); } public OutputWriter(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException { super(file, csn); } public OutputWriter(OutputStream out) { super(out); } public void flush() { super.flush(); } public void close() { super.close(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
/* ID: andrew42 LANG: JAVA TASK: PROG: */ import java.io.*; import java.util.*; import java.lang.*; public class curling { public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); int numD = input.nextInt(); double rad = input.nextInt(); int[] xC = new int[numD]; for (int i = 0; i < numD; i++){ xC[i] = input.nextInt(); } double[] maxY = new double[1001]; for (int i = 0; i < numD; i++){ double h = rad; for (int j = Math.max(1, xC[i]-(int)(2*rad)); j <= Math.min(1000, xC[i]+2*rad); j++){ if (maxY[j] > 0){ h = Math.max(h, Math.sqrt(4*rad*rad-(j-xC[i])*(j-xC[i]))+maxY[j]); } } System.out.print(h + " "); maxY[xC[i]] = h; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class Main { static double [] res; static double r; static double solve (int xMe, int xHim, int idxHim) { if (Math.abs(xMe - xHim) > 2 * r) return r; double hisY = res[idxHim]; double lo = hisY, hi = hisY + 2 * r, best = hi; for (int cnt = 0; cnt <= 50; cnt++) { double myY = (lo) + ((hi - lo) / 2); if (notIntersect(xMe, myY, xHim, hisY)) { best = Math.min(best, myY); hi = Math.max(lo, myY); } else lo = Math.min(hi, myY); } return best; } static boolean notIntersect (double x1, double y1, double x2, double y2) { return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) >= 2 * r * 2 * r; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); res = new double[n]; r = sc.nextInt(); int[] x = new int[n]; for (int i = 0; i < n; i++) x[i] = sc.nextInt(); for (int i = 0; i < n; i++) { double max = r; for (int j = 0; j < i; j++) { max = Math.max(max, solve(x[i], x[j], j)); } if (i > 0) out.print(" "); res[i] = max; out.printf("%.10f", max); } out.println(); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(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 { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; public class probC { static int r; static ArrayList<Circ> curr = new ArrayList<Circ>(); public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); r = sc.nextInt(); int[] xC = new int[n]; for(int i = 0; i < n; i++) xC[i] = sc.nextInt(); double ans[] = new double[n]; ans[0] = r; curr.add(new Circ(xC[0], r)); for(int i = 1; i < n; i++) { double max = r; for(int k = 0; k < curr.size(); k++) { double cur = curr.get(k).y+ Math.sqrt(4 * r*r - (xC[i]-curr.get(k).x)*(xC[i]-curr.get(k).x)); //System.out.println(cur + " " + max); if(4 * r*r - (xC[i]-curr.get(k).x)*(xC[i]-curr.get(k).x) >= 0) max = Math.max(cur, max); } ans[i] = max; curr.add(new Circ(xC[i], max)); //System.out.println(); } for(int i = 0; i < n; i++) System.out.print(ans[i] + " "); sc.close(); } static class Circ { double x, y; public Circ(double a, double b) { x=a; y=b; } public boolean isNT(Circ b) { double dist = Math.sqrt((x-b.x)*(x-b.x)+(y-b.y)*(y-b.y)); return dist > 2*r; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
//>>>BaZ<<<// import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static int dx[] = {-1,1,0,0}; static int dy[] = {0,0,1,-1}; static long MOD = 1000000007; static int INF = Integer.MAX_VALUE/10; static PrintWriter pw; static InputReader scan; //static MyFileReader1 ss; //static MyFileReader scan; static int ni() throws IOException{return scan.nextInt();} static long nl() throws IOException{return scan.nextLong();} static double nd() throws IOException{return scan.nextDouble();} static String ne() throws IOException{return scan.next();} static void pl() throws IOException {pw.println();} static void pl(Object o) throws IOException {pw.println(o);} static void p(Object o) throws IOException {pw.print(o+" ");} static void psb(StringBuilder sb) throws IOException {pw.print(sb);} public static void main(String[] args) { new Thread(null,null,"BaZ",99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws IOException { Calendar CAL1 = Calendar.getInstance(); CAL1.setTime(new Date()); scan = new InputReader(System.in); pw = new PrintWriter(System.out,true); //pw = new PrintWriter(new File("C://Users/Aman deep/Desktop/output.txt")); //ss = new MyFileReader1(); //scan = new MyFileReader(); StringBuilder sb = new StringBuilder(); int n = ni(); double r = ni(); double x[] = new double[n]; for(int i=0;i<n;++i) x[i] = nd(); double y[] = new double[n]; y[0] = r; for(int i=1;i<n;++i) { double max = -1; for(int j=0;j<i;++j) { double xx = 4*r*r-(x[i]-x[j])*(x[i]-x[j]); if(xx>=0) max = max(max,sqrt(xx)+y[j]); } if(max==-1) max = r; y[i] = max; } for(int i=0;i<n;++i) p(y[i]); pl(); Calendar CAL2 = Calendar.getInstance(); CAL2.setTime(new Date()); double Execution_Time = (double)(CAL2.getTimeInMillis()-CAL1.getTimeInMillis())/1000.000; //System.out.println("Execution time : "+Execution_Time+" seconds"); pw.flush(); pw.close(); } static class InputReader //NoSuchElementException -> EOF { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class MyFileReader //File input template { StringTokenizer st; BufferedReader br; MyFileReader() throws IOException { br = new BufferedReader(new FileReader("C://Users/Aman deep/Desktop/input.txt")); } String nextLine() throws IOException { return br.readLine(); } String next() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(nextLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } static class MyFileReader1 //File input template { StringTokenizer st; BufferedReader br; MyFileReader1() throws IOException { br = new BufferedReader(new FileReader("C://Users/Aman deep/Desktop/output.txt")); } String nextLine() throws IOException { return br.readLine(); } String next() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(nextLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Scanner; import java.util.*; public class Main { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(), R = sc.nextInt(); double answer[] = new double[N]; int[] x = new int[N]; for (int i = 0; i < N; i++) x[i] = sc.nextInt(); for (int i = 0; i < N; i++) { answer[i] = R; for (int j = 0; j < i; j++) { int dist = Math.abs(x[i] - x[j]); if(dist <= 2 * R) { double t = answer[j] + Math.sqrt(4 * R * R - dist * dist); answer[i] = Math.max(answer[i], t); } } } for(int i = 0; i < N; ++i) out.print(answer[i] + " "); out.println(); out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * Created by mostafa on 12/29/17. */ public class C { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(), r = sc.nextInt(); int[] x = new int[n]; for(int i = 0; i < n; i++) x[i] = sc.nextInt(); double[] ans = new double[n]; for(int i = 0; i < n; i++) { ans[i] = r; for(int j = 0; j < i; j++) { int d = Math.abs(x[i] - x[j]); if(d > 2 * r) continue; int h = 2 * r; double yd = Math.sqrt(h * h - d * d); ans[i] = Math.max(ans[i], ans[j] + yd); } out.print(ans[i]); if(i == n - 1) out.println(); else out.print(" "); } out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; import java.math.*; public class A{ void solve(){ int n=ni(); long r=ni(); int x[]=new int[n+1]; for(int i=1;i<=n;i++) x[i]=ni(); double ans[]=new double[n+1]; ans[1]=r; for(int i=2;i<=n;i++){ double mx=0; for(int j=1;j<i;j++) { double xx = Math.abs(x[i] - x[j]); if (xx > 2*r) { mx = Math.max(mx,r); } else { xx *= xx; mx=Math.max(mx,ans[j] + Math.sqrt(4 * r * r - xx)); // if(i==5) pw.println(j); } //if(i==4) pw.println(mx); } ans[i]=mx; } for(int i=1;i<=n;i++) pw.print(ans[i]+" "); } long M=(long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.sqrt; import static java.lang.System.exit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Locale; import java.util.StringTokenizer; public class C { static int sqr(int x) { return x * x; } static void solve() throws Exception { int n = scanInt(); int r = scanInt(); int x[] = new int[n]; double y[] = new double[n]; for (int i = 0; i < n; i++) { int cx = x[i] = scanInt(); double cy = r; for (int j = 0; j < i; j++) { if (abs(cx - x[j]) <= 2 * r) { cy = max(cy, y[j] + sqrt(sqr(2 * r) - sqr(cx - x[j]))); } } y[i] = cy; if (i > 0) { out.print(' '); } out.printf(Locale.US, "%.9f", cy); } } static int scanInt() throws IOException { return parseInt(scanString()); } static long scanLong() throws IOException { return parseLong(scanString()); } static String scanString() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.Scanner; public class TaskC { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), r = sc.nextInt(); int[] xcords = new int[n]; double[] ycords = new double[n]; double y = r, x = 0, px = 0, ty = 0; for(int i = 0; i < n; i++) { xcords[i] = sc.nextInt(); x = xcords[i]; y = r; for(int j = 0; j < i; j++) { px = xcords[j]; if(Math.abs(px - x) > r*2) continue; ty = Math.sqrt(4*r*r - (x-px)*(x-px)) + ycords[j]; y = Math.max(y, ty); } ycords[i] = y; } for(int i = 0; i < n; i++) { System.out.print(ycords[i] + " "); } } }
quadratic
908_C. New Year and Curling
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.HashMap; import java.util.HashSet; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { FastScanner in= new FastScanner(System.in); PrintWriter out= new PrintWriter(System.out); int n= in.nextInt(); int r= in.nextInt(); int [] x= new int[n]; for (int i = 0; i < x.length; i++) { x[i]= in.nextInt(); } double [] res= new double[n]; res[0]= r; for (int i = 1; i < x.length; i++) { boolean found = false; for (int j = 0; j < i; j++) { double dis= Math.abs(x[i]-x[j]); double rr= 4.0*r*r-1.0*dis*dis; if(rr>=0) { double del= Math.sqrt(rr); res[i]= Math.max(res[i], res[j]+del); found= true; } } if(!found) { res[i]= r; } } for (int i = 0; i < res.length; i++) { out.print(res[i]+" "); } out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public String next() throws IOException { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); return next(); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class C908 { public static class mPoint implements Comparable<mPoint> { public double a, b; public mPoint(int a, double b) { this.a = a; this.b = b; } public int compareTo(mPoint p) { return b < p.b ? 1 : (b > p.b) ? -1 : 0; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(), r = in.nextInt(); int[] ar = new int[n]; ArrayList<mPoint> disks = new ArrayList<>(); double[] ans = new double[n]; for (int i = 0; i < n; i++) { ar[i] = in.nextInt(); double max = -1; for (int j = 0; j < disks.size(); j++) { if (inRange(ar[i], disks.get(j).a, r)) { double h = 4*r*r - (ar[i]-disks.get(j).a) * (ar[i]-disks.get(j).a); max = Math.max(max, Math.sqrt(h) + disks.get(j).b); } } mPoint p = null; if (max == -1) { p = new mPoint(ar[i], r); } else { p = new mPoint(ar[i], max); } disks.add(p); ans[i] = p.b; } for (int i = 0; i < ans.length - 1; i++) { System.out.print(ans[i] + " "); } System.out.println(ans[ans.length - 1]); } public static boolean inRange(int a, double b, int r) { if (Math.abs(b - a) <= 2*r) return true; return false; } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class C { public static Scanner sc = new Scanner(System.in); public static StringTokenizer st; public static PrintWriter pw = new PrintWriter(System.out); final static boolean debugmode = true; public static int k = 7; // for 10^9 + k mods. public static long STMOD = 1000000000 + k; // 10^9 + k public static void main(String[] args) { int disks = getInt(); int radii = getInt(); if(disks == 1){ System.out.println(radii); } else{ double[][] diskcenters = new double[disks][2]; for(int i = 0;i<disks;i++){ diskcenters[i][0] = getInt(); } diskcenters[0][1] = radii; for(int i = 1;i<disks;i++){ double cmax = 0; for(int prev = 0;prev < i;prev++){ cmax = Math.max(cmax, calcintersection(diskcenters[prev][0],diskcenters[prev][1],radii,diskcenters[i][0],radii)); } diskcenters[i][1] = cmax; } for(int i = 0;i<diskcenters.length;i++){ System.out.print(Double.toString(diskcenters[i][1]) + " "); } System.out.print("\n"); } } public static double calcintersection(double x1,double y1, double r1,double x2, double r2){ // x1,y1 must be stationary. if(!intersects(x1-r1,x1+r1,x2-r1,x2+r2)){ return r2; } else if(x1 == x2){ return y1 + r1 + r2; } double lo = y1; double hi = y1 + 2 * r2; while(Math.abs(lo-hi) > 0.0000001){ double mid = (lo+hi)/2.0; int u = colide(x1,y1,r1,x2,mid,r2); if(u == 1){ lo = mid; } else if(u == 0) { hi = mid; } else{ return mid; } } return (lo+hi)/2.0; } public static boolean intersects(double l1, double r1,double l2, double r2 ){ if(l2 <= l1 && r2 >= l1){ return true; } if(l2 <= r1 && r2 >= r1){ return true; } if(l1 <= l2 && r2 <= r1){ return true; } else if(l2 <= l1 && r1 <= r2){ return true; } return false; } public static int colide(double x1,double y1,double r1,double x2,double y2,double r2){ double dist = Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y2-y1, 2)); if (dist > r1 + r2){ return 0; } else if(dist == r1+r2){ return 2; } else{ return 1; } } public static void debug(String toPrint){ if(!debugmode) {return;} pw.println("[DEBUG]: "+toPrint); } public static void submit(int[] k){ pw.println(Arrays.toString(k)); pw.close(); } public static void submit(int p){ pw.println(Integer.toString(p)); pw.close(); } public static void submit(String k){ pw.println(k); pw.close(); } public static void submit(double u){ pw.println(Double.toString(u)); pw.close(); } public static void submit(long lng){ pw.println(Long.toString(lng)); pw.close(); } public static int getInt(){ if (st != null && st.hasMoreTokens()){ return Integer.parseInt(st.nextToken()); } st = new StringTokenizer(sc.nextLine()); return Integer.parseInt(st.nextToken()); } public static long getLong(){ if (st != null && st.hasMoreTokens()){ return Long.parseLong(st.nextToken()); } st = new StringTokenizer(sc.nextLine()); return Long.parseLong(st.nextToken()); } public static double getDouble(){ if (st != null && st.hasMoreTokens()){ return Double.parseDouble(st.nextToken()); } st = new StringTokenizer(sc.nextLine()); return Double.parseDouble(st.nextToken()); } public static String getString(){ if(st != null && st.hasMoreTokens()){ return st.nextToken(); } st = new StringTokenizer(sc.nextLine()); return st.nextToken(); } public static String getLine(){ return sc.nextLine(); } public static int[][] readMatrix(int lines,int cols){ int[][] matrr = new int[lines][cols]; for (int i = 0;i < lines;i++){ for(int j = 0;j < cols;j++){ matrr[i][j] = getInt(); } } return matrr; } public static int[] readArray(int lines){ int[] ar = new int[lines]; for (int i = 0;i<lines;i++) ar[i] =getInt(); return ar; } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; public class C { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n, r; n = scan.nextInt(); r = scan.nextInt(); int[] locs = new int[n]; for (int i = 0; i < n; i++) { locs[i] = scan.nextInt(); } double[] yPos = new double[n]; Arrays.fill(yPos, 10e100); yPos[0] = r; for (int i = 1; i < n; i++) { double pos = r; for (int j = 0; j < i; j++) { int xDist = Math.abs(locs[i] - locs[j]); if (xDist <= 2 * r) { double y = (2.0 * r) * (2.0 * r) - (xDist * xDist); if (Math.abs(y - 0.0) < 0.0000000001) { y = 0; } else { y = Math.sqrt(y); } y += yPos[j]; pos = Math.max(pos, y); } else { continue; } } yPos[i] = pos; } String[] ans = new String[n]; for (int i = 0; i < n; i++) { ans[i] = "" + yPos[i]; } System.out.println(String.join(" ", ans)); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { static int n,r,x[]; static double ans[]; public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); n = sc.nextInt(); r = sc.nextInt(); x = new int[n]; ans = new double[n]; for (int i=0;i<n;i++) x[i] = sc.nextInt(); for (int i=0;i<n;i++) { ans[i] = r; for (int j=0;j<i;j++) { if (Math.abs(x[i]-x[j])>2*r) continue; int deltaxsq = (x[i]-x[j])*(x[i]-x[j]); int deltaysq = 4 * r * r - deltaxsq; double deltay = Math.sqrt(deltaysq); ans[i] = Math.max(ans[i], ans[j]+deltay); } pw.print(ans[i]+" "); } pw.flush(); pw.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; public class Solution { static MyScanner sc; private static PrintWriter out; static long M2 = 1_000_000_000L + 7; public static void main(String[] s) throws Exception { StringBuilder stringBuilder = new StringBuilder(); if (stringBuilder.length() == 0) { sc = new MyScanner(System.in); } else { sc = new MyScanner(new BufferedReader(new StringReader(stringBuilder.toString()))); } out = new PrintWriter(new OutputStreamWriter(System.out)); initData(); solve(); out.flush(); } private static void initData() { } private static void solve() throws IOException { int n = sc.nextInt(); int q = sc.nextInt(); int[] vv = sc.na(n); double[] ans = new double[n]; for (int i = 0; i < n; i++) { ans[i] = q; for (int s = 0; s < i; s++) { if (Math.abs(vv[i] - vv[s]) > q * 2) continue; double diff = 4 * q * q - Math.abs(vv[i] - vv[s]) * Math.abs(vv[i] - vv[s]); diff = Math.sqrt(diff); ans[i] = Math.max(ans[i], diff + ans[s]); } out.print(ans[i] + " "); } } private static void solveT() throws IOException { int t = sc.nextInt(); while (t-- > 0) { solve(); } } private static long gcd(long l, long l1) { if (l > l1) return gcd(l1, l); if (l == 0) return l1; return gcd(l1 % l, l); } private static long pow(long a, long b, long m) { if (b == 0) return 1; if (b == 1) return a; long pp = pow(a, b / 2, m); pp *= pp; pp %= m; return (pp * (b % 2 == 0 ? 1 : a)) % m; } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner(BufferedReader br) { this.br = br; } public MyScanner(InputStream in) { this(new BufferedReader(new InputStreamReader(in))); } void findToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } } String next() { findToken(); return st.nextToken(); } Integer[] nab(int n) { Integer[] k = new Integer[n]; for (int i = 0; i < n; i++) { k[i] = sc.fi(); } return k; } int[] na(int n) { int[] k = new int[n]; for (int i = 0; i < n; i++) { k[i] = sc.fi(); } return k; } long[] nl(int n) { long[] k = new long[n]; for (int i = 0; i < n; i++) { k[i] = sc.nextLong(); } return k; } int nextInt() { return Integer.parseInt(next()); } int fi() { String t = next(); int cur = 0; boolean n = t.charAt(0) == '-'; for (int a = n ? 1 : 0; a < t.length(); a++) { cur = cur * 10 + t.charAt(a) - '0'; } return n ? -cur : cur; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class GB17C { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); String[] dir = sc.readLine().split(" "); int n = Integer.parseInt(dir[0]); int r = Integer.parseInt(dir[1]); String[] t = sc.readLine().split(" "); int[] list = new int[n]; for(int x=0; x<n; x++){ list[x] = Integer.parseInt(t[x]); } double[] yCoords = new double[n]; for(int x=0; x<n; x++){ double stop = (double)r; int dist = 2*r; int xCoordNew = list[x]; for(int y=0; y<x; y++){ int xCoordOld = list[y]; if(Math.abs(xCoordNew - xCoordOld) == dist){ stop = Math.max(stop, yCoords[y]); } else if(Math.abs(xCoordNew - xCoordOld) < dist){ double extra = Math.pow((double)(dist*dist) - (double)((xCoordNew - xCoordOld)*(xCoordNew - xCoordOld)), 0.5); stop = Math.max(stop, yCoords[y] + extra); } } yCoords[x] = stop; System.out.print(stop+" "); } } } /* BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(sc.readLine()); String[] t = sc.readLine().split(" "); int[] list = new int[n]; for(int x=0; x<n; x++){ list[x] = Integer.parseInt(t[x]); } String[] dir = sc.readLine().split(" "); int a = Integer.parseInt(dir[0]); int b = Integer.parseInt(dir[1]); int c = Integer.parseInt(dir[2]); int d = Integer.parseInt(dir[3]); int e = Integer.parseInt(dir[4]); int n = Integer.parseInt(sc.readLine()); */
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.*; public class C { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); long r = sc.nextInt(); double d = 2 * r; long[] xs = sc.readLongArray(n); P[] points = new P[n]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { if (i > 0) sb.append(' '); double y = r; for (int j = 0; j < i; j++) { long diff = Math.abs(xs[i] - points[j].x); if (diff <= 2 * r) { double dy = Math.sqrt(d * d - diff * diff); double testY = points[j].y + dy; y = Math.max(y, testY); } } sb.append(y); points[i] = new P(xs[i], y); } System.out.println(sb); } static class P { final long x; final double y; public P(long x, double y) { this.x = x; this.y = y; } } static void shuffle(int[] arr) { Random rng = new Random(); int length = arr.length; for (int idx = 0; idx < arr.length; idx++) { int toSwap = idx + rng.nextInt(length - idx); int tmp = arr[idx]; arr[idx] = arr[toSwap]; arr[toSwap] = tmp; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(); int r = in.readInt(); int[] x = in.readIntArray(n); double[] y = new double[n]; y[0] = r; for (int i = 1; i < n; i++) { double max = r; for (int j = 0; j < i; j++) { double pow = Math.pow(x[i] - x[j], 2); if (pow <= 4 * r * r) { double ty = y[j] + Math.sqrt(4 * r * r - pow); max = Math.max(max, ty); } } y[i] = max; } for (double i : y) out.print(i + " "); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] readIntArray(int size) { int[] ans = new int[size]; for (int i = 0; i < size; i++) ans[i] = readInt(); return ans; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
/* * code together * code better */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.HashMap; import java.util.Scanner; public class Main { static int x[]=new int[1005]; static double ans[]=new double[1005]; static int nn,r; public static void main(String[] args) throws IOException { StreamTokenizer in=new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); Scanner sc=new Scanner(System.in); int huiwoqingchun=0; nn=sc.nextInt(); r=sc.nextInt(); for(int i=1;i<=nn;i++) { x[i]=sc.nextInt(); } //HashMap<, V> ans[1]=r; int lajitimu=0; for(int i=2;i<=nn;i++) { ans[i]=r; for(int j=1;j<i;j++) { if(Math.abs(x[j]-x[i])>2*r) continue; ans[i]=Math.max(ans[i], ans[j]+Math.sqrt(4*r*r-(x[j]-x[i])*(x[j]-x[i]))); } } double buzhidaoganma=0; for(int c=1;c<=nn;c++) System.out.printf("%.12f ",ans[c]); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); C908 solver = new C908(); solver.solve(1, in, out); out.close(); } static class C908 { int N; int R; int[] x; double[] ans; public void solve(int testNumber, FastScanner s, PrintWriter out) { N = s.nextInt(); R = s.nextInt(); x = s.nextIntArray(N); ans = new double[N]; Arrays.fill(ans, R); for (int i = 0; i < N; i++) { // placing circle i for (int j = 0; j < i; j++) { // testing collision with placed circles if (Math.abs(x[i] - x[j]) <= 2 * R) { // they will collide // compute the increase in y that will be had double dy = Math.sqrt(Math.pow(2 * R, 2) - Math.pow(x[i] - x[j], 2)); ans[i] = Math.max(ans[i], ans[j] + dy); } } } for (double d : ans) out.print(d + " "); out.println(); } } 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; } public int nextInt() { return Integer.parseInt(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 int[] nextIntArray(int N) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = this.nextInt(); return ret; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; public class naloga1{ static BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) throws Exception{ StringTokenizer st=new StringTokenizer(in.readLine()); int n=Integer.parseInt(st.nextToken()); int r=Integer.parseInt(st.nextToken()); int[] x=new int[n]; st=new StringTokenizer(in.readLine()); for(int i=0;i < n;i++){ x[i]=Integer.parseInt(st.nextToken()); } sim a=new sim(n,r); for(int i:x) { a.add(i); } for(double d:a.cy) { out.print(d+" "); } out.println(); out.close(); } } class sim{ double[]cx; int[]ccx; double[]cy; int count; int n; int r; sim(int nn,int rr){ r=rr; n=nn; cx=new double[n]; ccx=new int[n]; cy=new double[n]; count=0; } void add(int x) { double lowest=r; for(int i=0;i<count;i++) { if(Math.abs(ccx[i]-x)<=2*r) { double dy=Math.sqrt(4*r*r-(ccx[i]-x)*(ccx[i]-x)); lowest=Math.max(lowest,cy[i]+dy); } } ccx[count]=x; cy[count]=lowest; cx[count++]=x; } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; public class ProblemA { public static void main(String[] args) throws Exception{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(bf.readLine()); StringTokenizer st1 = new StringTokenizer(bf.readLine()); int n = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); int[] xcoords = new int[n]; for(int i = 0;i<n;i++){ xcoords[i] = Integer.parseInt(st1.nextToken()); } double[] ycoords = new double[n]; for(int i = 0;i<n;i++){ ArrayList<Integer> nodes = new ArrayList<Integer>(); for(int j = 0;j<i;j++){ if (Math.abs(xcoords[j] - xcoords[i]+0.0) <= 2*r) nodes.add(j); } if (nodes.isEmpty()){ ycoords[i] = r; continue; } else{ double min = -1; for(int k = 0;k<nodes.size();k++){ double tmp = ycoords[nodes.get(k)] + Math.sqrt(4*r*r - (xcoords[i] - xcoords[nodes.get(k)])*(xcoords[i] - xcoords[nodes.get(k)])); if (tmp > min){ min = tmp; } } ycoords[i] = min; } } for(int i = 0;i<ycoords.length;i++){ System.out.print(ycoords[i] + " "); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class C { public static void main(String[] args) { MyScanner in = new MyScanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int r = in.nextInt(); double[] y = new double[n]; int[] x = new int[n]; for(int i=0;i<n;++i){ x[i] = in.nextInt(); double bestY = r; for(int j=0;j<i;++j){ if(Math.abs(x[i]-x[j]) <= 2*r){ double ny = y[j] + Math.sqrt(4*r*r - (x[i]-x[j])*(x[i]-x[j])); if(ny > bestY){ bestY = ny; } } } y[i] = bestY; } for(int i=0;i<n;++i){ out.println(y[i]); } out.close(); } // -----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // -------------------------------------------------------- }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; public class Solution2 { private void solve() throws IOException { int n = in.nextInt(); double r = in.nextDouble(); List<Double> xes = new ArrayList<>(n); List<Double> yes = new ArrayList<>(n); for (int i = 0; i < n; i++) { xes.add(in.nextDouble()); } for (int i = 0; i < n; i++) { double max = r; for (int j = 0; j < i; j++) { double x = xes.get(j); double y = yes.get(j); if (xes.get(i) <= x + 2 * r && xes.get(i) >= x - 2 * r) { max = Math.max(max, y + Math.sqrt(4 * r * r - Math.abs(x - xes.get(i))* Math.abs(x - xes.get(i)))); } } yes.add(max); } for (double y : yes) { System.out.print(y + " "); } System.out.println(); System.out.flush(); } private static String filename = ""; private PrintWriter out; private MyScanner in; private void run() throws IOException { in = new MyScanner(); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } private class MyScanner { private BufferedReader br; private StringTokenizer st; MyScanner() throws IOException { this.br = new BufferedReader(new InputStreamReader(System.in)); } public MyScanner(String fileTitle) throws IOException { this.br = new BufferedReader(new FileReader(fileTitle)); } public String nextLine() throws IOException { String s = br.readLine(); return s == null ? "-1" : s; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return "-1"; } st = new StringTokenizer(s); } return st.nextToken(); } public Integer nextInt() throws IOException { return Integer.parseInt(this.next()); } public Long nextLong() throws IOException { return Long.parseLong(this.next()); } public Double nextDouble() throws IOException { return Double.parseDouble(this.next()); } void close() throws IOException { this.br.close(); } } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Solution2().run(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int r = sc.nextInt(); double ans[] = new double[n]; int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { ans[i] = r; for (int j = 0; j < i; j++) { int d = Math.abs(x[i] - x[j]); if(d <= 2 * r) { ans[i] = Math.max(ans[i], ans[j] + Math.sqrt(4 * r * r - d * d)); } } out.print(ans[i] + " "); } out.println(); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } 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(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; public class C { public static void main(String[] args) { FastScanner in = new FastScanner(); int n = in.nextInt(); double r = in.nextInt(); double x[] = new double[n]; for(int i = 0; i < n; i++) x[i] = in.nextDouble(); double y[] = new double[n]; y[0] = r; for(int i = 1; i < n; i++){ double miny = r; for(int j = 0; j < i; j++){ double dx = Math.abs(x[i]-x[j]); if(dx > r*2) continue; double yy = Math.sqrt(4*r*r-dx*dx); miny = Math.max(miny, yy+y[j]); } y[i] = miny; } for(int i = 0; i < n; i++){ System.out.print(y[i]+" "); } } static class FastScanner{ BufferedReader br; StringTokenizer st; public FastScanner(String s) { try{ br = new BufferedReader(new FileReader(s)); } catch(FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(){ br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while(st == null ||!st.hasMoreElements()){ try { st = new StringTokenizer(br.readLine());} catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } String next() { return nextToken(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; public class test { public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); StringTokenizer st = new StringTokenizer(s.nextLine()); int n = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); st = new StringTokenizer(s.nextLine()); int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = Integer.parseInt(st.nextToken()); } ArrayList<State> list = new ArrayList<State>(); for (int i = 0; i < n; i++) { double currY = r; for (int j = 0; j < list.size(); j++) { double xDiff = Math.abs(list.get(j).getX() - array[i]); if (xDiff <= 2 * r) { if (currY < list.get(j).getY() + Math.sqrt(4 * r * r - xDiff * xDiff)) { currY = list.get(j).getY() + Math.sqrt(4 * r * r - xDiff * xDiff); } } } list.add(new State(array[i], currY)); System.out.print(currY + " "); } s.close(); } static class State { double x; double y; public State(double a, double b) { x = a; y = b; } public double getX() { return x; } public double getY() { return y; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int r = in.nextInt(); int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); } double res = 0; double[] y = new double[n]; for (int i = 0; i < n; i++) { double curY = r; for (int j = 0; j < i; j++) { int d = Math.abs(x[i] - x[j]); if (d <= 2 * r) { int a2 = 4 * r * r - d * d; curY = Math.max(curY, y[j] + Math.sqrt(a2)); } } y[i] = curY; out.printf("%.14f", y[i]); if (i < n - 1) { out.print(" "); } else { out.println(); } } } } static class InputReader { final InputStream is; final byte[] buf = new byte[1024]; int pos; int size; public InputReader(InputStream is) { this.is = is; } public int nextInt() { int c = read(); while (isWhitespace(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = read(); } while (!isWhitespace(c)); return res * sign; } int read() { if (size == -1) throw new InputMismatchException(); if (pos >= size) { pos = 0; try { size = is.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (size <= 0) return -1; } return buf[pos++] & 255; } static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C { public static void main(String[] args){ FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(), r = scan.nextInt(); int[] x = scan.nextIntArray(n); double[] y = new double[n]; for(int i = 0; i < n; i++) { double best = 0; for(int j = 0; j < i; j++) { if(Math.abs(dist(x[i], y[j], x[j], y[j])-2*r) <= 1e-7) { best = Math.max(best, y[j]); continue; } double lo = y[j]-r-r, hi = y[j]+r+r; for(int bs = 0; bs < 200; bs++) { double mid = (lo+hi)/2.0; if(dist(x[i], mid, x[j], y[j])-2*r <= 1e-7) lo = mid; else hi = mid; } if(dist(x[i], lo, x[j], y[j])-2*r <= 1e-7) best = Math.max(best, lo); } if(best == 0) y[i] = r; else y[i] = best; } for(int i = 0; i < n; i++) out.printf("%.6f ", y[i]); out.close(); } static double dist(double x, double y, double xx, double yy) {return Math.sqrt((x-xx)*(x-xx)+(y-yy)*(y-yy));} static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n){ long[] a = new long[n]; for(int i = 0; i < n; i++) a[i] = nextLong(); return a; } public double[] nextDoubleArray(int n){ double[] a = new double[n]; for(int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char[][] nextGrid(int n, int m){ char[][] grid = new char[n][m]; for(int i = 0; i < n; i++) grid[i] = next().toCharArray(); return grid; } } }
quadratic
908_C. New Year and Curling
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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, MyInput in, PrintWriter out) { int n = in.nextInt(); int r = in.nextInt(); int[] x = in.nextIntArray(n); double[] py = new double[n]; for (int i = 0; i < n; i++) { double y = r; for (int j = 0; j < i; j++) { int dx = Math.abs(x[i] - x[j]); if (dx > 2 * r) continue; y = Math.max(y, Math.sqrt(4 * r * r - dx * dx) + py[j]); } py[i] = y; } for (int i = 0; i < n; i++) { out.printf("%.10f%s", py[i], i == n - 1 ? "\n" : " "); } } } 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; } public int[] nextIntArray(final int n) { final int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } static class EndOfFileRuntimeException extends RuntimeException { } } }
quadratic
908_C. New Year and Curling
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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int r = in.readInt(); int[] x = IOUtils.readIntArray(in, n); double[] y = new double[n]; for (int idx = 0; idx < x.length; idx++) { double yRes = r; for (int prev = 0; prev < idx; prev++) { int xDelta = Math.abs(x[idx] - x[prev]); if (xDelta <= 2 * r) { // then we intersect with prev double yDelta = calcDelta(xDelta, r); yRes = Math.max(yRes, y[prev] + yDelta); } } y[idx] = yRes; } out.printLine(y); } private double calcDelta(int xDelta, int r) { return Math.sqrt(4 * r * r - xDelta * xDelta); } } 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(double[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void printLine(double[] array) { print(array); writer.println(); } public void close() { writer.close(); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.readInt(); } return array; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.Scanner; /** * * @author msagimbekov */ public class Codeforces908C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int r = sc.nextInt(); int[] x = new int[n]; double[] res = new double[n]; for (int i = 0; i < n; i++) { x[i] = sc.nextInt(); res[i] = (double)r; for (int j = i - 1; j >= 0; j--) { int diff = x[j] - x[i]; if (Math.abs(x[j] - x[i]) <= 2 * r) { res[i] = Math.max(res[i], res[j] + Math.sqrt(4 * r * r - diff * diff)); } } } for (int i = 0; i < n; i++) { System.out.print(res[i] + " "); } System.out.println(""); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.StringTokenizer; public class NewYearCurling908C { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(); int n = in.nextInt(); double r = (double) in.nextInt(); double[] answers = new double[n]; double[] xCoords = new double[n]; for (int i = 0; i < n; i++) xCoords[i] = (double) in.nextInt(); answers[0] = r; for (int i = 1; i < n; i++) { double bound = r; for (int j = 0; j < i; j++) { double xDif = xCoords[i] - xCoords[j]; double y = answers[j]; double yNew = y + Math.sqrt(4 * r * r - xDif * xDif); if (yNew > bound) bound = yNew; } answers[i] = bound; } for (int i = 0; i < n; i++) System.out.print(answers[i] + " "); System.out.println(); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; public class ProblemD { static int mod = (int) (1e9+7); static InputReader in; static PrintWriter out; static void solve() { in = new InputReader(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); int r = in.nextInt(); double[] x = new double[n]; double[] y = new double[n]; for(int i = 0; i < n; i++){ int xx = in.nextInt(); x[i] = xx; y[i] = r; for(int j = 0; j < i; j++){ double delx = Math.abs(x[i] - x[j]); //debug(delx); if(delx <= 2 * r){ double tmp = 4 * r * r - delx * delx; tmp = Math.sqrt(tmp); tmp = y[j] + tmp; y[i] = Math.max(y[i], tmp); } } out.print(y[i] + " "); } out.close(); } public static void main(String[] args) { new Thread(null ,new Runnable(){ public void run(){ try{ solve(); } catch(Exception e){ e.printStackTrace(); } } },"1",1<<26).start(); } static class Pair implements Comparable<Pair> { long x,y; Pair (long x,long y) { this.x = x; this.y = y; } public int compareTo(Pair o) { return Long.compare(this.x,o.x); //return 0; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y==y; } return false; } @Override public String toString() { return x + " "+ y ; } /*public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); }*/ } static long add(long a,long b){ long x=(a+b); while(x>=mod) x-=mod; return x; } static long sub(long a,long b){ long x=(a-b); while(x<0) x+=mod; return x; } static long mul(long a,long b){ long x=(a*b); while(x>=mod) x-=mod; return x; } static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } static long gcd(long x,long y) { if(y==0) return x; else return gcd(y,x%y); } static int gcd(int x,int y) { if(y==0) return x; else return gcd(y,x%y); } static long pow(long n,long p,long m) { long result = 1; if(p==0){ return 1; } while(p!=0) { if(p%2==1) result *= n; if(result >= m) result %= m; p >>=1; n*=n; if(n >= m) n%=m; } return result; } static long pow(long n,long p) { long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
/* * * @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya) * Dhirubhai Ambani Institute of Information And Communication Technology * */ import java.util.*; import java.io.*; import java.lang.*; public class Code3 { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = in.nextInt(); double r = (double)in.nextInt(); double [] a = new double[n]; for(int i=0;i<n;i++) a[i] = (double)in.nextInt(); double[] ans = new double[n]; ans[0] = r; for(int i=1;i<n;i++) { double max = Double.MIN_VALUE; for(int j=0;j<i;j++) { if(Math.abs(a[i]-a[j])<=2*r) { //System.out.println(j); double cur = 4*r*r; cur -= ((a[i]-a[j])*(a[i]-a[j])); cur = Math.sqrt(cur); cur += ans[j]; //System.out.println(r); max = Math.max(max, cur); } } if(max == Double.MIN_VALUE) ans[i] = r; else ans[i] = max; } for(int i=0;i<n;i++) pw.print(ans[i] + " "); pw.flush(); pw.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int r = sc.nextInt(); int d = 2 * r; int[] xCoordinates = new int[n]; double[] yCoordinates = new double[n]; for (int i = 0; i < n; i++) yCoordinates[i] = r; for (int i = 0; i < n; i++) xCoordinates[i] = sc.nextInt(); double y = 0; for (int i = 0; i < n; i++) { y = r; for (int j = 0; j < i; j++) { if (Math.abs(xCoordinates[i] - xCoordinates[j]) <= 2 * r) { int dx = Math.abs(xCoordinates[i] - xCoordinates[j]); double dy = Math.sqrt(d * d - dx * dx); if (dy + yCoordinates[j] > y) y = dy + yCoordinates[j]; } } yCoordinates[i]=y; } for (int i = 0; i < n; i++) System.out.print(yCoordinates[i] + " "); sc.close(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.util.*; import java.io.*; public class C { static long time = System.currentTimeMillis(); public static void main(String[] args) throws IOException { //FastReader infile = new FastReader("test.txt"); FastReader infile = new FastReader(System.in); int N = infile.nextInt(); int R = infile.nextInt(); double[] xPos = new double[N]; for(int x = 0; x < N; x++) xPos[x] = infile.nextDouble(); double[] yPos = new double[N]; Arrays.fill(yPos, R); for(int x = 1; x < N; x++) { for(int y = 0; y < x; y++) if(Math.abs(xPos[x]-xPos[y])<=2*R) { yPos[x] = Math.max(yPos[x], yPos[y]+Math.sqrt((2*R)*(2*R)-Math.abs(xPos[x]-xPos[y])*Math.abs(xPos[x]-xPos[y]))); } } System.out.print(yPos[0]); for(int x = 1; x < N; x++) System.out.print(" "+yPos[x]); //System.out.println(System.currentTimeMillis()-time); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader(String file) throws IOException { br = new BufferedReader(new FileReader(file)); } public FastReader(InputStream i) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); } boolean hasNext() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { return false; } } return true; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int r = in.scanInt(), temp; double max1; double high[] = new double[1002]; for (int i = 0; i < n; i++) { temp = in.scanInt(); max1 = high[temp] + ((high[temp] == 0) ? r : +(2 * r)); for (int j = temp - 1; j > temp - (2 * r) && j > 0; j--) { if (high[j] == 0) continue; max1 = Math.max(max1, high[j] + Math.sqrt((4 * r * r) - ((temp - j) * (temp - j)))); } for (int j = temp + 1; j <= 1000 && j < temp + (2 * r); j++) { if (high[j] == 0) continue; max1 = Math.max(max1, high[j] + Math.sqrt((4d * r * r) - (((j - temp) * (j - temp))))); } if (temp - (2 * r) > 0) max1 = Math.max(high[temp - (2 * r)], max1); if (temp + (2 * r) <= 1000) max1 = Math.max(high[temp + (2 * r)], max1); high[temp] = max1; out.print(max1 + " "); } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.* ; import java.util.* ; import java.text.* ; import java.math.* ; import static java.lang.Math.min ; import static java.lang.Math.max ; import static java.lang.Math.sqrt ; public class Codeshefcode{ public static void main(String[] args) throws IOException{ Solver Machine = new Solver() ; Machine.Solve() ; Machine.Finish() ; // new Thread(null,new Runnable(){ // public void run(){ // Solver Machine = new Solver() ; // try{ // Machine.Solve() ; // Machine.Finish() ; // }catch(Exception e){ // e.printStackTrace() ; // System.out.flush() ; // System.exit(-1) ; // }catch(Error e){ // e.printStackTrace() ; // System.out.flush() ; // System.exit(-1) ; // } // } // },"Solver",1l<<27).start() ; } } class Mod{ static long mod=1000000007 ; static long d(long a,long b){ return (a*MI(b))%mod ; } static long m(long a,long b){ return (a*b)%mod ; } static private long MI(long a){ return pow(a,mod-2) ; } static long pow(long a,long b){ if(b<0) return pow(MI(a),-b) ; long val=a ; long ans=1 ; while(b!=0){ if((b&1)==1) ans = (ans*val)%mod ; val = (val*val)%mod ; b/=2 ; } return ans ; } } class pair implements Comparable<pair>{ int x ; int y ; pair(int x,int y){ this.x=x ; this.y=y ;} public int compareTo(pair p){ return (this.x<p.x ? -1 : (this.x>p.x ? 1 : (this.y<p.y ? -1 : (this.y>p.y ? 1 : 0)))) ; } } class Solver{ Reader ip = new Reader(System.in) ; PrintWriter op = new PrintWriter(System.out) ; public void Solve() throws IOException{ int n = ip.i() ; int r = ip.i() ; double x[] = new double[n] ; double y[] = new double[n] ; for(int i=0 ; i<n ; i++) x[i] = ip.i() ; for(int i=0 ; i<n ; i++){ double my = 0 ; for(int j=0 ; j<i ; j++) my = max(my,func(x[j],y[j],r,x[i])) ; y[i] = my ; } for(int i=0 ; i<n ; i++) p((y[i]+r)+" ") ; pln("") ; } double abd(double x,double y){ return x>y ? x-y : y-x ; } double func(double x1,double y1,double r,double x2){ if(abd(x1,x2)>(2*r)) return 0 ; if(abd(x1,x2)==(2*r)) return y1 ; double dx = x1-x2 ; double dx2 = dx*dx ; double val = sqrt(4*r*r-dx2) ; return y1+val ; } void Finish(){ op.flush(); op.close(); } void p(Object o){ op.print(o) ; } void pln(Object o){ op.println(o) ; } } class mylist extends ArrayList<Integer>{} class myset extends TreeSet<Integer>{} class mystack extends Stack<Integer>{} class mymap extends TreeMap<Long,Integer>{} class Reader{ BufferedReader reader; StringTokenizer tokenizer; Reader(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer("") ; } String s() throws IOException { while (!tokenizer.hasMoreTokens()){ tokenizer = new StringTokenizer( reader.readLine()) ; } return tokenizer.nextToken(); } int i() throws IOException { return Integer.parseInt(s()) ; } long l() throws IOException{ return Long.parseLong(s()) ; } double d() throws IOException { return Double.parseDouble(s()) ; } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.io.*; import java.util.*; import java.math.BigInteger; import java.util.Map.Entry; import static java.lang.Math.*; public class C extends PrintWriter { void run() { int n = nextInt(); int r = nextInt(); int[] x = nextArray(n); double[] y = new double[n]; Arrays.fill(y, r); for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { int dx = abs(x[i] - x[j]); int sdy = 4 * r * r - dx * dx; if (sdy >= 0) { double dy = sqrt(sdy); y[i] = max(y[i], y[j] + dy); } } } for (double v : y) { printf(Locale.ENGLISH, "%.10f ", v); } } boolean skip() { while (hasNext()) { next(); } return true; } int[][] nextMatrix(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) matrix[i][j] = nextInt(); return matrix; } String next() { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String line = nextLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } int[] nextArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return reader.readLine(); } catch (IOException err) { return null; } } public C(OutputStream outputStream) { super(outputStream); } static BufferedReader reader; static StringTokenizer tokenizer = new StringTokenizer(""); static Random rnd = new Random(); static boolean OJ; public static void main(String[] args) throws IOException { OJ = System.getProperty("ONLINE_JUDGE") != null; C solution = new C(System.out); if (OJ) { reader = new BufferedReader(new InputStreamReader(System.in)); solution.run(); } else { reader = new BufferedReader(new FileReader(new File(C.class.getName() + ".txt"))); long timeout = System.currentTimeMillis(); while (solution.hasNext()) { solution.run(); solution.println(); solution.println("----------------------------------"); } solution.println("time: " + (System.currentTimeMillis() - timeout)); } solution.close(); reader.close(); } }
quadratic
908_C. New Year and Curling
CODEFORCES
import java.lang.*; import java.io.*; import java.util.*; public class Main { public void solve() throws IOException { int n = nextInt(), r = nextInt(); int x[] = new int[n]; for (int i = 0; i < n; i++) { x[i] = nextInt(); } double res[] = new double[n]; res[0] = r; for (int i = 1; i < n; i++) { double max = r; for (int j = 0; j < i; j++) { int d = Math.abs(x[i] - x[j]); if(d <= 2 * r){ double yy = Math.sqrt(4 * r * r - d * d); max = Math.max(max, yy + res[j]); } } res[i] = max; } for (int i = 0; i < n; i++) { out.print(res[i] + " "); } } BufferedReader br; StringTokenizer sc; PrintWriter out; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Main().run(); } void run() throws IOException { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // br = new BufferedReader(new FileReader("pnumbers.in")); // out = new PrintWriter(new File("out.txt")); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } String nextToken() throws IOException { while (sc == null || !sc.hasMoreTokens()) { try { sc = new StringTokenizer(br.readLine()); } catch (Exception e) { return null; } } return sc.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
quadratic
908_C. New Year and Curling
CODEFORCES