src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.io.*;
import java.util.*;
public class A {
FastScanner in;
PrintWriter out;
void solve() {
long a = in.nextLong(), b = in.nextLong();
long ans = 0;
while (true) {
long div = a / b;
ans += div;
a -= div * b;
if (a == 0) {
break;
}
long tmp = a;
a = b;
b = tmp;
}
out.println(ans);
}
void run() {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
public static void main(String[] args) {
new A().run();
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.Point;
public class Main {
//static final long MOD = 1000000007L;
//static final long MOD2 = 1000000009L;
static final long MOD = 998244353L;
//static final long INF = 500000000000L;
static final int INF = 1000000005;
static final int NINF = -1000000005;
//static final long NINF = -1000000000000000000L;
static FastScanner sc;
static PrintWriter pw;
static final int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
public static void main(String[] args) {
sc = new FastScanner();
pw = new PrintWriter(System.out);
int Q = sc.ni();
for (int q = 0; q < Q; q++) {
int N = sc.ni();
String ans = "NO";
if (N%2==0 && isSquare(N/2))
ans = "YES";
if (N%4==0 && isSquare(N/4))
ans = "YES";
pw.println(ans);
}
pw.close();
}
public static boolean isSquare(int x) {
int s = (int)Math.round(Math.sqrt(x));
return s*s==x;
}
public static void sort(int[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
public static void sort(long[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
//Sort an array (immune to quicksort TLE)
public static void sort(int[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
return a[0]-b[0];
}
});
}
public static void sort(long[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else
return 0;
//Ascending order.
}
});
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[][] graph(int N, int[][] edges) {
int[][] graph = new int[N][];
int[] sz = new int[N];
for (int[] e: edges) {
sz[e[0]] += 1;
sz[e[1]] += 1;
}
for (int i = 0; i < N; i++) {
graph[i] = new int[sz[i]];
}
int[] cur = new int[N];
for (int[] e: edges) {
graph[e[0]][cur[e[0]]] = e[1];
graph[e[1]][cur[e[1]]] = e[0];
cur[e[0]] += 1;
cur[e[1]] += 1;
}
return graph;
}
int[] intArray(int N, int mod) {
int[] ret = new int[N];
for (int i = 0; i < N; i++)
ret[i] = ni()+mod;
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N, long mod) {
long[] ret = new long[N];
for (int i = 0; i < N; i++)
ret[i] = nl()+mod;
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class Houses implements Runnable {
private void solve() throws IOException {
int n = nextInt();
int t = nextInt();
int[] x = new int[n];
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
x[i] = nextInt() * 2;
a[i] = nextInt();
}
Set<Integer> res = new HashSet<Integer>();
for (int i = 0; i < n; ++i) {
if (valid(n, t, x, a, x[i] + a[i] + t))
res.add(x[i] + a[i] + t);
if (valid(n, t, x, a, x[i] - a[i] - t))
res.add(x[i] - a[i] - t);
}
writer.println(res.size());
}
private boolean valid(int n, int t, int[] x, int[] a, int pos) {
for (int i = 0; i < n; ++i) {
if (Math.abs(pos - x[i]) < a[i] + t)
return false;
}
return true;
}
public static void main(String[] args) {
new Houses().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.HashSet;
public class E17 {
static StreamTokenizer in;
static PrintWriter out;
static int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
static String nextString() throws IOException {
in.nextToken();
return in.sval;
}
public static void main(String[] args) throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
int n = nextInt(), k = nextInt();
int MAX = n, nprimes = 0;
int[] primes = new int[MAX];
boolean[] isPrime = new boolean[MAX+1];
Arrays.fill(isPrime, true);
isPrime[0] = false;
isPrime[1] = false;
for (int i = 2; i <= MAX; i++) if (isPrime[i]) {
primes[nprimes++] = i;
for (int j = i + i; j <= MAX; j += i) isPrime[j] = false;
}
primes[nprimes] = Integer.MAX_VALUE;
HashSet<Integer> h = new HashSet<Integer>();
for (int i = 1; i < nprimes; i++) {
int x = primes[i-1] + primes[i] + 1;
if (x > n) break;
if (isPrime[x]) h.add(x);
}
out.println(h.size() >= k ? "YES" : "NO");
out.flush();
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.System.out;
public class Main {
private FastScanner scanner = new FastScanner();
public static void main(String[] args) {
new Main().solve();
}
private List<Integer>[] gr = new ArrayList[1000_000+5];
private int dp[][] = new int[21][1000_000+5];
private boolean used[] = new boolean[1000_000+5];
void init(int v, int p) {
Stack<Integer> st = new Stack<>();
st.push(v);
st.push(p);
while (!st.isEmpty()) {
p = st.pop();
v = st.pop();
used[v] = true;
dp[0][v] = p;
for (int i = 1; i <= 20; i++) {
if (dp[i - 1][v] != -1) {
dp[i][v] = dp[i - 1][dp[i - 1][v]];
}
}
for (int next : gr[v]) {
if (!used[next]) {
st.push(next);
st.push(v);
}
}
}
}
private void solve() {
int n = scanner.nextInt(), k = scanner.nextInt();
boolean[] ans = new boolean[1000_000 + 5];
for (int i = 0; i < n; i++) {
gr[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i ++) {
int u = scanner.nextInt() - 1, v = scanner.nextInt() - 1;
gr[u].add(v);
gr[v].add(u);
}
k = n - k - 1;
ans[n - 1] = true;
init(n - 1 , n - 1);
int t, d, next;
for (int i = n - 2; i >= 0; i--) {
t = i;
d = 1;
if (ans[i]) {
continue;
}
for (int j = 20; j >= 0; j--){
next = dp[j][t];
if (next != -1 && !ans[next]) {
t = next;
d += 1 << j;
}
}
if (d <= k) {
k -=d;
t = i;
while (!ans[t]) {
ans[t] = true;
t = dp[0][t];
}
}
if (k == 0) {
break;
}
}
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < n; i++) {
if (!ans[i]) {
sb.append(i + 1).append(" ");
}
}
System.out.println(sb.toString());
}
class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
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 int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
nlogn
|
980_E. The Number Games
|
CODEFORCES
|
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
/**
*
* @author epiZend
*/
public class Cottage {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int t = sc.nextInt();
List<Point> houses = new ArrayList<Point>();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int a = sc.nextInt();
houses.add(new Point(x, a));
}
Collections.sort(houses, new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
return ((Integer) o1.x).compareTo(o2.x);
}
});
int pos = 2;
for (int i = 0; i < n - 1; i++) {
double end = houses.get(i).x + (houses.get(i).y+0.0)/2;
double start = houses.get(i+1).x - (houses.get(i+1).y+0.0)/2;
//System.out.println("end "+end+" start "+start);
double diff = start-end;
//System.out.println("diff");
if (Math.abs(diff-t) < 0.0000001) {
pos++;
}
if (diff > t) {
pos += 2;
}
}
System.out.println(pos);
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
//StringTokenizer st=new StringTokenizer(bf.readLine());
int n=Integer.parseInt(bf.readLine());
if(n%2==0) System.out.println(4+" "+(n-4));
else System.out.println(9+" "+(n-9));
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class D5 implements Runnable {
final double eps = 1e-9;
private void Solution() throws IOException {
double a = nextDouble(), v = nextDouble();
double l = nextDouble(), d = nextDouble(), w = nextDouble();
double t = 0;
if (w + eps > v) {
double s = v * v / (2 * a);
if (s + eps > l)
t = Math.sqrt(2 * l / a);
else {
double ta = v / a;
double sa = a * ta * ta / 2;
t = ta + (l - sa) / v;
}
} else {
double sv = v * v / (2 * a);
double sw = w * w / (2 * a);
if (sw + eps > d) {
if (sv + eps > l)
t = Math.sqrt(2 * l / a);
else {
double ta = v / a;
double sa = a * ta * ta / 2;
t = ta + (l - sa) / v;
}
} else {
double sd = (w * w - v * v) / (-2 * a);
if (sv + sd < eps + d)
t = v / a + (d - sv - sd) / v + (v - w) / a;
else {
double f = Math.sqrt(d * a + w * w / 2);
t = f / a + (f - w) / a;
}
if (sd + eps > l - d) {
double lv = Math.sqrt((l - d) * 2 * a + w * w);
t += (lv - w) / a;
} else {
t += (v - w) / a + (l - d - sd) / v;
}
}
}
out.printf("%.12f", t);
}
public static void main(String[] args) {
new D5().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tokenizer;
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
Solution();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
void print(Object... obj) {
for (int i = 0; i < obj.length; i++) {
if (i != 0)
out.print(" ");
out.print(obj[i]);
}
}
void println(Object... obj) {
print(obj);
print("\n");
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return in.readLine();
}
String next() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Trung Pham
*/
public class E {
public static double[] dp;
public static double[][] data;
public static int n;
public static void main(String[] args) {
Scanner in = new Scanner();
PrintWriter out = new PrintWriter(System.out);
n = in.nextInt();
data = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
data[i][j] = in.nextDouble();
}
}
dp = new double[1 << n];
Arrays.fill(dp, -1);
for (int i = 0; i < n; i++) {
int a = 1 << i;
out.print(cal(a) + " ");
}
out.close();
//System.out.print(builder.toString());
}
public static double cal(int mask) {
if (mask == (1 << n) - 1) {
// System.out.println(mask);
return 1;
}
if (dp[mask] != -1) {
return dp[mask];
}
double result = 0;
int c = 0;
for (int i = 0; i < n; i++) {
int a = 1 << i;
if ((a & mask) != 0) {
c++;
for (int j = 0; j < n; j++) {
int b = 1 << j;
if ((b & mask) == 0) {
result += (data[i][j] * cal(mask | b));
}
}
}
}
int nC2 = (c + 1) * c / 2;
dp[mask] = result / nC2;
return dp[mask];
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
static final int primeCount = 452;
static final int[] prime = new int[primeCount];
static void build_prime() {
boolean[] notPrime = new boolean[3200];
for (int i = 2; i < 3200; i++) {
if (notPrime[i]) continue;
for (int j = i * i; j < 3200; j += i) {
notPrime[j] = true;
}
}
int count = 0;
for (int i = 2; i < 3200; i++) {
if (notPrime[i]) continue;
prime[count++] = i;
}
}
private static void run(Reader in, PrintWriter out) throws IOException {
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = getReal(in.nextInt());
}
int[] pre = new int[n];
for (int i = 0; i < n; i++) pre[i] = -1;
TreeMap<Integer, Integer> exist = new TreeMap<>();
for (int i = 0; i < n; i++) {
Integer result = exist.get(a[i]);
if (result != null) {
pre[i] = result;
}
exist.put(a[i], i);
}
int[][] left = new int[m + 1][n];
for (int i = 0; i <= m; i++) {
int start = 0;
PriorityQueue<Integer> inSame = new PriorityQueue<>();
for (int j = 0; j < n; j++) {
if (pre[j] >= start) {
inSame.add(pre[j]);
if (inSame.size() > i) {
start = inSame.poll() + 1;
}
}
left[i][j] = start;
}
}
int[][] dp = new int[n][m + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= m; j++) {
if (j == 0) dp[i][0] = Integer.MAX_VALUE;
else dp[i][j] = dp[i][j - 1];
for (int k = 0; k <= j; k++) {
if (left[k][i] == 0) {
dp[i][j] = 1;
} else {
dp[i][j] = Math.min(dp[i][j], dp[left[k][i] - 1][j - k] + 1);
}
}
}
}
out.println(dp[n - 1][m]);
}
static int getReal(int x) {
int result = 1;
for (int i = 0; i < primeCount; i++) {
if (x % prime[i] == 0) {
int count = 0;
while (x % prime[i] == 0) {
count++;
x /= prime[i];
}
if (count % 2 == 1) {
result *= prime[i];
}
}
}
result *= x;
return result;
}
public static void main(String[] args) throws IOException {
Reader in = new Reader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
build_prime();
int t = in.nextInt();
for (int i = 0; i < t; i++) {
run(in, out);
}
out.flush();
in.close();
out.close();
}
static class Reader {
BufferedReader reader;
StringTokenizer st;
Reader(InputStreamReader stream) {
reader = new BufferedReader(stream, 32768);
st = null;
}
void close() throws IOException {
reader.close();
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
String nextLine() throws IOException {
return reader.readLine();
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
cubic
|
1497E2
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prakharjain
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
_992C solver = new _992C();
solver.solve(1, in, out);
out.close();
}
static class _992C {
static int mod = (int) 1e9 + 7;
public void solve(int testNumber, InputReader in, OutputWriter out) {
long x = in.nextLong();
long k = in.nextLong();
if (x == 0) {
out.println(0);
return;
}
long[][] base = new long[][]{{2, 0}, {1, 1}};
_992C.Matrix.N = 2;
base = _992C.Matrix.matrixPower(base, base, k);
x %= mod;
long ans = 2 * base[0][0] * x - base[1][0];
ans %= mod;
if (ans < 0)
ans += mod;
out.println(ans);
}
static public class Matrix {
static int N;
static long[][] id = new long[][]{{1, 0}, {0, 1}};
static long[][] matrixPower(long[][] mat, long[][] base, long pow) {
if (pow == 0) {
return id;
}
if (pow == 1) {
return base;
}
long[][] t = matrixPower(mat, base, pow / 2);
t = multiplyMatrix(t, t);
if (pow % 2 == 1) {
t = multiplyMatrix(t, base);
}
return t;
}
static long[][] multiplyMatrix(long[][] m, long[][] m2) {
long[][] ans = new long[N][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++) {
ans[i][j] = 0;
for (int k = 0; k < N; k++) {
ans[i][j] += m[i][k] * m2[k][j];
ans[i][j] %= mod;
}
}
return ans;
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
public void println(int i) {
writer.println(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 static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.*;import java.util.*;
import java.math.*;
public class Main{
static int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE;
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static int max(int a,int b)
{
return Math.max(a, b);
}
static int min(int a,int b)
{
return Math.min(a, b);
}
static int i()throws IOException
{
if(!st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return Integer.parseInt(st.nextToken());
}
static long l()throws IOException
{
if(!st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return Long.parseLong(st.nextToken());
}
static String s()throws IOException
{
if(!st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return st.nextToken();
}
static double d()throws IOException
{
if(!st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return Double.parseDouble(st.nextToken());
}
static void p(String p)
{
System.out.print(p);
}
static void p(int p)
{
System.out.print(p);
}
static void p(double p)
{
System.out.print(p);
}
static void p(long p)
{
System.out.print(p);
}
static void p(char p)
{
System.out.print(p);
}
static void p(boolean p)
{
System.out.print(p);
}
static void pl(String pl)
{
System.out.println(pl);
}
static void pl(int pl)
{
System.out.println(pl);
}
static void pl(char pl)
{
System.out.println(pl);
}
static void pl(double pl)
{
System.out.println(pl);
}
static void pl(long pl)
{
System.out.println(pl);
}
static void pl(boolean pl)
{
System.out.println(pl);
}
static void pl()
{
System.out.println();
}
static int[] ari(int n)throws IOException
{
int ar[]=new int[n];
if(!st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++)
ar[x]=Integer.parseInt(st.nextToken());
return ar;
}
static int[][] ari(int n,int m)throws IOException
{
int ar[][]=new int[n][m];
for(int x=0;x<n;x++)
{
st=new StringTokenizer(br.readLine());
for(int y=0;y<m;y++)
ar[x][y]=Integer.parseInt(st.nextToken());
}
return ar;
}
static long[] arl(int n)throws IOException
{
long ar[]=new long[n];
if(!st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++)
ar[x]=Long.parseLong(st.nextToken());
return ar;
}
static long[][] arl(int n,int m)throws IOException
{
long ar[][]=new long[n][m];
for(int x=0;x<n;x++)
{
st=new StringTokenizer(br.readLine());
for(int y=0;y<m;y++)
ar[x][y]=Long.parseLong(st.nextToken());
}
return ar;
}
static String[] ars(int n)throws IOException
{
String ar[]=new String[n];
if(!st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++)
ar[x]=st.nextToken();
return ar;
}
static String[][] ars(int n,int m)throws IOException
{
String ar[][]=new String[n][m];
for(int x=0;x<n;x++)
{
st=new StringTokenizer(br.readLine());
for(int y=0;y<m;y++)
ar[x][y]=st.nextToken();
}
return ar;
}
static double[] ard(int n)throws IOException
{
double ar[]=new double[n];
if(!st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++)
ar[x]=Double.parseDouble(st.nextToken());
return ar;
}
static double[][] ard(int n,int m)throws IOException
{
double ar[][]=new double[n][m];
for(int x=0;x<n;x++)
{
st=new StringTokenizer(br.readLine());
for(int y=0;y<m;y++)
ar[x][y]=Double.parseDouble(st.nextToken());
}
return ar;
}
static char[] arc(int n)throws IOException
{
char ar[]=new char[n];
if(!st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
for(int x=0;x<n;x++)
ar[x]=st.nextToken().charAt(0);
return ar;
}
static char[][] arc(int n,int m)throws IOException
{
char ar[][]=new char[n][m];
for(int x=0;x<n;x++)
{
st=new StringTokenizer(br.readLine());
for(int y=0;y<m;y++)
ar[x][y]=st.nextToken().charAt(0);
}
return ar;
}
static void par(int ar[])
{
for(int a:ar)
System.out.print(a+" ");
System.out.println();
}
static void par(int ar[][])
{
for(int a[]:ar)
{
for(int aa:a)
System.out.print(aa+" ");
System.out.println();
}
}
static void par(long ar[])
{
for(long a:ar)
System.out.print(a+" ");
System.out.println();
}
static void par(long ar[][])
{
for(long a[]:ar)
{
for(long aa:a)
System.out.print(aa+" ");
System.out.println();
}
}
static void par(String ar[])
{
for(String a:ar)
System.out.print(a+" ");
System.out.println();
}
static void par(String ar[][])
{
for(String a[]:ar)
{
for(String aa:a)
System.out.print(aa+" ");
System.out.println();
}
}
static void par(double ar[])
{
for(double a:ar)
System.out.print(a+" ");
System.out.println();
}
static void par(double ar[][])
{
for(double a[]:ar)
{
for(double aa:a)
System.out.print(aa+" ");
System.out.println();
}
}
static void par(char ar[])
{
for(char a:ar)
System.out.print(a+" ");
System.out.println();
}
static void par(char ar[][])
{
for(char a[]:ar)
{
for(char aa:a)
System.out.print(aa+" ");
System.out.println();
}
}
static public void main(String[] args)throws Exception{
st=new StringTokenizer(br.readLine());
int n=i();
int ar[]=ari(n);
Arrays.sort(ar);
int c=0;
for(int x=0;x<n;x++)
{
if(ar[x]!=-1)
{
c++;
for(int y=x+1;y<n;y++)
{
if(ar[y]!=-1)
{
if(ar[y]%ar[x]==0)
{
ar[y]=-1;
}
}
}
ar[x]=-1;
}
}
pl(c);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.awt.Point;
import java.util.Arrays;
import java.util.Scanner;
public class p15a {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int t = in.nextInt();
if(n == 1) {
System.out.println(2);
return;
}
house[] all = new house[n];
for (int i = 0; i < all.length; i++) {
all[i] = new house(in.nextInt(),in.nextInt());
}
Arrays.sort(all);
int count = 0;
for (int i = 0; i < all.length; i++) {
double left = all[i].center - (all[i].side*1.0/2);
double right = all[i].center + (all[i].side*1.0/2);
if(i == 0) {
count++;
double left2 = all[i+1].center - (all[i+1].side*1.0/2);
if(right+t<left2) {
count++;
}
continue;
}
if(i == all.length-1) {
count++;
double right2 = all[i-1].center + (all[i-1].side*1.0/2);
if(left-t>= right2) {
count++;
}
continue;
}
double left2 = all[i+1].center - (all[i+1].side*1.0/2);
double right2 = all[i-1].center + (all[i-1].side*1.0/2);
if(right+t<left2) {
count++;
}
if(left-t>=right2)
count++;
}
System.out.println(count);
}
}
class house implements Comparable<house>{
int center;
int side;
public house(int a , int b) {
center = a;
side = b;
}
public int compareTo(house o) {
return center-o.center;
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class CF1515E{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int md = sc.nextInt();
int k = (n + 1) / 2;
int[][] dp = new int[k + 1][n + 1]; dp[0][0] = 1;
for (int h = 1; h <= k; h++)
for (int l = h; l <= n - h + 1; l++)
dp[h][l] = (int) ((dp[h][l - 1] * 2L + dp[h - 1][l - 1]) * h % md);
int ans = 0;
for (int h = 1; h <= k; h++)
ans = (ans + dp[h][n - h + 1]) % md;
System.out.println(ans);
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.util.Scanner;
/**
* Created by misanand on 9/20/14.
*/
public class Recovery {
public static void main(String [] args) {
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
if( N%2 == 0) {
System.out.println( (4)+" "+(N-4));
}
else System.out.println( (9)+" "+(N-9));
scan .close();
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class nA {
Scanner in;
PrintWriter out;
void solve() {
int n = in.nextInt();
int a[] = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
sum+=a[i];
}
Arrays.sort(a);
int nowsum = 0;
int kol = 0;
for(int i = n - 1; i >= 0; i--){
if(nowsum <= sum / 2){
nowsum+=a[i];
kol++;
}else{
break;
}
}
out.println(kol);
}
void run() {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
try {
solve();
} finally {
out.close();
}
}
public static void main(String[] args) {
new nA().run();
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main7{
static class Pair
{
int x;
int y;
public Pair(int x,int y)
{
this.x= x;
this.y= y;
}
@Override
public int hashCode()
{
final int temp = 14;
int ans = 1;
ans =x*31+y*13;
return ans;
}
// Equal objects must produce the same
// hash code as long as they are equal
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (this.getClass() != o.getClass()) {
return false;
}
Pair other = (Pair)o;
if (this.x != other.x || this.y!=other.y) {
return false;
}
return true;
}
}
static class Pair1
{
String x;
int y;
int z;
}
static class Compare
{
/*static void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.start>p2.start)
{
return 1;
}
else if(p1.start==p2.start)
{
return 0;
}
else
{
return -1;
}
}
});
}
*/
}
public static long pow(long a, long b)
{
long result=1;
while(b>0)
{
if (b % 2 != 0)
{
result=(result*a)%mod;
b--;
}
a=(a*a)%mod;
b /= 2;
}
return result;
}
public static long fact(long num)
{
long value=1;
int i=0;
for(i=2;i<num;i++)
{
value=((value%mod)*i%mod)%mod;
}
return value;
}
public static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
/* public static long lcm(long a,long b)
{
return a * (b / gcd(a, b));
}
*/ public static long sum(int h)
{
return (h*(h+1)/2);
}
/*public static void dfs(int parent,boolean[] visited)
{
TreeSet<Integer> arr=new TreeSet<Integer>();
arr=graph.get(parent);
visited[parent]=true;
if(a[parent]==1)
{
flag=1;
}
if(a[parent]==2)
{
flag1=1;
}
if(flag==1 && flag1==1)
{
return;
}
Iterator itr=arr.iterator();
while(itr.hasNext())
{
int num=(int)itr.next();
if(visited[num]==false)
{
dfs(num,visited);
}
}
x1x`
}*/
// static int flag1=0;
static int[] dis;
static int mod=1000000007;
static ArrayList<ArrayList<Integer>> graph;
public static void bfs(int num,int size)
{
boolean[] visited=new boolean[size+1];
Queue<Integer> q=new LinkedList<>();
q.add(num);
ans[num]=1;
visited[num]=true;
while(!q.isEmpty())
{
int x=q.poll();
ArrayList<Integer> al=graph.get(x);
for(int i=0;i<al.size();i++)
{
int y=al.get(i);
if(visited[y]==false)
{
q.add(y);
ans[y]=ans[x]+1;
visited[y]=true;
}
}
}
}
static int[] ans;
// static int[] a;
public static int[] sort(int[] a)
{
int n=a.length;
ArrayList<Integer> ar=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
ar.add(a[i]);
}
Collections.sort(ar);
for(int i=0;i<n;i++)
{
a[i]=ar.get(i);
}
return a;
}
// static int flag=1;
static public void main(String args[])throws IOException
{
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
/* boolean[] prime=new boolean[1000001];
for(int i=2;i*i<=1000000;i++)
{
if(prime[i]==false)
{
for(int j=2*i;j<=1000000;j+=i)
{
prime[j]=true;
}
}
}
*/
int n=i();
int k=i();
long low=0;
long high=k;
long fin=0;
long ans=0;
for(int i=1;i<=n;i++)
{
ans+=i;
if(Math.abs(ans-k)+i==n && ans>=k)
{
fin=Math.abs(ans-k);
break;
}
}
pln(fin+"");
}
/**/
static InputReader in=new InputReader(System.in);
static OutputWriter out=new OutputWriter(System.out);
public static long l()
{
String s=in.String();
return Long.parseLong(s);
}
public static void pln(String value)
{
System.out.println(value);
}
public static int i()
{
return in.Int();
}
public static String s()
{
return in.String();
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars== -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
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 String() {
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 String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
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.Int();
return array;
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main
{
static HashMap<Integer,Integer> hm;
static int[] array;
static boolean marked[];
static int a , b ;
static int[] ans ;
public static void main( String args[])
{
Scanner sc = new Scanner(System.in);
int n ;
n = sc.nextInt();
a = sc.nextInt();
b = sc.nextInt();
hm = new HashMap<Integer,Integer>();
array = new int[n];
marked = new boolean[n];
for( int i = 0 ; i < n ; ++i )
{
array[i] = sc.nextInt();
hm.put( array[i] , i );
}
if( a == b)
{
boolean flag = true ;
for( int i = 0 ; i < n ; ++i )
if( !hm.containsKey( a - array[i]))
flag = false;
if( !flag)
System.out.println( "NO");
else
{
System.out.println("YES");
for( int i = 0 ; i < n ; ++i)
System.out.print("0 ");
}
}
else
{
ans = new int[n];
for( int i = 0 ; i < n ; ++i )
if( marked[i] ) continue;
else // hadle odd , even and single self loops
{
if( hm.containsKey(a - array[i]) && !hm.containsKey(b - array[i]))
{
propagateA(i);
}
else if( !hm.containsKey(a - array[i]) && hm.containsKey(b - array[i]))
{
// propagate b
propagateB(i);
}
else if(!hm.containsKey(a - array[i]) && !hm.containsKey(b - array[i]))
{
System.out.println("NO");
System.exit(0);
}
}
for( int i = 0 ; i < n ; ++i )
if( marked[i] ) continue;
else // handle doule self loops , cycles
{
start(i);
}
System.out.println("YES");
for( int i = 0 ; i < n; ++i)
System.out.print(ans[i] + " ");
System.exit(0);
}
}
static void propagateA(int index)
{
int i = index;
while( !marked[i])
{
if( hm.containsKey( a - array[i]) && !marked[ hm.get( a - array[i])])
{
marked[i] = true ;
ans [i] = 0 ;
i = hm.get( a - array[i]);
marked[i] = true ;
ans [i] = 0 ;
if( hm.containsKey( b - array[i]) && !marked[ hm.get( b - array[i])])
{
i = hm.get( b - array[i]);
}
}
else
{
System.out.println("NO");
System.exit(0);
}
}
}
static void propagateB(int index)
{
int i = index;
while( !marked[i])
{
if( hm.containsKey( b - array[i]) && !marked[ hm.get( b - array[i])])
{
marked[i] = true ;
ans [i] = 1 ;
i = hm.get( b - array[i]);
marked[i] = true ;
ans [i] = 1 ;
if( hm.containsKey( a - array[i]) && !marked[ hm.get( a - array[i])])
{
i = hm.get( a - array[i]);
}
}
else
{
System.out.println("NO");
System.exit(0);
}
}
}
static void start(int index)
{
int i = index ;
while( !marked[i] )
{
//System.out.println( a - array[i]);
if(!marked[ hm.get( a - array[i])])
{
marked[i] = true ;
ans [i] = 0 ;
i = hm.get( a - array[i]);
marked[i] = true ;
ans [i] = 0 ;
i = hm.get( b - array[i]);
}
}
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
/**
* 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;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
E2RotateColumnsHardVersion solver = new E2RotateColumnsHardVersion();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class E2RotateColumnsHardVersion {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
E2RotateColumnsHardVersion.Column[] columns = new E2RotateColumnsHardVersion.Column[m];
for (int i = 0; i < columns.length; ++i) columns[i] = new E2RotateColumnsHardVersion.Column(new int[n]);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
columns[j].v[i] = in.nextInt();
if (i == n - 1) columns[j].initMax();
}
}
Arrays.sort(columns, (o1, o2) -> o2.max - o1.max);
if (columns.length > n)
columns = Arrays.copyOf(columns, n);
long[] dp = new long[1 << n];
for (E2RotateColumnsHardVersion.Column c : columns) {
long[] ndp = new long[1 << n];
System.arraycopy(dp, 0, ndp, 0, dp.length);
for (int rot = 0; rot < n; ++rot) {
long[] temp = new long[1 << n];
System.arraycopy(dp, 0, temp, 0, dp.length);
for (int i = 0, pos = rot; i < n; ++i, ++pos) {
if (pos >= n) pos = 0;
int val = c.v[pos];
for (int j = 0; j < temp.length; ++j) {
if ((j & (1 << i)) == 0)
temp[j | (1 << i)] = Math.max(temp[j | (1 << i)], temp[j] + val);
}
}
for (int i = 0; i < ndp.length; ++i)
ndp[i] = Math.max(ndp[i], temp[i]);
}
dp = ndp;
}
out.println(dp[dp.length - 1]);
}
static class Column {
int[] v;
int max;
public Column(int[] v) {
this.v = v;
}
void initMax() {
max = 0;
for (int vv : v) max = Math.max(max, vv);
}
}
}
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 String next() {
return nextString();
}
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;
}
public String nextString() {
int c = pread();
while (isSpaceChar(c))
c = pread();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = pread();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class CFB {
static int n;
static FastScanner in;
public static void main(String[] args) throws Exception {
in = new FastScanner(System.in);
n = in.nextInt();
int a = query(1);
if(((a % 2)+2) % 2== 1){
System.out.println("! -1");
return;
}
if(a == 0){
System.out.println("! 1");
return;
}
bins(1 , n/2 + 1 , a , -a);
}
static void bins(int lo , int hi , int losign , int hisign){
int mid = (lo + hi)/2;
int k = query(mid);
if(k == 0){
System.out.println("! " + mid);
System.exit(0);
}
if(k > 0 && losign > 0 || k < 0 && losign < 0){
bins(mid , hi , k , hisign);
}
else {
bins(lo , mid , losign , k);
}
}
static int query(int i){
System.out.println("? " + i);
int a1 = in.nextInt();
System.out.println("? " + ((i + (n/2)) > n ? (i - (n/2)) : (i + (n/2))));
int a2 = in.nextInt();
return a1 - a2;
}
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String next() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.security.KeyException;
import java.util.HashMap;
import java.util.Scanner;
import java.util.TreeMap;
public class P15A
{
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt(), t = scan.nextInt();
TreeMap<Integer,Integer> hm = new TreeMap<Integer, Integer>();
for (int i = 0; i < n; i++) hm.put(scan.nextInt(),scan.nextInt());
int _x = 0, _a = 0, res = 2;
boolean started = false;
for (Integer key : hm.keySet())
{
if (!started)
{
_x = key;
_a = hm.get(_x);
started = true;
continue;
}
if (key - _x - ((Integer)hm.get(key) + _a)/2.0 > t) res +=2;
else if (key - _x - ((Integer)hm.get(key) + _a)/2.0 == t) res++;
_x = key;
_a = hm.get(_x);
}
System.out.println(res);
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
//q4
import java.io.*;
import java.util.*;
import java.math.*;
public class q4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
int query = in.nextInt();
while (query -- > 0) {
int n = in.nextInt();
int k = in.nextInt();
char[] arr = new char[n];
//slot all n into char array
String code = in.next();
for (int i = 0; i < n; i++) {
arr[i] = code.charAt(i);
}
//R, G, B cycle
int r = 0;
int g = 0;
int b = 0;
for (int i = 0; i < k; i++) {
if (i % 3 == 0) {
if (arr[i] == 'R') {g++; b++;}
else if (arr[i] == 'G') {r++; b++;}
else {r++; g++;} //if is 'B'
} else if (i % 3 == 1) {
if (arr[i] == 'G') {g++; b++;}
else if (arr[i] == 'B') {r++; b++;}
else {r++; g++;} //if is 'R'
} else { //if mod 3 is 2
if (arr[i] == 'B') {g++; b++;}
else if (arr[i] == 'R') {r++; b++;}
else {r++; g++;} //if is 'G'
}
}
//starting from kth position, if different then add 1, and check (j-k)th position
int rMin = r;
int gMin = g;
int bMin = b;
for (int j = k; j < n; j++) {
//R cycle
if ((j % 3 == 0 && arr[j] != 'R') ||
(j % 3 == 1 && arr[j] != 'G') ||
(j % 3 == 2 && arr[j] != 'B')) {
r++;
}
//R cycle
if (((j - k) % 3 == 0 && arr[j - k] != 'R') ||
((j - k) % 3 == 1 && arr[j - k] != 'G') ||
((j - k) % 3 == 2 && arr[j - k] != 'B')) {
r--;
}
rMin = Math.min(r, rMin);
//G cycle
if ((j % 3 == 0 && arr[j] != 'G') ||
(j % 3 == 1 && arr[j] != 'B') ||
(j % 3 == 2 && arr[j] != 'R')) {
g++;
}
if (((j - k) % 3 == 0 && arr[j - k] != 'G') ||
((j - k) % 3 == 1 && arr[j - k] != 'B') ||
((j - k) % 3 == 2 && arr[j - k] != 'R')) {
g--;
}
gMin = Math.min(gMin, g);
//B cycle
if ((j % 3 == 0 && arr[j] != 'B') ||
(j % 3 == 1 && arr[j] != 'R') ||
(j % 3 == 2 && arr[j] != 'G')) {
b++;
}
if (((j - k) % 3 == 0 && arr[j - k] != 'B') ||
((j - k) % 3 == 1 && arr[j - k] != 'R') ||
((j - k) % 3 == 2 && arr[j - k] != 'G')) {
b--;
}
bMin = Math.min(bMin, b);
}
out.println(Math.min(Math.min(rMin, gMin), bMin));
}
out.flush();
}
}
|
quadratic
|
1196_D2. RGB Substring (hard version)
|
CODEFORCES
|
import java.awt.List;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.TreeSet;
public final class CF_524_D2_D {
static boolean verb=true;
static void log(Object X){if (verb) System.err.println(X);}
static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}
static void logWln(Object X){if (verb) System.err.print(X);}
static void info(Object o){ System.out.println(o);}
static void output(Object o){outputWln(""+o+"\n"); }
static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}}
// Global vars
static BufferedWriter out;
static InputReader reader;
static long mod=1000000007;
static void process() throws Exception {
out = new BufferedWriter(new OutputStreamWriter(System.out));
reader=new InputReader(System.in);
long mymax=1L<<62;
log(mymax);
long cut=0;
int it=0;
long squares=1;
int GX=32;
long[] maxgen=new long[GX];
while (cut<2000000000000000000L){
maxgen[it]=cut;
//log("squares:"+squares+" cut:"+cut+" it:"+it+" size:"+(1L<<it));
it++;
cut=1+4*cut;
squares*=4;
}
//log(maxgen);
int T=reader.readInt();
for (int t=0;t<T;t++){
int n=reader.readInt();
long k=reader.readLong();
if (n>=GX){
output("YES "+(n-1));
} else {
// do first cut
long pieces=3;
long minc=1;
int size=n-1;
long maxc=1+maxgen[size];
while (size>0 && maxc<k){
minc+=pieces;
maxc+=pieces+maxgen[size-1]*(2*pieces-1);
size--;
pieces=2*pieces+1;
}
if (minc<=k && maxc>=k){
output("YES "+size);
} else {
output("NO");
//log("//check:"+maxc+" "+maxgen[n]);
}
//log("size:"+size+" minc:"+minc+" maxc:"+maxc);
}
}
try {
out.close();
}
catch (Exception EX){}
}
public static void main(String[] args) throws Exception {
process();
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res=new StringBuilder();
do {
res.append((char)c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public final int readInt() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
public final long readLong() throws IOException {
int c = read();
boolean neg=false;
while (isSpaceChar(c)) {
c = read();
}
char d=(char)c;
//log("d:"+d);
if (d=='-') {
neg=true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
//log("res:"+res);
if (neg)
return -res;
return res;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
public class A {
final int MOD = (int)1e9 + 7;
final double eps = 1e-12;
final int INF = (int)1e9;
public A () {
int N = sc.nextInt();
int K = sc.nextInt();
Long [] A = sc.nextLongs();
sort(A);
Set<Long> S = new HashSet<Long>();
for (long a : A) {
if (a % K == 0 && S.contains(H(a/K)))
continue;
S.add(H(a));
}
int res = S.size();
exit(res);
}
long P = probablePrime(60, new Random()).longValue();
long Q = probablePrime(60, new Random()).longValue();
long H(long x) {
return P*x + Q;
}
////////////////////////////////////////////////////////////////////////////////////
/* Dear hacker, don't bother reading below this line, unless you want to help me debug my I/O routines :-) */
static MyScanner sc = new MyScanner();
static class MyScanner {
public String next() {
newLine();
return line[index++];
}
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 String nextLine() {
line = null;
return readLine();
}
public String [] nextStrings() {
line = null;
return readLine().split(" ");
}
public char [] nextChars() {
return next().toCharArray();
}
public Integer [] nextInts() {
String [] L = nextStrings();
Integer [] res = new Integer [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Integer.parseInt(L[i]);
return res;
}
public Long [] nextLongs() {
String [] L = nextStrings();
Long [] res = new Long [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Long.parseLong(L[i]);
return res;
}
public Double [] nextDoubles() {
String [] L = nextStrings();
Double [] res = new Double [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Double.parseDouble(L[i]);
return res;
}
public String [] next (int N) {
String [] res = new String [N];
for (int i = 0; i < N; ++i)
res[i] = sc.next();
return res;
}
public Integer [] nextInt (int N) {
Integer [] res = new Integer [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInt();
return res;
}
public Long [] nextLong (int N) {
Long [] res = new Long [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLong();
return res;
}
public Double [] nextDouble (int N) {
Double [] res = new Double [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDouble();
return res;
}
public String [][] nextStrings (int N) {
String [][] res = new String [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextStrings();
return res;
}
public Integer [][] nextInts (int N) {
Integer [][] res = new Integer [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInts();
return res;
}
public Long [][] nextLongs (int N) {
Long [][] res = new Long [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLongs();
return res;
}
public Double [][] nextDoubles (int N) {
Double [][] res = new Double [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDoubles();
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 BufferedReader r;
MyScanner () {
this(new BufferedReader(new InputStreamReader(System.in)));
}
MyScanner(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 = readLine().split(" ");
index = 0;
}
}
}
static void print(Object o, Object... a) {
printDelim(" ", o, a);
}
static void cprint(Object o, Object... a) {
printDelim("", o, a);
}
static void printDelim (String delim, Object o, Object... a) {
pw.println(build(delim, o, a));
}
static void exit (Object o, Object... a) {
print(o, a);
exit();
}
static void exit () {
pw.close();
System.out.flush();
System.err.println("------------------");
System.err.println("Time: " + ((millis() - t) / 1000.0));
System.exit(0);
}
void NO() {
throw new Error("NO!");
}
////////////////////////////////////////////////////////////////////////////////////
static String build(String delim, Object o, Object... a) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : a)
append(b, p, delim);
return b.toString().trim();
}
static void append(StringBuilder b, Object o, String delim) {
if (o.getClass().isArray()) {
int L = Array.getLength(o);
for (int i = 0; i < L; ++i)
append(b, Array.get(o, i), delim);
} else if (o instanceof Iterable<?>) {
for (Object p : (Iterable<?>)o)
append(b, p, delim);
} else
b.append(delim).append(o);
}
////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
new A();
exit();
}
static void start() {
t = millis();
}
static PrintWriter pw = new PrintWriter(System.out);
static long t;
static long millis() {
return System.currentTimeMillis();
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
long k=Long.parseLong(br.readLine());
long l=1,h=1000000000000l;
long p[]=new long[13];
for(int i=1;i<=12;i++)
{
long ll=9*i;
p[i]=ll*(long)Math.pow(10,i-1);
p[i]+=p[i-1];
}
while(h-l>1)
{
long mid=(l+h)/2;
long num=(long)(Math.log(mid)/Math.log(10));
long l1=p[(int)num]+(num+1)*(mid-(long)Math.pow(10,num));
long l2=p[(int)num]+(num+1)*(mid-(long)Math.pow(10,num)+1);
if(k<=l1)
h=mid;
else if(k>l2)
l=mid;
else
{ l=mid; h=mid; }
}
if(h-l==1)
{
long num=(long)(Math.log(h)/Math.log(10));
long l1=p[(int)num]+(num+1)*(h-(long)Math.pow(10,num));
long l2=p[(int)num]+(num+1)*(h-(long)Math.pow(10,num)+1);
if(k>l1 && k<=l2)
{ l=h; }
}
long n=(long)(Math.log(l)/Math.log(10));
long u=p[(int)n]+(n+1)*(l-(long)Math.pow(10,n));
k-=u;
String ss=String.valueOf(l);
//System.out.println(l+" "+k);
System.out.println(ss.charAt((int)(k-1)));
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
/*
TASK: CFC
LANG: JAVA
*/
public class CFC {
static int n;
static int[][] dp;
static boolean[] s;
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in); //new FileInputStream(new File("CFC.in")));
//PrintWriter out = new PrintWriter(new File("CFC.out"));
n = in.nextInt();
if(n == 1){
System.out.println(1);
return;
}
dp = new int[n][n+1];
s = new boolean[n];
for(int i = 0;i <n; i++)s[i] = in.next().equals("s");
for(int j = 0;j < n; j++){
if(s[n-2])dp[n-1][j] = j+1;
else dp[n-1][j] = 1;
}
int suma , sumb;
for(int i = n-2; i >= 0; i--){
if(i == 0 ? true : s[i-1]){
if(s[i]) {
for (int j = 0; j < n; j++) {
dp[i][j] = ((j == 0 ? 0 : dp[i][j - 1]) + dp[i + 1][j]) % 1000000007;
}
}
else{
for(int j = 0;j < n; j++){
dp[i][j] = ((j == 0 ? 0 : dp[i][j-1]) + dp[i+1][j+1]) % 1000000007;
}
}
}
else{
if(s[i]){
for(int j = 0;j < n; j++){
dp[i][j] = dp[i+1][j];
}
}
else{
for(int j = 0;j < n; j++){
dp[i][j] = dp[i+1][j+1];
}
}
}
}
System.out.println(dp[0][0]);
}
private 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
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
//dp[firstInLoop][index][indentLevel]
private static int[][][] dp;
private static boolean[] wasLoop;
private static int MOD=1000000007;
private static int n;
public static void solve(FastScanner fs) {
n=fs.nextInt();
dp=new int[2][n][n];
for (int i=0; i<dp.length; i++)
for (int j=0; j<dp[i].length; j++)
Arrays.fill(dp[i][j], -1);
wasLoop=new boolean[n];
for (int i=0; i<n; i++)
wasLoop[i]=fs.next().equals("f");
int ans=go(0, 0, 0);
System.out.println(ans);
}
private static int go(int firstInLoop, int index, int indentLevel) {
if (index>=n)//base case
return 1;
if (dp[firstInLoop][index][indentLevel]!=-1)
return dp[firstInLoop][index][indentLevel];
//if I am forced, just do it
if (firstInLoop==1)
return dp[firstInLoop][index][indentLevel]=go(wasLoop[index]?1:0, index+1, indentLevel+(wasLoop[index]?1:0));
//if I am on the end level, I don't have a choice
if (indentLevel==0) {
return dp[firstInLoop][index][indentLevel]=go(wasLoop[index]?1:0, index+1, wasLoop[index]?1:0);
}
else {
//otherwise, add all the possibilities
int total=0;
total+=go(firstInLoop, index, indentLevel-1);
total+=go(wasLoop[index]?1:0, index+1, indentLevel+(wasLoop[index]?1:0));
total%=MOD;
return dp[firstInLoop][index][indentLevel]=total;
}
}
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;
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
FastReader in;
PrintWriter out;
int n;
public void solve(int testNumber, FastReader in, PrintWriter out) {
this.in = in;
this.out = out;
n = in.nextInt();
if (n % 4 != 0) {
out.println("! -1");
return;
}
int low = 0;
int high = n >> 1;
int fSign = Integer.signum(BValue(low));
if (fSign == 0) {
out.println("! " + (low + 1));
return;
}
while (high - low > 1) {
int mid = (high + low) >> 1;
int mSign = Integer.signum(BValue(mid));
if (mSign == 0) {
out.println("! " + (mid + 1));
return;
}
if (mSign == -fSign) {
high = mid;
} else {
low = mid;
}
}
out.println("! -1");
}
public int BValue(int index) {
out.println("? " + (index + 1));
out.flush();
int f = in.nextInt();
out.println("? " + (index + 1 + (n >> 1)));
out.flush();
int s = in.nextInt();
return f - s;
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[])
{
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int T=input.nextInt();
while(T-->0)
{
int n=input.nextInt();
int b[]=new int[n];
for(int i=0;i<n;i++)
{
b[i]=input.nextInt();
}
StringBuilder sb=new StringBuilder("");
int arr[]=new int[n+1];
out.println('1');
sb.append('1');
int size=1;
arr[size-1]=1;
for(int i=1;i<n;i++)
{
int a=b[i];
if(a==1)
{
size++;
arr[size-1]=1;
sb.append(".1");
out.println(sb.toString());
}
else
{
sb=new StringBuilder("");
int in=0;
for(int j=size-1;j>=0;j--)
{
if(arr[j]==a-1)
{
in=j;
break;
}
}
for(int j=0;j<in;j++)
{
sb.append(arr[j]+".");
}
sb.append(a);
size=in+1;
arr[size-1]=a;
out.println(sb.toString());
}
}
}
out.close();
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
public class FunctionHeight {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
long n = sc.nl();
long k = sc.nl();
long ans = (n+k-1)/n;
System.out.println(ans);
}
/////////// TEMPLATE FROM HERE /////////////////
private 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 ni() {
return Integer.parseInt(next());
}
float nf() {
return Float.parseFloat(next());
}
long nl() {
return Long.parseLong(next());
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
constant
|
1036_A. Function Height
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class C35C_BFS_Fire {
public static boolean[][] burning;
public static LinkedList<int[]> LitTrees; //which is best to use
public static int N, M;
public static int[] lastTree;
public static void main(String[] args) throws IOException {
// InputStreamReader stream = new InputStreamReader(System.in);
// BufferedReader input = new BufferedReader(stream);
BufferedReader input = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
StringTokenizer dataR = new StringTokenizer(input.readLine());
N = Integer.parseInt(dataR.nextToken());
M = Integer.parseInt(dataR.nextToken());
burning = new boolean[N+1][M+1];
StringTokenizer dataR1 = new StringTokenizer(input.readLine());
int K = Integer.parseInt(dataR1.nextToken());
StringTokenizer dataR2 = new StringTokenizer(input.readLine());
LitTrees = new LinkedList<int[]>();
for (int j = 0; j < K; j++){
int x = Integer.parseInt(dataR2.nextToken());
int y = Integer.parseInt(dataR2.nextToken());
int[] coord = {x, y};
LitTrees.add(coord);
burning[x][y] = true;
}
// while(ExistsAliveTree()){
// spread();
// }
spread();
// System.out.println(LitTrees.getLast()[0] + " " + LitTrees.getLast()[1]);
out.println(lastTree[0] + " " + lastTree[1]);
out.close();
}
public static void spread(){
while(!LitTrees.isEmpty()){
int[] studying = LitTrees.removeFirst(); //is iterator faster
int[] studying1 = {studying[0]-1, studying[1]};
int[] studying2 = {studying[0], studying[1]-1};
int[] studying3 = {studying[0], studying[1]+1};
int[] studying4 = {studying[0]+1, studying[1]};
if (studying1[0] >= 1 && !burning[studying1[0]][studying1[1]]){
LitTrees.add(studying1);
burning[studying1[0]][studying1[1]] = true;
}
if (studying2[1] >= 1 && !burning[studying2[0]][studying2[1]]){
LitTrees.add(studying2);
burning[studying2[0]][studying2[1]] = true;
}
if (studying3[1] < M+1 && !burning[studying3[0]][studying3[1]]){
LitTrees.add(studying3);
burning[studying3[0]][studying3[1]] = true;
}
if (studying4[0] < N+1 && !burning[studying4[0]][studying4[1]]){
LitTrees.add(studying4);
burning[studying4[0]][studying4[1]] = true;
}
lastTree = studying;
}
}
public static boolean ExistsAliveTree() {
if (LitTrees.size() == N*M){
return false;
} else{
return true;
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
//System.out.println("YES");
//System.out.println("NO");
//int n=sc.nextInt();
//int a[]=new int[n];
//for(int i=0;i<n;i++)
//a[i]=sc.nextInt();
//int n=sc.nextInt();
//long a[]=new long[n];
//for(int i=0;i<n;i++)
//a[i]=sc.nextLong();
//System.out.println();
//String str=sc.next();
//long n=sc.nextLong();
public static void main(String[] args) throws IOException{
Scanner sc=new Scanner(System.in);
// Reader sc=new Reader();
PrintWriter out=new PrintWriter(System.out);
int t = sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
ArrayList<Integer> al[]=new ArrayList[n+1];
for(int i=0;i<=n;i++)
al[i]=new ArrayList<>();
al[0].add(1);
int y;
y=sc.nextInt();
boolean flag=true;
for(int i=1;i<=n-1;i++) {
int x=sc.nextInt();
int idx=al[i-1].size()-1;
if(x!=1) {
while(flag) {
int ans=x-1;
if(al[i-1].get(idx)==ans) {
idx--;
break;
}
idx--;
}
}
for(int j=0;j<=idx;j++) {
al[i].add(al[i-1].get(j));
}
al[i].add(x);
}
for(int i=0;i<=n-1;i++) {
out.print(al[i].get(0));
for(int j=1;j<=al[i].size()-1;j++) {
out.print("."+al[i].get(j));
}
out.println();
}
}
out.flush();
out.close();
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.*;
public class Main
{
static double arr[][];
public static void main(String[] args)
{
try
{
Parserdoubt pd=new Parserdoubt(System.in);
PrintWriter pw=new PrintWriter(System.out);
int fishes=pd.nextInt();
arr=new double[fishes][fishes];
for(int i=0;i<fishes;i++)
for(int j=0;j<fishes;j++)
arr[i][j]=Double.parseDouble(pd.nextString());
double dp[]=new double[(1<<fishes)];
dp[dp.length-1]=1.0;
for(int c=dp.length-1;c>=0;c--)
{
if((c&(c-1))==0)
continue;
for(int i=0;i<fishes;i++)
for(int j=i+1;j<fishes;j++)
{
if(((1<<i)&c)!=0&&((1<<j)&c)!=0)
{
dp[c&~(1<<j)]+=arr[i][j]*dp[c];
dp[c&~(1<<i)]+=arr[j][i]*dp[c];
}
}
}
double s=0.0;
for(int i=0;i<fishes;i++)
s+=dp[1<<i];
for(int i=0;i<fishes;i++)
dp[1<<i]/=s;
int i=0;
for(i=0;i<fishes-1;i++)
pw.printf("%.6f ",dp[1<<i]);
pw.printf("%.6f\n",dp[1<<i]);
pw.close();
}
catch(Exception e)
{}
}
}
class Parserdoubt
{
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parserdoubt(InputStream in)
{
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws Exception
{
StringBuffer sb=new StringBuffer("");
byte c = read();
while (c <= ' ') c = read();
do
{
sb.append((char)c);
c=read();
}while(c>' ');
return sb.toString();
}
public char nextChar() throws Exception
{
byte c=read();
while(c<=' ') c= read();
return (char)c;
}
public int nextInt() throws Exception
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
public long nextLong() throws Exception
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
static void solve() throws IOException {
long a = nextLong(), b = nextLong();
long answer = get(a, b);
out.println(answer);
}
private static long get(long p, long q) {
if (p == 0) {
return 0;
}
if (q == 1) {
return p;
}
if (p == 1) {
return q;
}
if (p >= q) {
return p / q + get(p % q, q);
}
return q / p + get(p, q % p);
}
static BufferedReader br;
static StringTokenizer st;
static PrintWriter out;
public static void main(String[] args) throws IOException {
InputStream input = System.in;
PrintStream output = System.out;
File file = new File("a.in");
if (file.exists() && file.canRead()) {
input = new FileInputStream(file);
}
br = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(output);
solve();
out.close();
}
static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
public static void main(String[] args) throws Throwable {
new A().go();
}
void p(String s) {
System.out.println(s);
}
void go() throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] t = in.readLine().split(" ");
long a = Long.parseLong(t[0]), b = Long.parseLong(t[1]);
long mv = 0;
while (a > 1 && b > 1) {
if (a > b) {
long tt = a;
a = b;
b = tt;
}
mv += b / a;
b %= a;
}
System.out.println(mv + Math.max(a, b));
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class BetaRound23_A implements Runnable {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws IOException {
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());
}
@Override
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);
}
}
public static void main(String[] args) {
new Thread(new BetaRound23_A()).start();
}
void solve() throws IOException {
char[] s = in.readLine().toCharArray();
int n = s.length;
for (int ans = n - 1; ans >= 1; ans--) {
for (int i = 0; i < n - ans + 1; i++) {
for (int j = i + 1; j < n - ans + 1; j++) {
int count = 0;
for (int k = 0; k < ans; k++) {
if (s[i + k] == s[j + k]) count++;
else break;
}
if (count == ans) {
out.print(ans);
return;
}
}
}
}
out.print(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
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
|
/**
* author: derrick20
* created: 11/11/20 1:03 PM
*/
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class OnTheBench {
public static void main(String[] args) {
setupCombo(301);
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
long[] a = sc.nextLongs(N);
boolean[] vis = new boolean[N];
int[] groups = new int[N + 1];
int G = 0;
for (int i = 0; i < N; i++) {
if (!vis[i]) {
vis[i] = true;
int elems = 1;
for (int j = i + 1; j < N; j++) {
long prod = a[i] * a[j];
long root = (long) Math.sqrt(prod);
if (!vis[j] && prod == root * root) {
vis[j] = true;
elems++;
}
}
groups[++G] = elems;
}
}
long[][] dp = new long[G + 1][N + 1];
// dp[g][bad] = ways to interleave first g groups for a given # of bad pairs
dp[0][0] = 1;
// dp[0][k] = 0, k != 0
int total = 0;
for (int prefix = 1; prefix <= G; prefix++) {
int amt = groups[prefix];
for (int prevBad = 0; prevBad <= max(0, total - 1); prevBad++) {
for (int fixed = 0; fixed <= min(prevBad, amt); fixed++) {
for (int slots = max(1, fixed); slots <= min(amt, total + 1); slots++) {
int introduced = amt - slots;
long ways = mult(
choose[prevBad][fixed],
choose[total + 1 - prevBad][slots - fixed],
choose[amt - 1][slots - 1],
fact[amt],
dp[prefix - 1][prevBad]
);
int currBad = prevBad + introduced - fixed;
dp[prefix][currBad] = (dp[prefix][currBad] + ways) % mod;
}
}
}
total += amt;
// System.out.println(Arrays.toString(dp[prefix]));
}
out.println(dp[G][0]);
out.close();
}
static long mod = (long) 1e9 + 7;
static long[][] choose;
static long[] fact;
static long mult(long... multiplicands) {
long ans = 1;
for (long v : multiplicands) {
ans = (ans * v) % mod;
}
return ans;
}
static void setupCombo(int MAX) {
choose = new long[MAX + 1][MAX + 1];
fact = new long[MAX + 1];
choose[0][0] = 1;
fact[0] = 1;
for (int i = 1; i <= MAX; i++) {
fact[i] = (long) i * fact[i - 1] % mod;
choose[i][0] = 1;
for (int j = 1; j < i; j++) {
choose[i][j] = (choose[i - 1][j - 1] + choose[i - 1][j]) % mod;
}
choose[i][i] = 1;
}
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static void ASSERT(boolean assertion, String message) {
if (!assertion) throw new AssertionError(message);
}
static void ASSERT(boolean assertion) {
if (!assertion) throw new AssertionError();
}
}
|
cubic
|
840_C. On the Bench
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.util.Map.Entry;
public class cf2{
static int x0;
static int y0;
static int x1;
static int y1;
static HashMap<Integer,HashSet<Integer>>allowed;
static HashMap<Integer,HashMap<Integer,Integer>>cost;
static int []dx= {-1,-1,-1,0,0,0,1,1,1};
static int []dy= {-1,0,1,-1,0,1,-1,0,1};
static int highbound=(int)1e9;
static boolean valid(int i,int j) {
if(i>=1 && i<=highbound && j>=1 && j<=highbound && allowed.containsKey(i) && allowed.get(i).contains(j))return true;
return false;
}
static long ans;
static class Triple implements Comparable<Triple>
{
int i,j,cost;
Triple(int x, int y, int z){i = x; j = y; cost = z;}
public int compareTo(Triple t) {
return this.cost - t.cost;
}
public String toString() {
return i+" "+j+" "+cost;
}
}
public static int dijkstra()
{
PriorityQueue<Triple> q = new PriorityQueue<Triple>();
q.add(new Triple(x0,y0,0));
HashMap<Integer,Integer>z=new HashMap<Integer,Integer>();z.put(y0,0);
cost.put(x0,z);
while(!q.isEmpty())
{
Triple cur = q.remove();
//if(cur.i==x1 && cur.j==y1)continue;
if(cur.cost > cost.getOrDefault(cur.i,new HashMap<Integer,Integer>()).getOrDefault(cur.j,1000000000))
continue;
for(int k = 0; k < 9; k++)
{
int x = cur.i + dx[k];
int y = cur.j + dy[k];
int c=cost.getOrDefault(x,new HashMap<Integer,Integer>()).getOrDefault(y,1000000000);
if(valid(x,y) && cur.cost +1 < c)
{
HashMap<Integer,Integer>zz=new HashMap<Integer,Integer>();zz.put(y,cur.cost+1);
cost.put(x,zz);
q.add(new Triple(x,y,cur.cost+1));
}
}
}
return cost.getOrDefault(x1,new HashMap<Integer,Integer>()).getOrDefault(y1,-1);
}
static int t;static int n;
static int []ds;
static int []gs;
static int [][]memo;
static int dp(int lastg,int msk,int sum) {
if(sum==t)return 1;
if(msk==(1<<n)-1) {
return 0;
}
if(memo[lastg][msk]!=-1)return memo[lastg][msk];
int tot=0;
for(int i=0;i<n;i++) {
if(((1<<i)&msk)==0 && gs[i]!=lastg) {
tot=(tot+dp(gs[i],msk|(1<<i),sum+ds[i]))%(1000000007);
}
}
return memo[lastg][msk]=tot;
}
public static void main(String[] args) throws IOException{
MScanner sc = new MScanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
n=sc.nextInt();
t=sc.nextInt();
ds=new int[n];gs=new int[n];
for(int i=0;i<n;i++) {
ds[i]=sc.nextInt();gs[i]=sc.nextInt();
}
memo=new int[4][1<<n];
for(int []i:memo)Arrays.fill(i,-1);
pw.println(dp(0, 0,0));
pw.flush();
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static int[]primes;
static int sizeofp=0;
static int[] isComposite;
static void sieve(int N) // O(N log log N)
{
isComposite = new int[N+1];
isComposite[0] = isComposite[1] = 1;
primes = new int[N];
for (int i = 2; i <= N; ++i)
if (isComposite[i] == 0)
{
primes[sizeofp++]=i;;
if(1l * i * i <= N)
for (int j = i * i; j <= N; j += i)
isComposite[j] = 1;
}
}
static class pair implements Comparable<pair>{
int num;int idx;
pair(int x,int y){
num=x;idx=y;
}
@Override
public int compareTo(pair o) {
if(num!=o.num) {
return num-o.num;
}
return idx-o.idx;
}
@Override
public int hashCode()
{
return Objects.hash(num,idx) ;
}
public boolean equals(pair o) {
if(this.compareTo(o)==0)return true;
return false;
}
public String toString() {
return "("+0+" "+0+")";
}
}
static class MScanner
{
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.io.*;
public class B14G {
public static void main(String[] args) throws IOException {
init_io();
int t = nint();
while(t-- > 0) {
int N = nint();
if (N % 2 != 0) {
out.println("NO"); continue;
}
N /= 2;
int sqrt = (int)(Math.round(Math.sqrt(N)));
int sqrt2 = (int)(Math.round(Math.sqrt(N/2)));
if (sqrt * sqrt == N || sqrt2 * sqrt2 * 2 == N) {
out.println("YES");
}
else {
out.println("NO");
}
}
out.close();
}
static StreamTokenizer in;
static PrintWriter out;
static BufferedReader br;
static int nint() throws IOException {
in.nextToken();
return (int) in.nval;
}
static void init_io() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
in = new StreamTokenizer(br);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.util.Scanner;
public class BB {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long a=sc.nextLong();
long b=sc.nextLong();
if(b-a>(long)2){
if(a%(long)2==0){
System.out.print(a+" "+(a+1)+" "+(a+2));
return;
}else{
System.out.print(a+1+" "+(a+2)+" "+(a+3));
return;
}
}else{
if(b-a<=(long)1){
System.out.println(-1);
return;
}
if(b-a==(long)2){
if(a%(long)2==0){
System.out.print(a+" "+(a+1)+" "+(a+2));
return;
}else{
System.out.print(-1);
return;
}
}
}
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class Round364_div2_C {
public static void main(String[] args) throws IOException {
FastReader in = new FastReader(System.in);
PrintWriter out = new PrintWriter(System.out);
solve(in, out);
out.flush();
}
public static void solve(FastReader in, PrintWriter out) {
int n = in.readInt();
String s = in.readString();
int totalCnt = (int) s.chars().distinct().count();
Map<Character, Integer> curCnts = new HashMap<>();
int solution = s.length();
int i = 0;
for (int j = 0 ; j < s.length() ; j++) {
// add s_j
char sj = s.charAt(j);
curCnts.put(sj, curCnts.getOrDefault(sj, 0) + 1);
// contract s_i
while (curCnts.getOrDefault(s.charAt(i), 0) > 1) {
char si = s.charAt(i);
int siCnt = curCnts.get(si);
if (siCnt > 1) {
curCnts.put(si, siCnt - 1);
} else {
curCnts.remove(si);
}
i++;
}
if (curCnts.size() == totalCnt) {
solution = Math.min(solution, j - i + 1);
}
}
out.println(solution);
}
/**
* Custom buffered reader. Faster than Scanner and BufferedReader + StringTokenizer.
*/
static class FastReader {
private final InputStream stream;
private int current;
private int size;
private byte[] buffer = new byte[1024 * 8];
public FastReader(InputStream stream) {
this.stream = stream;
current = 0;
size = 0;
}
public int readInt() {
int sign = 1;
int abs = 0;
int c = readNonEmpty();
if (c == '-') {
sign = -1;
c = readAny();
}
do {
if (c < '0' || c > '9') {
throw new IllegalStateException();
}
abs = 10 * abs + (c - '0');
c = readAny();
} while (!isEmpty(c));
return sign * abs;
}
public int[] readIntArray(int n) {
int[] array = new int[n];
for (int i = 0 ; i < n ; i++) {
array[i] = readInt();
}
return array;
}
public char readChar() {
return (char) readNonEmpty();
}
public String readString() {
StringBuffer sb = new StringBuffer();
int c;
do {
c = readAny();
} while (isEmpty(c));
do {
sb.append((char) c);
c = readAny();
} while (!isEmpty(c));
return sb.toString();
}
private int readAny() {
try {
if (current >= size) {
current = 0;
size = stream.read(buffer);
if (size < 0) {
return -1;
}
}
} catch (IOException e) {
throw new RuntimeException("Failed to readAny next byte", e);
}
return buffer[current++];
}
private int readNonEmpty() {
int result;
do {
result = readAny();
} while (isEmpty(result));
return result;
}
private static boolean isEmpty(int c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == -1;
}
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.*;
import java.util.StringTokenizer;
/**
* Codeforces 11D - A Simple Task
* Created by Darren on 14-10-21.
* O(2^n * n^2) time and O(2^n * n) space.
*
* Tag: dynamic programming, bitmask, graph
*/
public class D {
Reader in = new Reader(System.in);
PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
new D().run();
}
int n, m;
boolean[][] adjacency; // Adjacency matrix
void run() throws IOException {
n = in.nextInt();
m = in.nextInt();
adjacency = new boolean[n+1][n];
for (int i = 0; i < m; i++) {
int u = in.nextInt(), v = in.nextInt();
adjacency[u-1][v-1] = adjacency[v-1][u-1] = true; // Converted to 0-based
}
final int MASK_BOUND = (1 << n);
// dp[i][j]: the number of Hamiltonian walks over the subgraph formed by
// the mask i, starting at the smallest vertex and ending at vertex j
// dp[1<<i][i] = 1;
// dp[i][j] = sum_k{dp[i^j][k]} if j is within the mask i and (k,j) is an edge
long[][] dp = new long[MASK_BOUND][n];
for (int i = 0; i < n; i++)
dp[1<<i][i] = 1;
long sum = 0;
for (int mask = 1; mask < MASK_BOUND; mask++) {
int lowestVertex = (int) (Math.log(lowest(mask)) / Math.log(2));
for (int i = 0; i < n; i++) {
if (bit(i, mask) && i != lowestVertex) {
for (int j = 0; j < n; j++) {
if (adjacency[j][i]) {
dp[mask][i] += dp[mask^(1<<i)][j];
}
}
// A simple cycle with length not smaller than 3
if (count(mask) >= 3 && adjacency[lowestVertex][i])
sum += dp[mask][i];
} else {
// dp[mask][i] = 0
}
}
}
out.println(sum / 2); // A cycle is counted twice
out.flush();
}
// Return the number of '1's in the binary representation of the mask
int count(int mask) {
int count = 0;
while (mask > 0) {
if ((mask & 1) == 1)
count++;
mask >>= 1;
}
return count;
}
// Return an integer with only one '1' in its binary form and the position of the
// only '1' is the same with the lowest '1' in mask
int lowest(int mask) {
// mask = x1b where b is a sequence of zeros;
// -mask = x'1b', where x' and b' is formed by reversing digits in x and b;
// mask & (-mask) = 0...010...0, where the only 1 is the lowest 1 in mask
return mask & (-mask);
}
// Check whether the digit at the given index of the mask is '1'
boolean bit(int index, int mask) {
return ((1 << index) & mask) > 0;
}
static class Reader {
BufferedReader reader;
StringTokenizer tokenizer;
public Reader(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/** get next word */
String nextToken() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer( reader.readLine() );
}
return tokenizer.nextToken();
}
String readLine() throws IOException {
return reader.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt( nextToken() );
}
long nextLong() throws IOException {
return Long.parseLong( nextToken() );
}
double nextDouble() throws IOException {
return Double.parseDouble( nextToken() );
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.*;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println("0 0 " + n);
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
List<Clause> clauses = new ArrayList<Clause>();
int[] p = new int[n];
Map<Integer, Integer> id = new HashMap<>();
for (int i = 0; i < n; i++) {
p[i] = in.nextInt();
id.put(p[i], i);
}
// var[i] = true means p[i] \in A
for (int i = 0; i < n; i++) {
int x = p[i];
Integer j = id.get(a - x);
if (j == null) {
// var[i] is false
clauses.add(new Clause(i, i, true, false));
} else {
clauses.add(new Clause(i, j, true, true));
clauses.add(new Clause(j, i, false, false));
}
j = id.get(b - x);
if (j == null) {
// var[i] is true
clauses.add(new Clause(i, i, false, true));
} else {
clauses.add(new Clause(i, j, false, false));
clauses.add(new Clause(j, i, true, true));
}
}
SAT2Solver solver = new SAT2Solver(n);
if (!solver.solve(clauses)) {
out.println("NO");
return;
}
out.println("YES");
for (int i = 0; i < n; i++) {
if (i > 0) {
out.print(" ");
}
if (solver.isTrue[i]) {
out.print(0);
} else {
out.print(1);
}
}
out.println();
}
class Clause {
int v1, v2;
boolean neg1, neg2;
// Example: (x=>!y) is translated to Clause(x, y, true, false)
Clause(int v1, int v2, boolean pos1, boolean pos2) {
this.v1 = v1;
this.v2 = v2;
this.neg1 = !pos1;
this.neg2 = !pos2;
}
}
class SAT2Solver {
List<Integer>[] g;
boolean[] isTrue;
int n;
int numComps;
int[] low;
int[] vis;
int[] comp;
boolean[] onStack;
int[] stack;
int sp;
int globalTime;
SAT2Solver(int n) {
this.n = n;
isTrue = new boolean[2 * n];
vis = new int[2 * n];
low = new int[2 * n];
stack = new int[2 * n];
comp = new int[2 * n];
onStack = new boolean[2 * n];
g = new List[2 * n];
}
public boolean solve(List<Clause> clauses) {
for (int i = 0; i < 2 * n; i++) {
g[i] = new ArrayList<Integer>();
}
for (Clause clause : clauses) {
int v1 = clause.v1;
int v2 = clause.v2;
boolean neg1 = clause.neg1;
boolean neg2 = clause.neg2;
if (neg1) {
v1 = negate(v1);
}
if (neg2) {
v2 = negate(v2);
}
//g[negate(v1, n)].add(v2);
//g[negate(v2, n)].add(v1);
g[v1].add(v2);
}
Arrays.fill(vis, -1);
Arrays.fill(onStack, false);
sp = 0;
globalTime = 0;
numComps = 0;
for (int i = 0; i < 2 * n; i++) {
if (vis[i] < 0) {
dfsTarjan(i);
}
}
int[] firstInComp = new int[numComps];
Arrays.fill(firstInComp, -1);
int[] nextSameComp = new int[2 * n];
for (int i = 0; i < 2 * n; i++) {
int c = comp[i];
nextSameComp[i] = firstInComp[c];
firstInComp[c] = i;
}
List<Integer>[] invertedCompEdges = new List[numComps];
for (int i = 0; i < numComps; i++) {
invertedCompEdges[i] = new ArrayList<Integer>();
}
for (int i = 0; i < 2*n; i++) {
for (int j : g[i]) {
invertedCompEdges[comp[j]].add(comp[i]);
}
}
boolean[] compIsTrue = new boolean[numComps];
Arrays.fill(compIsTrue, true);
for (int c = 0; c < numComps; c++) {
if (!compIsTrue[c]) {
continue;
}
for (int i = firstInComp[c]; i >= 0; i = nextSameComp[i]) {
int nc = comp[negate(i)];
if (c == nc) {
return false;
}
}
for (int i = firstInComp[c]; i >= 0; i = nextSameComp[i]) {
int nc = comp[negate(i)];
dfsReject(nc, invertedCompEdges, compIsTrue);
}
}
for (int i = 0; i < 2 * n; i++) {
isTrue[i] = compIsTrue[comp[i]];
}
for (int i = 0; i < n; i++) {
if (isTrue[i] && isTrue[negate(i)]) {
throw new AssertionError();
}
if (!isTrue[i] && !isTrue[negate(i)]) {
return false;
}
}
return true;
}
private int negate(int i) {
return i + (i < n ? n : -n);
}
private void dfsReject(int c, List<Integer>[] invertedCompEdges, boolean[] compIsTrue) {
if (!compIsTrue[c]) {
return;
}
compIsTrue[c] = false;
for (int p : invertedCompEdges[c]) {
dfsReject(p, invertedCompEdges, compIsTrue);
}
}
void dfsTarjan(int v) {
vis[v] = globalTime;
low[v] = globalTime;
++globalTime;
stack[sp++] = v;
onStack[v] = true;
for (int u : g[v]) {
if (vis[u] < 0) {
dfsTarjan(u);
if (low[v] > low[u]) {
low[v] = low[u];
}
} else if (onStack[u] && low[v] > vis[u]) {
low[v] = vis[u];
}
}
if (low[v] == vis[v]) {
while (true) {
int u = stack[--sp];
onStack[u] = false;
comp[u] = numComps;
if (u == v) {
break;
}
}
++numComps;
}
}
}
}
class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
// Created by Whiplash99
import java.io.*;
import java.util.*;
public class A
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
long N,K,tmp,ans=0;
String s[]=br.readLine().trim().split(" ");
N=Long.parseLong(s[0]);
K=Long.parseLong(s[1]);
long l=1,r=N,mid;
while(l<=r)
{
mid=(l+r)/2;
tmp=mid*(mid+1)/2;
tmp-=N;
tmp+=mid;
if(tmp==K)
{
ans=N-mid;
break;
}
else if(tmp>K)
r=mid-1;
else
l=mid+1;
}
System.out.println(ans);
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.*;
public class NewEmpty
{
public static void main(String[] args)
{
Scanner blabla=new Scanner(System.in);
long a,b,c=0,d;
a=blabla.nextLong();
b=blabla.nextLong();
while (b!=0){
c+=(a/b);
a=a%b;
d=a;
a=b;
b=d;
}
System.out.println(c);
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.util.Scanner;
public class A470 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int start=4;
while(true){
if((start%2==0||start%3==0)&&((n-start)%2==0||(n-start)%3==0))
{
System.out.println(start+" "+(n-start));
return;
}
else
start++;
}
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.util.* ;
public class PythonIndentation
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in) ;
int n = in.nextInt() ;
boolean[] lst = new boolean[n] ;
for(int i=0;i<n;i++)
{
lst[i] = (in.next().equals("s"))?false:true ;
}
System.out.println(dp(lst)) ;
}
static int dp(boolean[] lst)
{//false in lst means an "s" (simple statement), and true a "f"(for loop)
int[][] dp = new int[2][lst.length] ;
dp[0][0] = 1 ;
for(int i=1;i<lst.length;i++)
{
for(int j=0;j<lst.length;j++)
{
if(lst[i-1])//(i-1)st statement is a for loop
{
if(j==0)
dp[i%2][j] = 0 ;
else
dp[i%2][j] = dp[(i-1)%2][j-1] ;
}
else//i-1 st statement is a simple statement
{
if(j==0)
{
int temp = 0 ;
for(int k=0;k<lst.length;k++)
temp = (temp+dp[(i-1)%2][k])%1000000007 ;
dp[i%2][j] = temp ;
}
else
dp[i%2][j] = (dp[i%2][j-1]-dp[(i-1)%2][j-1])%1000000007 ;
}
}
}
int ans = 0 ;
for(int i=0;i<lst.length;i++)
{
ans = (ans + dp[(lst.length-1)%2][i])%1000000007 ;
}
if(ans<0)
ans = ans + 1000000007 ;
return ans ;
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
int n = Integer.parseInt(tokenizer.nextToken());
int k = Integer.parseInt(tokenizer.nextToken());
System.out.println((int)(n-(-3.0+Math.sqrt(9.0+8.0*(n+k)))/2.0));
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[])
{
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int T=1;
while(T-->0)
{
long k=input.nextLong();
long v=9;
long s=0;
int x=1;
while(true)
{
if(s+v*x>k)
{
break;
}
s+=v*x;
v*=10;
x++;
}
if(s==k)
{
out.println(9);
}
else
{
long d=k-s;
long u=d/x;
long rem=d%x;
long nu=(long)Math.pow(10,x-1);
nu+=u;
if(rem==0)
{
nu--;
out.println(nu%10);
}
else
{
String str=String.valueOf(nu);
out.println(str.charAt((int)(rem-1)));
}
}
}
out.close();
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Kaudo {
static Reader in =new Reader();
static StringBuilder Sd=new StringBuilder();
static long ans,res,lot,max;
static List<Integer>gr[];
static ArrayList<Integer> A=new ArrayList();
static String ch[];
public static void main(String [] args) {
int n=in.nextInt(),a[]=new int [n],g=0;
for(int i=0;i<n;i++){
a[i]=in.nextInt();
if(a[i]==1){System.out.println("1");return;}
}
ans=0;
Arrays.sort(a);
for(int i=0;i<n;i++){
int x=a[i];
if(x>0){ans++;
for(int u=i;u<n;u++){
if(a[u]%x==0){a[u]=0;}
}}
}
System.out.println(ans);
}
static int gcd(int a,int b){
if(b==0)return a;
return gcd(b,a%b);
}
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public int nextInt(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Set;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Washoum
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
inputClass in = new inputClass(inputStream);
PrintWriter out = new PrintWriter(outputStream);
F2SameSumBlocksHard solver = new F2SameSumBlocksHard();
solver.solve(1, in, out);
out.close();
}
static class F2SameSumBlocksHard {
public void solve(int testNumber, inputClass sc, PrintWriter out) {
int n = sc.nextInt();
int[] tab = new int[n];
int[] s = new int[n];
for (int i = 0; i < n; i++) {
tab[i] = sc.nextInt();
if (i > 0)
s[i] = s[i - 1] + tab[i];
else
s[0] = tab[0];
}
HashMap<Integer, F2SameSumBlocksHard.Pair> sums = new HashMap<>();
F2SameSumBlocksHard.Pair p;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j > 0) {
if (sums.get(s[i] - s[j - 1]) != null) {
if (sums.get(s[i] - s[j - 1]).last < j) {
sums.get(s[i] - s[j - 1]).sum++;
sums.get(s[i] - s[j - 1]).last = i;
}
} else {
p = new F2SameSumBlocksHard.Pair();
p.sum = 1;
p.last = i;
sums.put(s[i] - s[j - 1], p);
}
} else {
if (sums.get(s[i]) != null) {
if (sums.get(s[i]).last < j) {
sums.get(s[i]).sum++;
sums.get(s[i]).last = i;
}
} else {
p = new F2SameSumBlocksHard.Pair();
p.sum = 1;
p.last = i;
sums.put(s[i], p);
}
}
}
}
Iterator<Map.Entry<Integer, F2SameSumBlocksHard.Pair>> it = sums.entrySet().iterator();
Map.Entry<Integer, F2SameSumBlocksHard.Pair> t;
int maxsum = 0;
int cnt = 0;
while (it.hasNext()) {
t = it.next();
if (t.getValue().sum > cnt) {
maxsum = t.getKey();
cnt = t.getValue().sum;
}
}
out.println(cnt);
int start = 0;
for (int i = 0; i < n; i++) {
for (int j = start; j <= i; j++) {
if (j > 0) {
if (s[i] - s[j - 1] == maxsum) {
out.println((j + 1) + " " + (i + 1));
start = i + 1;
break;
}
} else {
if (s[i] == maxsum) {
out.println((j + 1) + " " + (i + 1));
start = i + 1;
break;
}
}
}
}
}
static class Pair {
int sum;
int last;
}
}
static class inputClass {
BufferedReader br;
StringTokenizer st;
public inputClass(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import static java.lang.Math.*;
public class Main2 {
private FastScanner scanner = new FastScanner();
public static void main(String[] args) {
new Main2().solve();
}
private void solve() {
int n = scanner.nextInt();
int a[][] = new int[n][3];
for (int i = 0; i < n; i++) {
a[i][0] = scanner.nextInt();
a[i][1] = scanner.nextInt();
a[i][2] = i;
}
int l = -1, r = -1;
Arrays.sort(a, (o1, o2) -> {
if (o1[0] != o2[0]) {
return o1[0] - o2[0];
} else {
return o2[1] - o1[1];
}
});
int maxr = -1, maxi = -1;
for (int i = 0; i < n; i++) {
if (a[i][1] <= maxr) {
l = a[i][2] + 1;
r = maxi + 1;
break;
}
if (a[i][1] > maxr) {
maxi = a[i][2];
maxr = a[i][1];
}
}
System.out.println(l + " " + r);
}
boolean check(int cnt[][], int[] tcnt, int mid) {
boolean ok = true;
for (int j = 0; j < 27; j++) {
if (cnt[mid][j] < tcnt[j]) {
ok = false;
}
}
return ok;
}
class Pair {
int c, f;
}
class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
Integer[] nextA(int n) {
Integer a[] = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
nlogn
|
976_C. Nested Segments
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.Random;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
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();
char[] str = IOUtils.readCharArray(in, n);
for (int i = 0; i < n; i++) {
if (str[i] <= 'Z') {
str[i] = (char) (str[i] - 'A');
} else {
str[i] = (char) (str[i] - 'a' + 26);
}
}
IntHashSet set = new IntHashSet();
for (char c : str) {
set.add(c);
}
int max = 26 + 26;
int[][] next = new int[max][n];
ArrayUtils.fill(next, -1);
for (int i = n - 2; i >= 0; i--) {
for (int ch = 0; ch < max; ch++) {
next[ch][i] = next[ch][i + 1];
}
next[str[i + 1]][i] = i + 1;
}
int ans = (int) 1e9;
final int tagetCnt = set.size();
for (int s = 0; s < n; s++) {
boolean[] used = new boolean[max];
used[str[s]] = true;
int cnt = 1;
int pos = s;
while (cnt < tagetCnt) {
int nextPos = n;
for (int ch = 0; ch < max; ch++) {
if (!used[ch]) {
if (next[ch][pos] == -1) {
continue;
}
nextPos = Math.min(nextPos, next[ch][pos]);
}
}
pos = nextPos;
if (nextPos == n) {
break;
}
++cnt;
used[str[nextPos]] = true;
}
if (pos == n) {
break;
}
ans = Math.min(ans, pos - s + 1);
}
out.printLine(ans);
}
}
static interface IntCollection extends IntStream {
public int size();
default public void add(int value) {
throw new UnsupportedOperationException();
}
default public IntCollection addAll(IntStream values) {
for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) {
add(it.value());
}
return this;
}
}
static interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
public IntIterator intIterator();
default public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private IntIterator it = intIterator();
public boolean hasNext() {
return it.isValid();
}
public Integer next() {
int result = it.value();
it.advance();
return result;
}
};
}
default public int compareTo(IntStream c) {
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
int i = it.value();
int j = jt.value();
if (i < j) {
return -1;
} else if (i > j) {
return 1;
}
it.advance();
jt.advance();
}
if (it.isValid()) {
return 1;
}
if (jt.isValid()) {
return -1;
}
return 0;
}
}
static class IntHashSet extends IntAbstractStream implements IntSet {
private static final Random RND = new Random();
private static final int[] SHIFTS = new int[4];
private static final byte PRESENT_MASK = 1;
private static final byte REMOVED_MASK = 2;
private int size;
private int realSize;
private int[] values;
private byte[] present;
private int step;
private int ratio;
static {
for (int i = 0; i < 4; i++) {
SHIFTS[i] = RND.nextInt(31) + 1;
}
}
public IntHashSet() {
this(3);
}
public IntHashSet(int capacity) {
capacity = Math.max(capacity, 3);
values = new int[capacity];
present = new byte[capacity];
ratio = 2;
initStep(capacity);
}
public IntHashSet(IntCollection c) {
this(c.size());
addAll(c);
}
public IntHashSet(int[] arr) {
this(new IntArray(arr));
}
private void initStep(int capacity) {
step = RND.nextInt(capacity - 2) + 1;
while (IntegerUtils.gcd(step, capacity) != 1) {
step++;
}
}
public IntIterator intIterator() {
return new IntIterator() {
private int position = size == 0 ? values.length : -1;
public int value() throws NoSuchElementException {
if (position == -1) {
advance();
}
if (position >= values.length) {
throw new NoSuchElementException();
}
if ((present[position] & PRESENT_MASK) == 0) {
throw new IllegalStateException();
}
return values[position];
}
public boolean advance() throws NoSuchElementException {
if (position >= values.length) {
throw new NoSuchElementException();
}
position++;
while (position < values.length && (present[position] & PRESENT_MASK) == 0) {
position++;
}
return isValid();
}
public boolean isValid() {
return position < values.length;
}
public void remove() {
if ((present[position] & PRESENT_MASK) == 0) {
throw new IllegalStateException();
}
present[position] = REMOVED_MASK;
}
};
}
public int size() {
return size;
}
public void add(int value) {
ensureCapacity((realSize + 1) * ratio + 2);
int current = getHash(value);
while (present[current] != 0) {
if ((present[current] & PRESENT_MASK) != 0 && values[current] == value) {
return;
}
current += step;
if (current >= values.length) {
current -= values.length;
}
}
while ((present[current] & PRESENT_MASK) != 0) {
current += step;
if (current >= values.length) {
current -= values.length;
}
}
if (present[current] == 0) {
realSize++;
}
present[current] = PRESENT_MASK;
values[current] = value;
size++;
}
private int getHash(int value) {
int hash = IntHash.hash(value);
int result = hash;
for (int i : SHIFTS) {
result ^= hash >> i;
}
result %= values.length;
if (result < 0) {
result += values.length;
}
return result;
}
private void ensureCapacity(int capacity) {
if (values.length < capacity) {
capacity = Math.max(capacity * 2, values.length);
rebuild(capacity);
}
}
private void rebuild(int capacity) {
initStep(capacity);
int[] oldValues = values;
byte[] oldPresent = present;
values = new int[capacity];
present = new byte[capacity];
size = 0;
realSize = 0;
for (int i = 0; i < oldValues.length; i++) {
if ((oldPresent[i] & PRESENT_MASK) == PRESENT_MASK) {
add(oldValues[i]);
}
}
}
}
static interface IntList extends IntReversableCollection {
public abstract int get(int index);
public abstract void addAt(int index, int value);
public abstract void removeAt(int index);
default public IntIterator intIterator() {
return new IntIterator() {
private int at;
private boolean removed;
public int value() {
if (removed) {
throw new IllegalStateException();
}
return get(at);
}
public boolean advance() {
at++;
removed = false;
return isValid();
}
public boolean isValid() {
return !removed && at < size();
}
public void remove() {
removeAt(at);
at--;
removed = true;
}
};
}
default public void add(int value) {
addAt(size(), value);
}
}
static class IntegerUtils {
public static int gcd(int a, int b) {
a = Math.abs(a);
b = Math.abs(b);
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
}
static abstract class IntAbstractStream implements IntStream {
public String toString() {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
if (first) {
first = false;
} else {
builder.append(' ');
}
builder.append(it.value());
}
return builder.toString();
}
public boolean equals(Object o) {
if (!(o instanceof IntStream)) {
return false;
}
IntStream c = (IntStream) o;
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
if (it.value() != jt.value()) {
return false;
}
it.advance();
jt.advance();
}
return !it.isValid() && !jt.isValid();
}
public int hashCode() {
int result = 0;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
result *= 31;
result += it.value();
}
return result;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class IntHash {
private IntHash() {
}
public static int hash(int c) {
return c;
}
}
static interface IntReversableCollection extends IntCollection {
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
static class IntArray extends IntAbstractStream implements IntList {
private int[] data;
public IntArray(int[] arr) {
data = arr;
}
public int size() {
return data.length;
}
public int get(int at) {
return data[at];
}
public void addAt(int index, int value) {
throw new UnsupportedOperationException();
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
}
static interface IntSet extends IntCollection {
}
static class IOUtils {
public static char[] readCharArray(InputReader in, int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = in.readCharacter();
}
return array;
}
}
static interface IntIterator {
public int value() throws NoSuchElementException;
public boolean advance();
public boolean isValid();
}
static class ArrayUtils {
public static void fill(int[][] array, int value) {
for (int[] row : array) {
Arrays.fill(row, value);
}
}
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.util.Scanner;
/**
* Feb 18, 2016 | 4:00:49 PM
* <pre>
* <u>Description</u>
*
* </pre>
*
* @author Essiennta Emmanuel (colourfulemmanuel@gmail.com)
*/
public class ProblemA{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
sc.next();
System.out.println(25);
sc.close();
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) throws Exception {
new A().doit();
}
private void doit() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
long a = Long.parseLong(st.nextToken());
long b = Long.parseLong(st.nextToken());
long ans = 0;
while(a > 0 && b > 0) {
if (a > b) {
ans += a / b;
a %= b;
} else {
ans += b / a;
b %= a;
}
}
System.out.println(ans);
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Solution1 {
private void solve() throws IOException {
long MOD = 1_000_000_007;
long x = in.nextLong();
long k = in.nextLong();
if (x == 0) {
System.out.println(0);
return;
}
long val = binpow(2, k + 1, MOD) % MOD;
long kek = (binpow(2, k, MOD) - 1 + MOD) % MOD;
x = (val % MOD) * (x % MOD) % MOD;
long ans = (x % MOD - kek % MOD + MOD) % MOD;
System.out.println(ans % MOD);
}
private long binpow(long a, long n, long mod) {
long res = 1;
while (n > 0) {
if (n % 2 == 1)
res = (res % mod) * (a % mod) % mod;
a = (a % mod) * (a % mod) % mod;
n >>= 1;
}
return res % mod;
}
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;
public 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;
}
public 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());
}
public void close() throws IOException {
this.br.close();
}
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
new Solution1().run();
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class f {
static int n;
static double[][] g;
public static void main(String[] args) throws IOException {
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
n = input.nextInt();
g = new double[n][n];
for(int i = 0; i<n; i++)
for(int j = 0; j<n; j++)
g[i][j] = input.nextDouble();
for(int i = 0; i<n; i++)
for(int j = 0; j<n; j++)
g[j][i] = 1 - g[i][j];
for(int i = 0; i<n; i++)
{
double[] dp = new double[1<<n];
for(int mask = 0; mask < (1<<n); mask++)
{
if((mask & (1<<i)) == 0)
{
dp[mask] = 0;
continue;
}
if(mask == (1<<i))
{
dp[mask] = 1;
continue;
}
int count = Integer.bitCount(mask);
double prob = 1.0 / (count * (count-1)/2);
for(int a = 0; a<n; a++)
{
if((mask & (1<<a)) == 0) continue;
for(int b = a+1; b<n; b++)
{
if((mask & (1<<b)) == 0) continue;
double p = g[a][b] * dp[mask ^ (1<<b)] + g[b][a] * dp[mask ^ (1<<a)];
dp[mask] += p;
}
}
dp[mask] *= prob;
}
out.print(dp[(1<<n)-1]+" ");
}
out.close();
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
/**
* Created by Baelish on 6/18/2018.
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.InputMismatchException;
public class C_3 {
public static void main(String[] args) throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
long mod = (long) 1e9 + 7;
long xx = in.nextLong(), kk = in.nextLong();
if(xx == 0){
pw.println(0); pw.close();
return;
}
BigInteger x = BigInteger.valueOf(xx), k = BigInteger.valueOf(kk);
// long a = bigMod(2, k+1, mod );long b = bigMod(2, k, mod);
BigInteger MOD = BigInteger.valueOf(mod);
BigInteger a = BigInteger.valueOf(2).modPow(BigInteger.valueOf(kk+1), MOD);
BigInteger b = BigInteger.valueOf(2).modPow(BigInteger.valueOf(kk), MOD);
BigInteger s = (a.multiply(x)).mod(MOD);
s = s.subtract(b.mod(MOD));
s = s.add(BigInteger.ONE);
s = s.mod(MOD);
s = s.add(MOD);
s = s.mod(MOD);
// debug(a, b, x);
// long s = ((a * x) % mod - b % mod + 1 + mod) % mod;
pw.println(s);
pw.close();
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
static final int ints[] = new int[128];
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
public FastReader(InputStream is) {
for (int i = '0'; i <= '9'; i++) ints[i] = i - '0';
this.is = is;
}
public 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++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
public String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + ints[b];
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + ints[b];
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
/* public char nextChar() {
return (char)skip();
}*/
public char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
/*private char buff[] = new char[1005];
public char[] nextCharArray(){
int b = skip(), p = 0;
while(!(isSpaceChar(b))){
buff[p++] = (char)b;
b = readByte();
}
return Arrays.copyOf(buff, p);
}*/
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long itrIdx = 0;
long itr = 0;
long num = 0;
while(itrIdx < n){
itrIdx += (itr+1)*(Math.pow(10,itr+1) - Math.pow(10,itr));
num+= (Math.pow(10,itr+1) - Math.pow(10,itr));
itr++;
}
itrIdx -= itr*(Math.pow(10,itr)-Math.pow(10,itr-1));
num -= (Math.pow(10,itr)-Math.pow(10,itr-1));
long lastNum = num + ((n-itrIdx)/itr);
long lastNumIndex = itrIdx + (itr* (lastNum-num));
if(lastNumIndex == n){
lastNumIndex = lastNumIndex-itr;
lastNum -=1;
}
String nextNum = String.valueOf(lastNum+=1);
System.out.println(nextNum.charAt((int) (n-lastNumIndex-1)));
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
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);
E1RotateColumnsEasyVersion solver = new E1RotateColumnsEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class E1RotateColumnsEasyVersion {
int n;
int m;
int[][] arr;
int[][] mskValue;
int[][] memo;
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int q = sc.nextInt();
while (q-- > 0) {
n = sc.nextInt();
m = sc.nextInt();
arr = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = sc.nextInt();
int[][] temp = new int[m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
temp[i][j] = arr[j][i];
Arrays.sort(temp, (a, b) -> getMax(b) - getMax(a));
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
arr[j][i] = temp[i][j];
mskValue = new int[n][1 << n];
for (int i = 0; i < Math.min(n, m); i++) {
for (int j = 0; j < 1 << n; j++) {
int max = 0;
for (int shift = 0; shift < n; shift++) {
int sum = 0;
for (int k = 0; k < n; k++)
if ((j & 1 << k) != 0)
sum += arr[(k + shift) % n][i];
max = Math.max(max, sum);
}
mskValue[i][j] = max;
}
}
memo = new int[Math.min(n, m)][1 << n];
for (int[] x : memo)
Arrays.fill(x, -1);
pw.println(dp(0, 0));
}
}
private int getMax(int[] a) {
int max = 0;
for (int x : a)
max = Math.max(max, x);
return max;
}
private int dp(int idx, int msk) {
if (msk == (1 << n) - 1)
return 0;
if (idx == Math.min(n, m))
return (int) -1e9;
int max = Integer.MIN_VALUE;
if (memo[idx][msk] != -1)
return memo[idx][msk];
int availableBits = msk ^ ((1 << n) - 1);
for (int colMask = availableBits; colMask != 0; colMask = (colMask - 1) & availableBits) {
max = Math.max(max, mskValue[idx][colMask] + dp(idx + 1, msk | colMask));
}
return memo[idx][msk] = max;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main (String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
String parameterStringList[] = reader.readLine().split(" ");
int x = Integer.parseInt(parameterStringList[0]);
int y = Integer.parseInt(parameterStringList[1]);
int z = Integer.parseInt(parameterStringList[2]);
int t1 = Integer.parseInt(parameterStringList[3]);
int t2 = Integer.parseInt(parameterStringList[4]);
int t3 = Integer.parseInt(parameterStringList[5]);
int T1 = Math.abs(x-y) * t1;
int T2 = Math.abs(x-z) * t2 + 3*t3 + Math.abs(x-y) * t2;
if(T2 <= T1) System.out.println("YES");
else System.out.println("NO");
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
constant
|
1054_A. Elevator or Stairs?
|
CODEFORCES
|
/**
* Codeforces Beta Round #10
*
* @author ProjectYoung
*/
import java.util.Scanner;
public class CF11D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
boolean[][] map = new boolean[n][n];
long[][] dp = new long[1 << n][n];
for (int i = 0; i < m; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
map[a][b] = map[b][a] = true;
dp[(1 << a) + (1 << b)][Math.max(a, b)] = 1;
}
long ans = 0;
for (int mask = 1; mask < (1 << n); mask++) {
int lowbit = 0;
for (; (mask & (1 << lowbit)) == 0; lowbit++);
for (int i = lowbit + 1; i < n; i++) {
if ((mask & (1 << i)) == 0) {
continue;
}
for (int j = lowbit + 1; j < n; j++) {
if ((mask & (1 << j)) == 0 || j == i) {
continue;
}
if (map[i][j]) {
dp[mask][i] += dp[mask ^ (1 << i)][j];
}
}
if (map[lowbit][i]) {
ans += dp[mask][i];
}
}
}
System.out.println((ans - m) / 2);
sc.close();
}
}
|
np
|
11_D. A Simple Task
|
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: Patel Rag
//Java version "1.8.0_211"
import java.util.*;
import java.io.*;
public class Main
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); }
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong(){ return Long.parseLong(next()); }
double nextDouble(){ return Double.parseDouble(next()); }
float nextFloat() { return Float.parseFloat(next()); }
boolean nextBoolean() { return Boolean.parseBoolean(next()); }
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long modExp(long x, long n, long mod) //binary Modular exponentiation
{
long result = 1;
while(n > 0)
{
if(n % 2 == 1)
result = (result%mod * x%mod)%mod;
x = (x%mod * x%mod)%mod;
n=n/2;
}
return result;
}
static long gcd(long a, long b)
{
if(a==0) return b;
return gcd(b%a,a);
}
public static void main(String[] args)
throws IOException
{
FastReader fr = new FastReader();
int n = fr.nextInt();
int q = fr.nextInt();
long[] a = new long[n];
long[] k = new long[q];
for(int i = 0; i < n; i++) a[i] = fr.nextLong();
for(int i = 0; i < q; i++) k[i] = fr.nextLong();
long[] pre = new long[n];
pre[0] = a[0];
for(int i = 1; i < n; i++) pre[i] = pre[i-1] + a[i];
long pd = 0;
for(int i = 0; i < q; i++)
{
int l = 0;
int r = n - 1;
while(r > l)
{
int mid = (l + r) >> 1;
if(pre[mid] - pd < k[i])
{
l = mid + 1;
}
else if(pre[mid] - pd > k[i])
{
r = mid - 1;
}
else
{
l = r = mid;
}
}
int ans = 0;
if(pre[l] - pd <= k[i])
{
ans = n - l - 1;
}
else
{
ans = n - l;
}
if(ans == 0) ans = n;
pd = pd + k[i];
if(pd >= pre[n-1]) pd = 0;
System.out.println(ans);
}
}
}
class pair
{
public int first;
public int second;
public pair(int first,int second)
{
this.first = first;
this.second = second;
}
public pair(pair p)
{
this.first = p.first;
this.second = p.second;
}
public int first() { return first; }
public int second() { return second; }
public void setFirst(int first) { this.first = first; }
public void setSecond(int second) { this.second = second; }
}
class myComp implements Comparator<pair>
{
public int compare(pair a,pair b)
{
if(a.first != b.first) return (a.first - b.first);
return (b.second - a.second);
}
}
class BIT //Binary Indexed Tree aka Fenwick Tree
{
public long[] m_array;
public BIT(long[] dat)
{
m_array = new long[dat.length + 1];
Arrays.fill(m_array,0);
for(int i = 0; i < dat.length; i++)
{
m_array[i + 1] = dat[i];
}
for(int i = 1; i < m_array.length; i++)
{
int j = i + (i & -i);
if(j < m_array.length)
{
m_array[j] = m_array[j] + m_array[i];
}
}
}
public final long prefix_query(int i)
{
long result = 0;
for(++i; i > 0; i = i - (i & -i))
{
result = result + m_array[i];
}
return result;
}
public final long range_query(int fro, int to)
{
if(fro == 0)
{
return prefix_query(to);
}
else
{
return (prefix_query(to) - prefix_query(fro - 1));
}
}
public void update(int i, long add)
{
for(++i; i < m_array.length; i = i + (i & -i))
{
m_array[i] = m_array[i] + add;
}
}
}
|
nlogn
|
975_C. Valhalla Siege
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class cf908G {
final static int MOD = 1_000_000_007;
public static void main(String[] argv) {
cf908G pro = new cf908G();
InputStream fin = null;
if (System.getProperty("ONLINE_JUDGE") == null) {
try {
fin = new FileInputStream("input.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
fin = System.in;
}
pro.solve(new Scanner(fin), System.out);
}
private void solve(Scanner scanner, PrintStream out) {
long ans = 0;
String X = scanner.next();
for (int x = 0; x < 9; x++) {
ans = (ans + solve2(x, X)) % MOD;
}
out.println((ans % MOD + MOD) % MOD);
}
private long solve2(int x, String X) {
int[][][] f = new int[X.length() + 1][X.length() + 1][2];
f[0][0][1] = 1;
int n = X.length();
for (int i = 0; i < n; i++) {
for (int j = 0; j <= n; j++) {
for (int u = 0; u < 2; u++) {
int val = f[i][j][u];
if (val == 0) continue;
for (int num = 0; num < 10; num++) {
int Xi = X.charAt(i) - '0';
if (u == 1 && num > Xi) break;
int _i = i + 1;
int _j = num <= x ? j + 1 : j;
int _u = u == 1 && num == Xi ? 1 : 0;
f[_i][_j][_u] = (f[_i][_j][_u] + val) % MOD;
}
}
}
}
long base = 1;
long ret = 0;
for (int i = n; i > 0; i--) {
long t = 0;
for (int j = 0; j < i; j++) {
t = (t + f[n][j][0] + f[n][j][1]) % MOD;
}
ret = (ret + base * t) % MOD;
base = (base * 10) % MOD;
}
return ret;
}
}
|
quadratic
|
908_G. New Year and Original Order
|
CODEFORCES
|
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 19:12:30 30/05/2021
Custom Competitive programming helper.
*/
public class Main {
public static void solve() {
int n = in.nextInt();
ArrayList<Integer> ans = new ArrayList<>();
out.println(in.nextInt());
ans.add(1);
for(int i = 0; i<n-1; i++) {
int cur = in.nextInt();
if(ans.isEmpty() || cur==1) ans.add(cur);
else {
while((!ans.isEmpty()) && (ans.get(ans.size()-1)+1!=cur)) ans.remove(ans.size()-1);
if(!ans.isEmpty()) ans.remove(ans.size()-1);
ans.add(cur);
}
int cnt = 0;
for(int j : ans) {
cnt++;
out.print(j+(cnt==ans.size()?"":"."));
}
out.println();
}
}
static boolean equal(ArrayList<Integer> a, ArrayList<Integer> b) {
if(a.size()!=b.size()) return false;
for(int i = 0; i<a.size(); i++) if(a.get(i)!=b.get(i)) return false;
return true;
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = in.nextInt();
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
this.br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util{
private static Random random = new Random();
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted doesn't exist
long x = gcdE[1];
return (x % MOD + MOD) % MOD;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
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;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i*i <= n; i++) if (isPrime[i])
for (int j = i; i*j <= n; j++) isPrime[i*j] = false;
return isPrime;
}
public static int gcd(int a, int b) {
int tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max-min+1)+min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
int tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(long[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
long tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(float[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
float tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(double[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
double tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(char[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
char tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length-1);
}
public static <T> void reverse(T[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
T tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length-1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
// author @mdazmat9
public class codeforces{
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int test = 1;
for (int ind = 0; ind < test; ind++) {
int [] a=new int[3];
a[0]=sc.nextInt();
a[1]=sc.nextInt();
a[2]=sc.nextInt();
Arrays.sort(a);
int k1=a[0];
int k2=a[1];
int k3=a[2];
if(k1==1 || k2==1 || k3==1){
out.println("YES");
}
else if((k1==2 && k2==2)||(k2==2 && k3==2)){
out.println("YES");
}
else if(k1==3 && k2==3 && k3==3){
out.println("YES");
}
else if(k1==2 && k2==4 && k3==4){
out.println("YES");
}
else
out.println("NO");
}
out.flush();
}
static void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
static long gcd(long a , long b)
{
if(b == 0)
return a;
return gcd(b , a % b);
}
}
class Scanner {
public BufferedReader reader;
public StringTokenizer st;
public Scanner(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 long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
class OutputWriter {
BufferedWriter writer;
public OutputWriter(OutputStream stream) {
writer = new BufferedWriter(new OutputStreamWriter(stream));
}
public void print(int i) throws IOException {
writer.write(i);
}
public void print(String s) throws IOException {
writer.write(s);
}
public void print(char[] c) throws IOException {
writer.write(c);
}
public void close() throws IOException {
writer.close();
}
}
|
constant
|
911_C. Three Garlands
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
String nextLine() throws IOException {
return br.readLine();
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
float nextFloat() {
return Float.parseFloat(nextToken());
}
}
static FastReader f = new FastReader();
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static StringBuilder sb = new StringBuilder();
static long[] fact;
static int[] inputArray(int n) throws IOException {
int[] a = new int[n];
for(int i = 0 ; i < n ; i++) {
// a[i] = (int) (Math.random()*1e5 + 1);
a[i] = f.nextInt();
}
return a;
}
static long[] inputLongArray(int n) throws IOException {
long[] a = new long[n];
for(int i = 0 ; i < n ; i++) {
a[i] = f.nextLong();
// a[i] = (long) (Math.random() * 1e9 + 1);
}
return a;
}
static long gcd(long a , long b) {
if(a == 0 || b == 0) {
return Math.max(a , b);
}
//System.out.println("a - " + a + " b - " + b);
if(a % b == 0) {
return b;
}
return gcd(b , a % b);
}
static void initializeFact() {
fact = new long[MAX_N];
for(int i = 0 ; i < fact.length ; i++) {
if(i == 0) {
fact[i] = 1;
}
else {
fact[i] = fact[i-1] * i % mod;
}
}
}
static long longModulus(long x , long m) {
if(x < m) {
return x;
}
long d = x / m;
return x - d * m;
}
static BitSet sieveOfEratosthenes(int n)
{
BitSet isPrime = new BitSet(n+1);
isPrime.set(0, n + 1);
isPrime.set(0);
isPrime.set(1);
for(int i = 2; i * i <= n ; i++)
{
if(isPrime.get(i))
for(int j = i * i ; j <= n; j += i)
isPrime.clear(j);
}
return isPrime;
}
static long moduloInversePrime(long a) {
//System.out.println("modulo inverse of " + a + " -> " + ans);
return modPow(a , mod - 2);
}
static long mult(long a, long b)
{
return (a * b % mod);
}
static long modPow(long a, int step)
{
long ans = 1;
while(step != 0)
{
if((step & 1) != 0)
ans = mult(ans , a);
a = mult(a , a);
step >>= 1;
}
return ans;
}
static int query(int l , int r) {
System.out.println("? " + l + " " + r);
System.out.flush();
return f.nextInt();
}
static int sum(int n) {
return n * (n + 1) / 2;
}
private static final int mod = (int) (1e9 + 7);
static int MAX_N = (int) Math.sqrt(1e9);
public static void main(String[] args) throws IOException {
int test = f.nextInt();
// System.out.println(MAX_N);
TreeSet<Integer> set = new TreeSet<>();
for(int i = 1 ; i <= MAX_N ; i++) {
set.add(i*i*2);
set.add(i*i*4);
}
// System.out.println(set);
for(int t = 1 ; t <= test ; t++) {
int n = f.nextInt();
if(set.contains(n)) {
sb.append("YES").append("\n");
}
else {
sb.append("NO").append("\n");
}
}
System.out.println(sb);
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class MainG {
static StdIn in = new StdIn();
static PrintWriter out = new PrintWriter(System.out);
static long M=(long)1e9+7;
public static void main(String[] args) {
char[] cs = in.next().toCharArray();
int n=cs.length;
int[] x = new int[n];
for(int i=0; i<n; ++i)
x[i]=cs[i]-'0';
long[] dp1 = new long[n+1];
for(int i=0; i<n; ++i)
dp1[i+1]=(x[i]+dp1[i]*10)%M;
long ans=0;
for(int d1=1; d1<=9; ++d1) {
long[][] dp2 = new long[2][n+1];
for(int i=0; i<n; ++i) {
dp2[0][i+1]=x[i]>=d1?(10*dp2[0][i]+1)%M:dp2[0][i];
for(int d2=0; d2<x[i]; ++d2)
dp2[1][i+1]=((d2>=d1?10*(dp2[0][i]+dp2[1][i])+dp1[i]+1:dp2[0][i]+dp2[1][i])+dp2[1][i+1])%M;
for(int d2=x[i]; d2<=9; ++d2)
dp2[1][i+1]=((d2>=d1?10*dp2[1][i]+dp1[i]:dp2[1][i])+dp2[1][i+1])%M;
}
ans+=dp2[0][n]+dp2[1][n];
}
out.println(ans%M);
out.close();
}
interface Input {
public String next();
public String nextLine();
public int nextInt();
public long nextLong();
public double nextDouble();
}
static class StdIn implements Input {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public StdIn() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public StdIn(InputStream in) {
try{
din = new DataInputStream(in);
} catch(Exception e) {
throw new RuntimeException();
}
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == ' ' || c == '\n'||c=='\r')
break;
s.append((char)c);
c=read();
}
return s.toString();
}
public String nextLine() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == '\n'||c=='\r')
break;
s.append((char)c);
c = read();
}
return s.toString();
}
public int nextInt() {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int n) {
int[] ar = new int[n];
for(int i=0; i<n; ++i)
ar[i]=nextInt();
return ar;
}
public long nextLong() {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long[] readLongArray(int n) {
long[] ar = new long[n];
for(int i=0; i<n; ++i)
ar[i]=nextLong();
return ar;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() {
try{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
} catch(IOException e) {
throw new RuntimeException();
}
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
}
|
quadratic
|
908_G. New Year and Original Order
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class C_455
{
public static final long[] POWER2 = generatePOWER2();
public static final IteratorBuffer<Long> ITERATOR_BUFFER_PRIME = new IteratorBuffer<>(streamPrime(1000000).iterator());
private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer stringTokenizer = null;
private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static class Array<Type> implements Iterable<Type>
{
private final Object[] array;
public Array(int size)
{
this.array = new Object[size];
}
public Array(int size, Type element)
{
this(size);
Arrays.fill(this.array, element);
}
public Array(Array<Type> array, Type element)
{
this(array.size() + 1);
for (int index = 0; index < array.size(); index++)
{
set(index, array.get(index));
}
set(size() - 1, element);
}
public Array(List<Type> list)
{
this(list.size());
int index = 0;
for (Type element : list)
{
set(index, element);
index += 1;
}
}
public Type get(int index)
{
return (Type) this.array[index];
}
@Override
public Iterator<Type> iterator()
{
return new Iterator<Type>()
{
int index = 0;
@Override
public boolean hasNext()
{
return this.index < size();
}
@Override
public Type next()
{
Type result = Array.this.get(index);
index += 1;
return result;
}
};
}
public Array set(int index, Type value)
{
this.array[index] = value;
return this;
}
public int size()
{
return this.array.length;
}
public List<Type> toList()
{
List<Type> result = new ArrayList<>();
for (Type element : this)
{
result.add(element);
}
return result;
}
@Override
public String toString()
{
return "[" + C_455.toString(this, ", ") + "]";
}
}
static class BIT
{
private static int lastBit(int index)
{
return index & -index;
}
private final long[] tree;
public BIT(int size)
{
this.tree = new long[size];
}
public void add(int index, long delta)
{
index += 1;
while (index <= this.tree.length)
{
tree[index - 1] += delta;
index += lastBit(index);
}
}
public long prefix(int end)
{
long result = 0;
while (end > 0)
{
result += this.tree[end - 1];
end -= lastBit(end);
}
return result;
}
public int size()
{
return this.tree.length;
}
public long sum(int start, int end)
{
return prefix(end) - prefix(start);
}
}
static abstract class Edge<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>>
{
public final TypeVertex vertex0;
public final TypeVertex vertex1;
public final boolean bidirectional;
public Edge(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
{
this.vertex0 = vertex0;
this.vertex1 = vertex1;
this.bidirectional = bidirectional;
this.vertex0.edges.add(getThis());
if (this.bidirectional)
{
this.vertex1.edges.add(getThis());
}
}
public abstract TypeEdge getThis();
public TypeVertex other(Vertex<TypeVertex, TypeEdge> vertex)
{
TypeVertex result;
if (vertex0 == vertex)
{
result = vertex1;
}
else
{
result = vertex0;
}
return result;
}
public void remove()
{
this.vertex0.edges.remove(getThis());
if (this.bidirectional)
{
this.vertex1.edges.remove(getThis());
}
}
@Override
public String toString()
{
return this.vertex0 + "->" + this.vertex1;
}
}
public static class EdgeDefault<TypeVertex extends Vertex<TypeVertex, EdgeDefault<TypeVertex>>> extends Edge<TypeVertex, EdgeDefault<TypeVertex>>
{
public EdgeDefault(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
{
super(vertex0, vertex1, bidirectional);
}
@Override
public EdgeDefault<TypeVertex> getThis()
{
return this;
}
}
public static class EdgeDefaultDefault extends Edge<VertexDefaultDefault, EdgeDefaultDefault>
{
public EdgeDefaultDefault(VertexDefaultDefault vertex0, VertexDefaultDefault vertex1, boolean bidirectional)
{
super(vertex0, vertex1, bidirectional);
}
@Override
public EdgeDefaultDefault getThis()
{
return this;
}
}
public static class FIFO<Type>
{
public SingleLinkedList<Type> start;
public SingleLinkedList<Type> end;
public FIFO()
{
this.start = null;
this.end = null;
}
public boolean isEmpty()
{
return this.start == null;
}
public Type peek()
{
return this.start.element;
}
public Type pop()
{
Type result = this.start.element;
this.start = this.start.next;
return result;
}
public void push(Type element)
{
SingleLinkedList<Type> list = new SingleLinkedList<>(element, null);
if (this.start == null)
{
this.start = list;
this.end = list;
}
else
{
this.end.next = list;
this.end = list;
}
}
}
static class Fraction implements Comparable<Fraction>
{
public static final Fraction ZERO = new Fraction(0, 1);
public static Fraction fraction(long whole)
{
return fraction(whole, 1);
}
public static Fraction fraction(long numerator, long denominator)
{
Fraction result;
if (denominator == 0)
{
throw new ArithmeticException();
}
if (numerator == 0)
{
result = Fraction.ZERO;
}
else
{
int sign;
if (numerator < 0 ^ denominator < 0)
{
sign = -1;
numerator = Math.abs(numerator);
denominator = Math.abs(denominator);
}
else
{
sign = 1;
}
long gcd = gcd(numerator, denominator);
result = new Fraction(sign * numerator / gcd, denominator / gcd);
}
return result;
}
public final long numerator;
public final long denominator;
private Fraction(long numerator, long denominator)
{
this.numerator = numerator;
this.denominator = denominator;
}
public Fraction add(Fraction fraction)
{
return fraction(this.numerator * fraction.denominator + fraction.numerator * this.denominator, this.denominator * fraction.denominator);
}
@Override
public int compareTo(Fraction that)
{
return Long.compare(this.numerator * that.denominator, that.numerator * this.denominator);
}
public Fraction divide(Fraction fraction)
{
return multiply(fraction.inverse());
}
public boolean equals(Fraction that)
{
return this.compareTo(that) == 0;
}
public boolean equals(Object that)
{
return this.compareTo((Fraction) that) == 0;
}
public Fraction getRemainder()
{
return fraction(this.numerator - getWholePart() * denominator, denominator);
}
public long getWholePart()
{
return this.numerator / this.denominator;
}
public Fraction inverse()
{
return fraction(this.denominator, this.numerator);
}
public Fraction multiply(Fraction fraction)
{
return fraction(this.numerator * fraction.numerator, this.denominator * fraction.denominator);
}
public Fraction neg()
{
return fraction(-this.numerator, this.denominator);
}
public Fraction sub(Fraction fraction)
{
return add(fraction.neg());
}
@Override
public String toString()
{
String result;
if (getRemainder().equals(Fraction.ZERO))
{
result = "" + this.numerator;
}
else
{
result = this.numerator + "/" + this.denominator;
}
return result;
}
}
static class IteratorBuffer<Type>
{
private Iterator<Type> iterator;
private List<Type> list;
public IteratorBuffer(Iterator<Type> iterator)
{
this.iterator = iterator;
this.list = new ArrayList<Type>();
}
public Iterator<Type> iterator()
{
return new Iterator<Type>()
{
int index = 0;
@Override
public boolean hasNext()
{
return this.index < list.size() || IteratorBuffer.this.iterator.hasNext();
}
@Override
public Type next()
{
if (list.size() <= this.index)
{
list.add(iterator.next());
}
Type result = list.get(index);
index += 1;
return result;
}
};
}
}
public static class MapCount<Type> extends SortedMapAVL<Type, Long>
{
private int count;
public MapCount(Comparator<? super Type> comparator)
{
super(comparator);
this.count = 0;
}
public long add(Type key, Long delta)
{
long result;
if (delta > 0)
{
Long value = get(key);
if (value == null)
{
value = delta;
}
else
{
value += delta;
}
put(key, value);
result = delta;
}
else
{
result = 0;
}
this.count += result;
return result;
}
public int count()
{
return this.count;
}
public List<Type> flatten()
{
List<Type> result = new ArrayList<>();
for (Entry<Type, Long> entry : entrySet())
{
for (long index = 0; index < entry.getValue(); index++)
{
result.add(entry.getKey());
}
}
return result;
}
@Override
public SortedMapAVL<Type, Long> headMap(Type keyEnd)
{
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map<? extends Type, ? extends Long> map)
{
throw new UnsupportedOperationException();
}
public long remove(Type key, Long delta)
{
long result;
if (delta > 0)
{
Long value = get(key) - delta;
if (value <= 0)
{
result = delta + value;
remove(key);
}
else
{
result = delta;
put(key, value);
}
}
else
{
result = 0;
}
this.count -= result;
return result;
}
@Override
public Long remove(Object key)
{
Long result = super.remove(key);
this.count -= result;
return result;
}
@Override
public SortedMapAVL<Type, Long> subMap(Type keyStart, Type keyEnd)
{
throw new UnsupportedOperationException();
}
@Override
public SortedMapAVL<Type, Long> tailMap(Type keyStart)
{
throw new UnsupportedOperationException();
}
}
public static class MapSet<TypeKey, TypeValue> extends SortedMapAVL<TypeKey, SortedSetAVL<TypeValue>> implements Iterable<TypeValue>
{
private Comparator<? super TypeValue> comparatorValue;
public MapSet(Comparator<? super TypeKey> comparatorKey, Comparator<? super TypeValue> comparatorValue)
{
super(comparatorKey);
this.comparatorValue = comparatorValue;
}
public MapSet(Comparator<? super TypeKey> comparatorKey, SortedSetAVL<Entry<TypeKey, SortedSetAVL<TypeValue>>> entrySet, Comparator<? super TypeValue> comparatorValue)
{
super(comparatorKey, entrySet);
this.comparatorValue = comparatorValue;
}
public boolean add(TypeKey key, TypeValue value)
{
SortedSetAVL<TypeValue> set = computeIfAbsent(key, k -> new SortedSetAVL<>(comparatorValue));
return set.add(value);
}
public TypeValue firstValue()
{
TypeValue result;
Entry<TypeKey, SortedSetAVL<TypeValue>> firstEntry = firstEntry();
if (firstEntry == null)
{
result = null;
}
else
{
result = firstEntry.getValue().first();
}
return result;
}
@Override
public MapSet<TypeKey, TypeValue> headMap(TypeKey keyEnd)
{
return new MapSet<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)), this.comparatorValue);
}
public Iterator<TypeValue> iterator()
{
return new Iterator<TypeValue>()
{
Iterator<SortedSetAVL<TypeValue>> iteratorValues = values().iterator();
Iterator<TypeValue> iteratorValue = null;
@Override
public boolean hasNext()
{
return iteratorValues.hasNext() || (iteratorValue != null && iteratorValue.hasNext());
}
@Override
public TypeValue next()
{
if (iteratorValue == null || !iteratorValue.hasNext())
{
iteratorValue = iteratorValues.next().iterator();
}
return iteratorValue.next();
}
};
}
public TypeValue lastValue()
{
TypeValue result;
Entry<TypeKey, SortedSetAVL<TypeValue>> lastEntry = lastEntry();
if (lastEntry == null)
{
result = null;
}
else
{
result = lastEntry.getValue().last();
}
return result;
}
public boolean removeSet(TypeKey key, TypeValue value)
{
boolean result;
SortedSetAVL<TypeValue> set = get(key);
if (set == null)
{
result = false;
}
else
{
result = set.remove(value);
if (set.size() == 0)
{
remove(key);
}
}
return result;
}
@Override
public MapSet<TypeKey, TypeValue> tailMap(TypeKey keyStart)
{
return new MapSet<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)), this.comparatorValue);
}
}
public static class Matrix
{
public final int rows;
public final int columns;
public final Fraction[][] cells;
public Matrix(int rows, int columns)
{
this.rows = rows;
this.columns = columns;
this.cells = new Fraction[rows][columns];
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
set(row, column, Fraction.ZERO);
}
}
}
public void add(int rowSource, int rowTarget, Fraction fraction)
{
for (int column = 0; column < columns; column++)
{
this.cells[rowTarget][column] = this.cells[rowTarget][column].add(this.cells[rowSource][column].multiply(fraction));
}
}
private int columnPivot(int row)
{
int result = this.columns;
for (int column = this.columns - 1; 0 <= column; column--)
{
if (this.cells[row][column].compareTo(Fraction.ZERO) != 0)
{
result = column;
}
}
return result;
}
public void reduce()
{
for (int rowMinimum = 0; rowMinimum < this.rows; rowMinimum++)
{
int rowPivot = rowPivot(rowMinimum);
if (rowPivot != -1)
{
int columnPivot = columnPivot(rowPivot);
Fraction current = this.cells[rowMinimum][columnPivot];
Fraction pivot = this.cells[rowPivot][columnPivot];
Fraction fraction = pivot.inverse().sub(current.divide(pivot));
add(rowPivot, rowMinimum, fraction);
for (int row = rowMinimum + 1; row < this.rows; row++)
{
if (columnPivot(row) == columnPivot)
{
add(rowMinimum, row, this.cells[row][columnPivot(row)].neg());
}
}
}
}
}
private int rowPivot(int rowMinimum)
{
int result = -1;
int pivotColumnMinimum = this.columns;
for (int row = rowMinimum; row < this.rows; row++)
{
int pivotColumn = columnPivot(row);
if (pivotColumn < pivotColumnMinimum)
{
result = row;
pivotColumnMinimum = pivotColumn;
}
}
return result;
}
public void set(int row, int column, Fraction value)
{
this.cells[row][column] = value;
}
public String toString()
{
String result = "";
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
result += this.cells[row][column] + "\t";
}
result += "\n";
}
return result;
}
}
public static class Node<Type>
{
public static <Type> Node<Type> balance(Node<Type> result)
{
while (result != null && 1 < Math.abs(height(result.left) - height(result.right)))
{
if (height(result.left) < height(result.right))
{
Node<Type> right = result.right;
if (height(right.right) < height(right.left))
{
result = new Node<>(result.value, result.left, right.rotateRight());
}
result = result.rotateLeft();
}
else
{
Node<Type> left = result.left;
if (height(left.left) < height(left.right))
{
result = new Node<>(result.value, left.rotateLeft(), result.right);
}
result = result.rotateRight();
}
}
return result;
}
public static <Type> Node<Type> clone(Node<Type> result)
{
if (result != null)
{
result = new Node<>(result.value, clone(result.left), clone(result.right));
}
return result;
}
public static <Type> Node<Type> delete(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
if (node.left == null)
{
result = node.right;
}
else
{
if (node.right == null)
{
result = node.left;
}
else
{
Node<Type> first = first(node.right);
result = new Node<>(first.value, node.left, delete(node.right, first.value, comparator));
}
}
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, delete(node.left, value, comparator), node.right);
}
else
{
result = new Node<>(node.value, node.left, delete(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static <Type> Node<Type> first(Node<Type> result)
{
while (result.left != null)
{
result = result.left;
}
return result;
}
public static <Type> Node<Type> get(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = node;
}
else
{
if (compare < 0)
{
result = get(node.left, value, comparator);
}
else
{
result = get(node.right, value, comparator);
}
}
}
return result;
}
public static <Type> Node<Type> head(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = node.left;
}
else
{
if (compare < 0)
{
result = head(node.left, value, comparator);
}
else
{
result = new Node<>(node.value, node.left, head(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static int height(Node node)
{
return node == null ? 0 : node.height;
}
public static <Type> Node<Type> insert(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = new Node<>(value, null, null);
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = new Node<>(value, node.left, node.right);
;
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, insert(node.left, value, comparator), node.right);
}
else
{
result = new Node<>(node.value, node.left, insert(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static <Type> Node<Type> last(Node<Type> result)
{
while (result.right != null)
{
result = result.right;
}
return result;
}
public static int size(Node node)
{
return node == null ? 0 : node.size;
}
public static <Type> Node<Type> tail(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = new Node<>(node.value, null, node.right);
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, tail(node.left, value, comparator), node.right);
}
else
{
result = tail(node.right, value, comparator);
}
}
result = balance(result);
}
return result;
}
public static <Type> void traverseOrderIn(Node<Type> node, Consumer<Type> consumer)
{
if (node != null)
{
traverseOrderIn(node.left, consumer);
consumer.accept(node.value);
traverseOrderIn(node.right, consumer);
}
}
public final Type value;
public final Node<Type> left;
public final Node<Type> right;
public final int size;
private final int height;
public Node(Type value, Node<Type> left, Node<Type> right)
{
this.value = value;
this.left = left;
this.right = right;
this.size = 1 + size(left) + size(right);
this.height = 1 + Math.max(height(left), height(right));
}
public Node<Type> rotateLeft()
{
Node<Type> left = new Node<>(this.value, this.left, this.right.left);
return new Node<>(this.right.value, left, this.right.right);
}
public Node<Type> rotateRight()
{
Node<Type> right = new Node<>(this.value, this.left.right, this.right);
return new Node<>(this.left.value, this.left.left, right);
}
}
public static class SingleLinkedList<Type>
{
public final Type element;
public SingleLinkedList<Type> next;
public SingleLinkedList(Type element, SingleLinkedList<Type> next)
{
this.element = element;
this.next = next;
}
public void toCollection(Collection<Type> collection)
{
if (this.next != null)
{
this.next.toCollection(collection);
}
collection.add(this.element);
}
}
public static class SmallSetIntegers
{
public static final int SIZE = 20;
public static final int[] SET = generateSet();
public static final int[] COUNT = generateCount();
public static final int[] INTEGER = generateInteger();
private static int count(int set)
{
int result = 0;
for (int integer = 0; integer < SIZE; integer++)
{
if (0 < (set & set(integer)))
{
result += 1;
}
}
return result;
}
private static final int[] generateCount()
{
int[] result = new int[1 << SIZE];
for (int set = 0; set < result.length; set++)
{
result[set] = count(set);
}
return result;
}
private static final int[] generateInteger()
{
int[] result = new int[1 << SIZE];
Arrays.fill(result, -1);
for (int integer = 0; integer < SIZE; integer++)
{
result[SET[integer]] = integer;
}
return result;
}
private static final int[] generateSet()
{
int[] result = new int[SIZE];
for (int integer = 0; integer < result.length; integer++)
{
result[integer] = set(integer);
}
return result;
}
private static int set(int integer)
{
return 1 << integer;
}
}
public static class SortedMapAVL<TypeKey, TypeValue> implements SortedMap<TypeKey, TypeValue>
{
public final Comparator<? super TypeKey> comparator;
public final SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet;
public SortedMapAVL(Comparator<? super TypeKey> comparator)
{
this(comparator, new SortedSetAVL<>((entry0, entry1) -> comparator.compare(entry0.getKey(), entry1.getKey())));
}
private SortedMapAVL(Comparator<? super TypeKey> comparator, SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet)
{
this.comparator = comparator;
this.entrySet = entrySet;
}
@Override
public void clear()
{
this.entrySet.clear();
}
@Override
public Comparator<? super TypeKey> comparator()
{
return this.comparator;
}
@Override
public boolean containsKey(Object key)
{
return this.entrySet().contains(new AbstractMap.SimpleEntry<>((TypeKey) key, null));
}
@Override
public boolean containsValue(Object value)
{
throw new UnsupportedOperationException();
}
@Override
public SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet()
{
return this.entrySet;
}
public Entry<TypeKey, TypeValue> firstEntry()
{
return this.entrySet.first();
}
@Override
public TypeKey firstKey()
{
return firstEntry().getKey();
}
@Override
public TypeValue get(Object key)
{
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
entry = this.entrySet.get(entry);
return entry == null ? null : entry.getValue();
}
@Override
public SortedMapAVL<TypeKey, TypeValue> headMap(TypeKey keyEnd)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)));
}
@Override
public boolean isEmpty()
{
return this.entrySet.isEmpty();
}
@Override
public Set<TypeKey> keySet()
{
return new SortedSet<TypeKey>()
{
@Override
public boolean add(TypeKey typeKey)
{
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends TypeKey> collection)
{
throw new UnsupportedOperationException();
}
@Override
public void clear()
{
throw new UnsupportedOperationException();
}
@Override
public Comparator<? super TypeKey> comparator()
{
throw new UnsupportedOperationException();
}
@Override
public boolean contains(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public TypeKey first()
{
throw new UnsupportedOperationException();
}
@Override
public SortedSet<TypeKey> headSet(TypeKey typeKey)
{
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty()
{
return size() == 0;
}
@Override
public Iterator<TypeKey> iterator()
{
final Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator();
return new Iterator<TypeKey>()
{
@Override
public boolean hasNext()
{
return iterator.hasNext();
}
@Override
public TypeKey next()
{
return iterator.next().getKey();
}
};
}
@Override
public TypeKey last()
{
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public int size()
{
return SortedMapAVL.this.entrySet.size();
}
@Override
public SortedSet<TypeKey> subSet(TypeKey typeKey, TypeKey e1)
{
throw new UnsupportedOperationException();
}
@Override
public SortedSet<TypeKey> tailSet(TypeKey typeKey)
{
throw new UnsupportedOperationException();
}
@Override
public Object[] toArray()
{
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] ts)
{
throw new UnsupportedOperationException();
}
};
}
public Entry<TypeKey, TypeValue> lastEntry()
{
return this.entrySet.last();
}
@Override
public TypeKey lastKey()
{
return lastEntry().getKey();
}
@Override
public TypeValue put(TypeKey key, TypeValue value)
{
TypeValue result = get(key);
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>(key, value);
this.entrySet().add(entry);
return result;
}
@Override
public void putAll(Map<? extends TypeKey, ? extends TypeValue> map)
{
map.entrySet()
.forEach(entry -> put(entry.getKey(), entry.getValue()));
}
@Override
public TypeValue remove(Object key)
{
TypeValue result = get(key);
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
this.entrySet.remove(entry);
return result;
}
@Override
public int size()
{
return this.entrySet().size();
}
@Override
public SortedMapAVL<TypeKey, TypeValue> subMap(TypeKey keyStart, TypeKey keyEnd)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.subSet(new AbstractMap.SimpleEntry<>(keyStart, null), new AbstractMap.SimpleEntry<>(keyEnd, null)));
}
@Override
public SortedMapAVL<TypeKey, TypeValue> tailMap(TypeKey keyStart)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)));
}
@Override
public String toString()
{
return this.entrySet().toString();
}
@Override
public Collection<TypeValue> values()
{
return new Collection<TypeValue>()
{
@Override
public boolean add(TypeValue typeValue)
{
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends TypeValue> collection)
{
throw new UnsupportedOperationException();
}
@Override
public void clear()
{
throw new UnsupportedOperationException();
}
@Override
public boolean contains(Object value)
{
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty()
{
return SortedMapAVL.this.entrySet.isEmpty();
}
@Override
public Iterator<TypeValue> iterator()
{
return new Iterator<TypeValue>()
{
Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator();
@Override
public boolean hasNext()
{
return this.iterator.hasNext();
}
@Override
public TypeValue next()
{
return this.iterator.next().getValue();
}
};
}
@Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public int size()
{
return SortedMapAVL.this.entrySet.size();
}
@Override
public Object[] toArray()
{
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] ts)
{
throw new UnsupportedOperationException();
}
};
}
}
public static class SortedSetAVL<Type> implements SortedSet<Type>
{
public Comparator<? super Type> comparator;
public Node<Type> root;
private SortedSetAVL(Comparator<? super Type> comparator, Node<Type> root)
{
this.comparator = comparator;
this.root = root;
}
public SortedSetAVL(Comparator<? super Type> comparator)
{
this(comparator, null);
}
public SortedSetAVL(Collection<? extends Type> collection, Comparator<? super Type> comparator)
{
this(comparator, null);
this.addAll(collection);
}
public SortedSetAVL(SortedSetAVL<Type> sortedSetAVL)
{
this(sortedSetAVL.comparator, Node.clone(sortedSetAVL.root));
}
@Override
public boolean add(Type value)
{
int sizeBefore = size();
this.root = Node.insert(this.root, value, this.comparator);
return sizeBefore != size();
}
@Override
public boolean addAll(Collection<? extends Type> collection)
{
return collection.stream()
.map(this::add)
.reduce(true, (x, y) -> x | y);
}
@Override
public void clear()
{
this.root = null;
}
@Override
public Comparator<? super Type> comparator()
{
return this.comparator;
}
@Override
public boolean contains(Object value)
{
return Node.get(this.root, (Type) value, this.comparator) != null;
}
@Override
public boolean containsAll(Collection<?> collection)
{
return collection.stream()
.allMatch(this::contains);
}
@Override
public Type first()
{
return Node.first(this.root).value;
}
public Type get(Type value)
{
Node<Type> node = Node.get(this.root, value, this.comparator);
return node == null ? null : node.value;
}
@Override
public SortedSetAVL<Type> headSet(Type valueEnd)
{
return new SortedSetAVL<>(this.comparator, Node.head(this.root, valueEnd, this.comparator));
}
@Override
public boolean isEmpty()
{
return this.root == null;
}
@Override
public Iterator<Type> iterator()
{
Stack<Node<Type>> path = new Stack<>();
return new Iterator<Type>()
{
{
push(SortedSetAVL.this.root);
}
@Override
public boolean hasNext()
{
return !path.isEmpty();
}
@Override
public Type next()
{
if (path.isEmpty())
{
throw new NoSuchElementException();
}
else
{
Node<Type> node = path.peek();
Type result = node.value;
if (node.right != null)
{
push(node.right);
}
else
{
do
{
node = path.pop();
}
while (!path.isEmpty() && path.peek().right == node);
}
return result;
}
}
public void push(Node<Type> node)
{
while (node != null)
{
path.push(node);
node = node.left;
}
}
};
}
@Override
public Type last()
{
return Node.last(this.root).value;
}
@Override
public boolean remove(Object value)
{
int sizeBefore = size();
this.root = Node.delete(this.root, (Type) value, this.comparator);
return sizeBefore != size();
}
@Override
public boolean removeAll(Collection<?> collection)
{
return collection.stream()
.map(this::remove)
.reduce(true, (x, y) -> x | y);
}
@Override
public boolean retainAll(Collection<?> collection)
{
SortedSetAVL<Type> set = new SortedSetAVL<>(this.comparator);
collection.stream()
.map(element -> (Type) element)
.filter(this::contains)
.forEach(set::add);
boolean result = size() != set.size();
this.root = set.root;
return result;
}
@Override
public int size()
{
return this.root == null ? 0 : this.root.size;
}
@Override
public SortedSetAVL<Type> subSet(Type valueStart, Type valueEnd)
{
return tailSet(valueStart).headSet(valueEnd);
}
@Override
public SortedSetAVL<Type> tailSet(Type valueStart)
{
return new SortedSetAVL<>(this.comparator, Node.tail(this.root, valueStart, this.comparator));
}
@Override
public Object[] toArray()
{
return toArray(new Object[0]);
}
@Override
public <T> T[] toArray(T[] ts)
{
List<Object> list = new ArrayList<>();
Node.traverseOrderIn(this.root, list::add);
return list.toArray(ts);
}
@Override
public String toString()
{
return "{" + C_455.toString(this, ", ") + "}";
}
}
public static class Tree2D
{
public static final int SIZE = 1 << 30;
public static final Tree2D[] TREES_NULL = new Tree2D[] { null, null, null, null };
public static boolean contains(int x, int y, int left, int bottom, int size)
{
return left <= x && x < left + size && bottom <= y && y < bottom + size;
}
public static int count(Tree2D[] trees)
{
int result = 0;
for (int index = 0; index < 4; index++)
{
if (trees[index] != null)
{
result += trees[index].count;
}
}
return result;
}
public static int count
(
int rectangleLeft,
int rectangleBottom,
int rectangleRight,
int rectangleTop,
Tree2D tree,
int left,
int bottom,
int size
)
{
int result;
if (tree == null)
{
result = 0;
}
else
{
int right = left + size;
int top = bottom + size;
int intersectionLeft = Math.max(rectangleLeft, left);
int intersectionBottom = Math.max(rectangleBottom, bottom);
int intersectionRight = Math.min(rectangleRight, right);
int intersectionTop = Math.min(rectangleTop, top);
if (intersectionRight <= intersectionLeft || intersectionTop <= intersectionBottom)
{
result = 0;
}
else
{
if (intersectionLeft == left && intersectionBottom == bottom && intersectionRight == right && intersectionTop == top)
{
result = tree.count;
}
else
{
size = size >> 1;
result = 0;
for (int index = 0; index < 4; index++)
{
result += count
(
rectangleLeft,
rectangleBottom,
rectangleRight,
rectangleTop,
tree.trees[index],
quadrantLeft(left, size, index),
quadrantBottom(bottom, size, index),
size
);
}
}
}
}
return result;
}
public static int quadrantBottom(int bottom, int size, int index)
{
return bottom + (index >> 1) * size;
}
public static int quadrantLeft(int left, int size, int index)
{
return left + (index & 1) * size;
}
public final Tree2D[] trees;
public final int count;
private Tree2D(Tree2D[] trees, int count)
{
this.trees = trees;
this.count = count;
}
public Tree2D(Tree2D[] trees)
{
this(trees, count(trees));
}
public Tree2D()
{
this(TREES_NULL);
}
public int count(int rectangleLeft, int rectangleBottom, int rectangleRight, int rectangleTop)
{
return count
(
rectangleLeft,
rectangleBottom,
rectangleRight,
rectangleTop,
this,
0,
0,
SIZE
);
}
public Tree2D setPoint
(
int x,
int y,
Tree2D tree,
int left,
int bottom,
int size
)
{
Tree2D result;
if (contains(x, y, left, bottom, size))
{
if (size == 1)
{
result = new Tree2D(TREES_NULL, 1);
}
else
{
size = size >> 1;
Tree2D[] trees = new Tree2D[4];
for (int index = 0; index < 4; index++)
{
trees[index] = setPoint
(
x,
y,
tree == null ? null : tree.trees[index],
quadrantLeft(left, size, index),
quadrantBottom(bottom, size, index),
size
);
}
result = new Tree2D(trees);
}
}
else
{
result = tree;
}
return result;
}
public Tree2D setPoint(int x, int y)
{
return setPoint
(
x,
y,
this,
0,
0,
SIZE
);
}
}
public static class Tuple2<Type0, Type1>
{
public final Type0 v0;
public final Type1 v1;
public Tuple2(Type0 v0, Type1 v1)
{
this.v0 = v0;
this.v1 = v1;
}
@Override
public String toString()
{
return "(" + this.v0 + ", " + this.v1 + ")";
}
}
public static class Tuple2Comparable<Type0 extends Comparable<? super Type0>, Type1 extends Comparable<? super Type1>> extends Tuple2<Type0, Type1> implements Comparable<Tuple2Comparable<Type0, Type1>>
{
public Tuple2Comparable(Type0 v0, Type1 v1)
{
super(v0, v1);
}
@Override
public int compareTo(Tuple2Comparable<Type0, Type1> that)
{
int result = this.v0.compareTo(that.v0);
if (result == 0)
{
result = this.v1.compareTo(that.v1);
}
return result;
}
}
public static class Tuple3<Type0, Type1, Type2>
{
public final Type0 v0;
public final Type1 v1;
public final Type2 v2;
public Tuple3(Type0 v0, Type1 v1, Type2 v2)
{
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
}
@Override
public String toString()
{
return "(" + this.v0 + ", " + this.v1 + ", " + this.v2 + ")";
}
}
public static class Vertex
<
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>
>
implements Comparable<Vertex<? super TypeVertex, ? super TypeEdge>>
{
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>,
TypeResult
> TypeResult breadthFirstSearch
(
TypeVertex vertex,
TypeEdge edge,
BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
Array<Boolean> visited,
FIFO<TypeVertex> verticesNext,
FIFO<TypeEdge> edgesNext,
TypeResult result
)
{
if (!visited.get(vertex.index))
{
visited.set(vertex.index, true);
result = function.apply(vertex, edge, result);
for (TypeEdge edgeNext : vertex.edges)
{
TypeVertex vertexNext = edgeNext.other(vertex);
if (!visited.get(vertexNext.index))
{
verticesNext.push(vertexNext);
edgesNext.push(edgeNext);
}
}
}
return result;
}
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>,
TypeResult
>
TypeResult breadthFirstSearch
(
Array<TypeVertex> vertices,
int indexVertexStart,
BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
TypeResult result
)
{
Array<Boolean> visited = new Array<>(vertices.size(), false);
FIFO<TypeVertex> verticesNext = new FIFO<>();
verticesNext.push(vertices.get(indexVertexStart));
FIFO<TypeEdge> edgesNext = new FIFO<>();
edgesNext.push(null);
while (!verticesNext.isEmpty())
{
result = breadthFirstSearch(verticesNext.pop(), edgesNext.pop(), function, visited, verticesNext, edgesNext, result);
}
return result;
}
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>
>
boolean
cycle
(
TypeVertex start,
SortedSet<TypeVertex> result
)
{
boolean cycle = false;
Stack<TypeVertex> stackVertex = new Stack<>();
Stack<TypeEdge> stackEdge = new Stack<>();
stackVertex.push(start);
stackEdge.push(null);
while (!stackVertex.isEmpty())
{
TypeVertex vertex = stackVertex.pop();
TypeEdge edge = stackEdge.pop();
if (!result.contains(vertex))
{
result.add(vertex);
for (TypeEdge otherEdge : vertex.edges)
{
if (otherEdge != edge)
{
TypeVertex otherVertex = otherEdge.other(vertex);
if (result.contains(otherVertex))
{
cycle = true;
}
else
{
stackVertex.push(otherVertex);
stackEdge.push(otherEdge);
}
}
}
}
}
return cycle;
}
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>
>
SortedSet<TypeVertex>
depthFirstSearch
(
TypeVertex start,
BiConsumer<TypeVertex, TypeEdge> functionVisitPre,
BiConsumer<TypeVertex, TypeEdge> functionVisitPost
)
{
SortedSet<TypeVertex> result = new SortedSetAVL<>(Comparator.naturalOrder());
Stack<TypeVertex> stackVertex = new Stack<>();
Stack<TypeEdge> stackEdge = new Stack<>();
stackVertex.push(start);
stackEdge.push(null);
while (!stackVertex.isEmpty())
{
TypeVertex vertex = stackVertex.pop();
TypeEdge edge = stackEdge.pop();
if (result.contains(vertex))
{
functionVisitPost.accept(vertex, edge);
}
else
{
result.add(vertex);
stackVertex.push(vertex);
stackEdge.push(edge);
functionVisitPre.accept(vertex, edge);
for (TypeEdge otherEdge : vertex.edges)
{
TypeVertex otherVertex = otherEdge.other(vertex);
if (!result.contains(otherVertex))
{
stackVertex.push(otherVertex);
stackEdge.push(otherEdge);
}
}
}
}
return result;
}
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>
>
SortedSet<TypeVertex>
depthFirstSearch
(
TypeVertex start,
Consumer<TypeVertex> functionVisitPreVertex,
Consumer<TypeVertex> functionVisitPostVertex
)
{
BiConsumer<TypeVertex, TypeEdge> functionVisitPreVertexEdge = (vertex, edge) ->
{
functionVisitPreVertex.accept(vertex);
};
BiConsumer<TypeVertex, TypeEdge> functionVisitPostVertexEdge = (vertex, edge) ->
{
functionVisitPostVertex.accept(vertex);
};
return depthFirstSearch(start, functionVisitPreVertexEdge, functionVisitPostVertexEdge);
}
public final int index;
public final List<TypeEdge> edges;
public Vertex(int index)
{
this.index = index;
this.edges = new ArrayList<>();
}
@Override
public int compareTo(Vertex<? super TypeVertex, ? super TypeEdge> that)
{
return Integer.compare(this.index, that.index);
}
@Override
public String toString()
{
return "" + this.index;
}
}
public static class VertexDefault<TypeEdge extends Edge<VertexDefault<TypeEdge>, TypeEdge>> extends Vertex<VertexDefault<TypeEdge>, TypeEdge>
{
public VertexDefault(int index)
{
super(index);
}
}
public static class VertexDefaultDefault extends Vertex<VertexDefaultDefault, EdgeDefaultDefault>
{
public static Array<VertexDefaultDefault> vertices(int n)
{
Array<VertexDefaultDefault> result = new Array<>(n);
for (int index = 0; index < n; index++)
{
result.set(index, new VertexDefaultDefault(index));
}
return result;
}
public VertexDefaultDefault(int index)
{
super(index);
}
}
public static class Wrapper<Type>
{
public Type value;
public Wrapper(Type value)
{
this.value = value;
}
public Type get()
{
return this.value;
}
public void set(Type value)
{
this.value = value;
}
@Override
public String toString()
{
return this.value.toString();
}
}
public static void add(int delta, int[] result)
{
for (int index = 0; index < result.length; index++)
{
result[index] += delta;
}
}
public static void add(int delta, int[]... result)
{
for (int index = 0; index < result.length; index++)
{
add(delta, result[index]);
}
}
public static int binarySearchMaximum(Function<Integer, Boolean> filter, int start, int end)
{
return -binarySearchMinimum(x -> filter.apply(-x), -end, -start);
}
public static int binarySearchMinimum(Function<Integer, Boolean> filter, int start, int end)
{
int result;
if (start == end)
{
result = end;
}
else
{
int middle = start + (end - start) / 2;
if (filter.apply(middle))
{
result = binarySearchMinimum(filter, start, middle);
}
else
{
result = binarySearchMinimum(filter, middle + 1, end);
}
}
return result;
}
public static void close()
{
out.close();
}
public static List<List<Integer>> combinations(int n, int k)
{
List<List<Integer>> result = new ArrayList<>();
if (k == 0)
{
}
else
{
if (k == 1)
{
List<Integer> combination = new ArrayList<>();
combination.add(n);
result.add(combination);
}
else
{
for (int index = 0; index <= n; index++)
{
for (List<Integer> combination : combinations(n - index, k - 1))
{
combination.add(index);
result.add(combination);
}
}
}
}
return result;
}
public static <Type> int compare(Iterator<Type> iterator0, Iterator<Type> iterator1, Comparator<Type> comparator)
{
int result = 0;
while (result == 0 && iterator0.hasNext() && iterator1.hasNext())
{
result = comparator.compare(iterator0.next(), iterator1.next());
}
if (result == 0)
{
if (iterator1.hasNext())
{
result = -1;
}
else
{
if (iterator0.hasNext())
{
result = 1;
}
}
}
return result;
}
public static <Type> int compare(Iterable<Type> iterable0, Iterable<Type> iterable1, Comparator<Type> comparator)
{
return compare(iterable0.iterator(), iterable1.iterator(), comparator);
}
public static long divideCeil(long x, long y)
{
return (x + y - 1) / y;
}
public static Set<Long> divisors(long n)
{
SortedSetAVL<Long> result = new SortedSetAVL<>(Comparator.naturalOrder());
result.add(1L);
for (Long factor : factors(n))
{
SortedSetAVL<Long> divisors = new SortedSetAVL<>(result);
for (Long divisor : result)
{
divisors.add(divisor * factor);
}
result = divisors;
}
return result;
}
public static LinkedList<Long> factors(long n)
{
LinkedList<Long> result = new LinkedList<>();
Iterator<Long> primes = ITERATOR_BUFFER_PRIME.iterator();
Long prime;
while (n > 1 && (prime = primes.next()) * prime <= n)
{
while (n % prime == 0)
{
result.add(prime);
n /= prime;
}
}
if (n > 1)
{
result.add(n);
}
return result;
}
public static long faculty(int n)
{
long result = 1;
for (int index = 2; index <= n; index++)
{
result *= index;
}
return result;
}
public static long gcd(long a, long b)
{
while (a != 0 && b != 0)
{
if (a > b)
{
a %= b;
}
else
{
b %= a;
}
}
return a + b;
}
public static long[] generatePOWER2()
{
long[] result = new long[63];
for (int x = 0; x < result.length; x++)
{
result[x] = 1L << x;
}
return result;
}
public static boolean isPrime(long x)
{
boolean result = x > 1;
Iterator<Long> iterator = ITERATOR_BUFFER_PRIME.iterator();
Long prime;
while ((prime = iterator.next()) * prime <= x)
{
result &= x % prime > 0;
}
return result;
}
public static long knapsack(List<Tuple3<Long, Integer, Integer>> itemsValueWeightCount, int weightMaximum)
{
long[] valuesMaximum = new long[weightMaximum + 1];
for (Tuple3<Long, Integer, Integer> itemValueWeightCount : itemsValueWeightCount)
{
long itemValue = itemValueWeightCount.v0;
int itemWeight = itemValueWeightCount.v1;
int itemCount = itemValueWeightCount.v2;
for (int weight = weightMaximum; 0 <= weight; weight--)
{
for (int index = 1; index <= itemCount && 0 <= weight - index * itemWeight; index++)
{
valuesMaximum[weight] = Math.max(valuesMaximum[weight], valuesMaximum[weight - index * itemWeight] + index * itemValue);
}
}
}
long result = 0;
for (long valueMaximum : valuesMaximum)
{
result = Math.max(result, valueMaximum);
}
return result;
}
public static boolean knapsackPossible(List<Tuple2<Integer, Integer>> itemsWeightCount, int weightMaximum)
{
boolean[] weightPossible = new boolean[weightMaximum + 1];
weightPossible[0] = true;
int weightLargest = 0;
for (Tuple2<Integer, Integer> itemWeightCount : itemsWeightCount)
{
int itemWeight = itemWeightCount.v0;
int itemCount = itemWeightCount.v1;
for (int weightStart = 0; weightStart < itemWeight; weightStart++)
{
int count = 0;
for (int weight = weightStart; weight <= weightMaximum && (0 < count || weight <= weightLargest); weight += itemWeight)
{
if (weightPossible[weight])
{
count = itemCount;
}
else
{
if (0 < count)
{
weightPossible[weight] = true;
weightLargest = weight;
count -= 1;
}
}
}
}
}
return weightPossible[weightMaximum];
}
public static long lcm(int a, int b)
{
return a * b / gcd(a, b);
}
public static void main(String[] args)
{
try
{
solve();
}
catch (IOException exception)
{
exception.printStackTrace();
}
close();
}
public static double nextDouble() throws IOException
{
return Double.parseDouble(nextString());
}
public static int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
public static void nextInts(int n, int[]... result) throws IOException
{
for (int index = 0; index < n; index++)
{
for (int value = 0; value < result.length; value++)
{
result[value][index] = nextInt();
}
}
}
public static int[] nextInts(int n) throws IOException
{
int[] result = new int[n];
nextInts(n, result);
return result;
}
public static String nextLine() throws IOException
{
return bufferedReader.readLine();
}
public static long nextLong() throws IOException
{
return Long.parseLong(nextString());
}
public static void nextLongs(int n, long[]... result) throws IOException
{
for (int index = 0; index < n; index++)
{
for (int value = 0; value < result.length; value++)
{
result[value][index] = nextLong();
}
}
}
public static long[] nextLongs(int n) throws IOException
{
long[] result = new long[n];
nextLongs(n, result);
return result;
}
public static String nextString() throws IOException
{
while ((stringTokenizer == null) || (!stringTokenizer.hasMoreTokens()))
{
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
}
return stringTokenizer.nextToken();
}
public static String[] nextStrings(int n) throws IOException
{
String[] result = new String[n];
{
for (int index = 0; index < n; index++)
{
result[index] = nextString();
}
}
return result;
}
public static <T> List<T> permutation(long p, List<T> x)
{
List<T> copy = new ArrayList<>();
for (int index = 0; index < x.size(); index++)
{
copy.add(x.get(index));
}
List<T> result = new ArrayList<>();
for (int indexTo = 0; indexTo < x.size(); indexTo++)
{
int indexFrom = (int) p % copy.size();
p = p / copy.size();
result.add(copy.remove(indexFrom));
}
return result;
}
public static <Type> List<List<Type>> permutations(List<Type> list)
{
List<List<Type>> result = new ArrayList<>();
result.add(new ArrayList<>());
for (Type element : list)
{
List<List<Type>> permutations = result;
result = new ArrayList<>();
for (List<Type> permutation : permutations)
{
for (int index = 0; index <= permutation.size(); index++)
{
List<Type> permutationNew = new ArrayList<>(permutation);
permutationNew.add(index, element);
result.add(permutationNew);
}
}
}
return result;
}
public static Stream<BigInteger> streamFibonacci()
{
return Stream.generate(new Supplier<BigInteger>()
{
private BigInteger n0 = BigInteger.ZERO;
private BigInteger n1 = BigInteger.ONE;
@Override
public BigInteger get()
{
BigInteger result = n0;
n0 = n1;
n1 = result.add(n0);
return result;
}
});
}
public static Stream<Long> streamPrime(int sieveSize)
{
return Stream.generate(new Supplier<Long>()
{
private boolean[] isPrime = new boolean[sieveSize];
private long sieveOffset = 2;
private List<Long> primes = new ArrayList<>();
private int index = 0;
public void filter(long prime, boolean[] result)
{
if (prime * prime < this.sieveOffset + sieveSize)
{
long remainingStart = this.sieveOffset % prime;
long start = remainingStart == 0 ? 0 : prime - remainingStart;
for (long index = start; index < sieveSize; index += prime)
{
result[(int) index] = false;
}
}
}
public void generatePrimes()
{
Arrays.fill(this.isPrime, true);
this.primes.forEach(prime -> filter(prime, isPrime));
for (int index = 0; index < sieveSize; index++)
{
if (isPrime[index])
{
this.primes.add(this.sieveOffset + index);
filter(this.sieveOffset + index, isPrime);
}
}
this.sieveOffset += sieveSize;
}
@Override
public Long get()
{
while (this.primes.size() <= this.index)
{
generatePrimes();
}
Long result = this.primes.get(this.index);
this.index += 1;
return result;
}
});
}
public static <Type> String toString(Iterator<Type> iterator, String separator)
{
StringBuilder stringBuilder = new StringBuilder();
if (iterator.hasNext())
{
stringBuilder.append(iterator.next());
}
while (iterator.hasNext())
{
stringBuilder.append(separator);
stringBuilder.append(iterator.next());
}
return stringBuilder.toString();
}
public static <Type> String toString(Iterator<Type> iterator)
{
return toString(iterator, " ");
}
public static <Type> String toString(Iterable<Type> iterable, String separator)
{
return toString(iterable.iterator(), separator);
}
public static <Type> String toString(Iterable<Type> iterable)
{
return toString(iterable, " ");
}
public static long totient(long n)
{
Set<Long> factors = new SortedSetAVL<>(factors(n), Comparator.naturalOrder());
long result = n;
for (long p : factors)
{
result -= result / p;
}
return result;
}
interface BiFunctionResult<Type0, Type1, TypeResult>
{
TypeResult apply(Type0 x0, Type1 x1, TypeResult x2);
}
public static final long BIG = 1000000007;
public static long bigAdd(long x, long y)
{
return (x + y) % BIG;
}
public static long bigMultiply(long x, long y)
{
return (x * y) % BIG;
}
public static int convert(int n, int start, int end)
{
return n * start + end;
}
public static long solve(long[] results, boolean[] statements, int start, int end)
{
int converted = convert(statements.length, start, end);
long result = results[converted];
if (result == -1)
{
if (start == end)
{
result = 1L;
}
else
{
if (statements[start])
{
result = solve(results, statements, start + 1, end);
}
else
{
result = 0L;
for (int index = start + 2; index <= end; index++)
{
long inside = solve(results, statements, start + 1, index);
long outside = solve(results, statements, index, end);
result = C_455.bigAdd(result, C_455.bigMultiply(inside, outside));
}
}
}
results[converted] = result;
}
return result;
}
public static long solve(boolean[] statements)
{
long[] results = new long[(statements.length + 1) * (statements.length + 1)];
Arrays.fill(results, -1);
return solve(results, statements, 0, statements.length);
}
public static long solveFast(boolean[] statements)
{
long[] indent2Count = new long[statements.length];
indent2Count[0] = 1;
for (boolean statement: statements)
{
if (statement)
{
long count = 0;
for (int index = statements.length - 1; 0 <= index; index--)
{
count = bigAdd(count, indent2Count[index]);
indent2Count[index] = count;
}
}
else
{
for (int index = statements.length - 1; 1 <= index; index--)
{
indent2Count[index] = indent2Count[index - 1];
}
indent2Count[0] = 0;
}
}
return indent2Count[0];
}
public static void solve() throws IOException
{
int n = nextInt();
boolean[] statements = new boolean[n];
for (int index = 0; index < n; index++)
{
statements[index] = nextString().equals("s");
}
out.println(solveFast(statements));
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class PrB {
public static long time;
public static void main(String[] args) throws Exception {
time = System.currentTimeMillis();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
a = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++)
a[i] = Integer.parseInt(st.nextToken());
int end = end();
if(end < 0) System.out.println("-1 -1");
else System.out.println((start(end) + 1) + " " + (end + 1));
br.close();
System.exit(0);
}
static int n, k;
static int[] a;
public static int end() throws Exception {
boolean[] reached = new boolean[100002];
int rem = k;
for(int i = 0; i < n; i++) {
if(!reached[a[i]]) {
rem--;
if(rem == 0) return i;
}
reached[a[i]] = true;
}
return -1;
}
public static int start(int end) throws Exception {
boolean[] reached = new boolean[100002];
int rem = k;
for(int i = end; i >= 0; i--) {
if(!reached[a[i]]) {
rem--;
if(rem == 0) return i;
}
reached[a[i]] = true;
}
return 0;
}
public static void checkTime() {
System.out.println(System.currentTimeMillis() - time);
time = System.currentTimeMillis();
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class A {
public static void main(String[] args) throws Exception{
String str = new Scanner(System.in).next();
Set<String> set = new HashSet<String>();
String max = "";
for(int l = 1; l < str.length(); ++l){
for(int i = 0; i < str.length()-l; ++i){
String substr = str.substring(i, i+l);
if(!set.contains(substr) && str.indexOf(substr) != str.lastIndexOf(substr)){
set.add(substr);
if(substr.length() > max.length()){
max = substr;
}
}
}
}
System.out.println(max.length());
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.*;
public class B {
static int[] loyality;
static int[] level;
static int mid;
static int a, n;
static double sol;
public static void getMax(int idx, int rem) {
if (idx == loyality.length) {
double pos = 0;
for (int i = 0; i < (1 << n); i++)
pos += solve(i);
sol = Math.max(sol, pos);
return;
}
int cur = loyality[idx];
int r = 0;
while (r + cur <= 10 && r <= rem) {
loyality[idx] = cur + r;
getMax(idx + 1, rem - r);
r++;
}
loyality[idx] = cur;
}
public static double solve(int mask) {
int c = 0;
int sum = 0;
double b = 1;
for (int i = 0; i < n; i++) {
if (((1 << i) | mask) == mask) {
c++;
b *= (loyality[i] / 10.0);
} else {
sum += level[i];
b *= (1 - (loyality[i] / 10.0));
}
}
if (c >= mid)
return b;
return b * (a * 1.0) / (a + sum);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int k = sc.nextInt();
a = sc.nextInt();
level = new int[n];
loyality = new int[n];
for (int i = 0; i < n; i++) {
level[i] = sc.nextInt();
loyality[i] = sc.nextInt() / 10;
}
mid = (n/2) +1;
sol = 0;
getMax(0, k);
System.out.println(sol);
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main{
static int[][]memo;
static int n,m,in[][];
static int dp(int col,int maxRowMask) {
if(col>=m)return 0;
if(memo[col][maxRowMask]!=-1)return memo[col][maxRowMask];
int ans=0;
for(int colMask=0;colMask<(1<<n);colMask++) {
int sum=0;
for(int i=0;i<n;i++) {
if(((colMask>>i)&1)!=0) {
sum+=in[i][col];
}
}
int curMask=colMask;
for(int cyclicShift=0;cyclicShift<n;cyclicShift++) {
if((curMask&maxRowMask)!=0) {//some row has max value already determined
int lastBit=curMask&1;
curMask>>=1;
curMask|=(lastBit<<(n-1));
continue;
}
ans=Math.max(ans, sum+dp(col+1, maxRowMask|curMask));
int lastBit=curMask&1;
curMask>>=1;
curMask|=(lastBit<<(n-1));
}
}
return memo[col][maxRowMask]=ans;
}
public static void main(String[] args) throws Exception{
pw=new PrintWriter(System.out);
sc = new MScanner(System.in);
int tc=sc.nextInt();
while(tc-->0) {
n=sc.nextInt();m=sc.nextInt();
in=new int[n][m];
for(int i=0;i<n;i++)in[i]=sc.intArr(m);
memo=new int[m][1<<n];
for(int i=0;i<m;i++)Arrays.fill(memo[i], -1);
pw.println(dp(0, 0));
}
pw.flush();
}
static PrintWriter pw;
static MScanner sc;
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
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[] intArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] LongArr(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void shuffle(int[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
int tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
static void shuffle(long[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
long tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class C implements Runnable {
private static final boolean USE_FILE_IO = false;
private static final String FILE_IN = "c.in";
private static final String FILE_OUT = "c.out";
BufferedReader in;
PrintWriter out;
StringTokenizer tokenizer = new StringTokenizer("");
public static void main(String[] args) {
new Thread(new C()).start();
}
int n, h, t;
char[] c;
private void solve() throws IOException {
n = nextInt();
c = nextToken().toCharArray();
if (c.length != n) {
throw new IllegalStateException();
}
for (char l : c)
if (l == 'H') {
h++;
}
t = n - h;
if (h == 0) {
out.print(0);
return;
}
int answer = Integer.MAX_VALUE;
for (int hLo = 0; hLo < n; hLo++)
if (c[hLo] == 'H') {
int hHi = (hLo + h) % n;
int current = 0;
int j = hLo;
while (j != hHi) {
if (c[j] == 'T') {
current++;
}
j = (j + 1) % n;
}
answer = Math.min(answer, current);
}
out.print(answer);
}
public void run() {
long timeStart = System.currentTimeMillis();
try {
if (USE_FILE_IO) {
in = new BufferedReader(new FileReader(FILE_IN));
out = new PrintWriter(new FileWriter(FILE_OUT));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
}
solve();
in.close();
out.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
long timeEnd = System.currentTimeMillis();
System.out.println("Time spent: " + (timeEnd - timeStart) + " ms");
}
private String nextToken() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private BigInteger nextBigInt() throws IOException {
return new BigInteger(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CodeF
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String nextLine()
{
try
{
return br.readLine();
}
catch(Exception e)
{
throw(new RuntimeException());
}
}
public String next()
{
while(!st.hasMoreTokens())
{
String l = nextLine();
if(l == null)
return null;
st = new StringTokenizer(l);
}
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 int[] nextIntArray(int n)
{
int[] res = new int[n];
for(int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public long[] nextLongArray(int n)
{
long[] res = new long[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public double[] nextDoubleArray(int n)
{
double[] res = new double[n];
for(int i = 0; i < res.length; i++)
res[i] = nextDouble();
return res;
}
public void sortIntArray(int[] array)
{
Integer[] vals = new Integer[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortLongArray(long[] array)
{
Long[] vals = new Long[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortDoubleArray(double[] array)
{
Double[] vals = new Double[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public String[] nextStringArray(int n)
{
String[] vals = new String[n];
for(int i = 0; i < n; i++)
vals[i] = next();
return vals;
}
Integer nextInteger()
{
String s = next();
if(s == null)
return null;
return Integer.parseInt(s);
}
int[][] nextIntMatrix(int n, int m)
{
int[][] ans = new int[n][];
for(int i = 0; i < n; i++)
ans[i] = nextIntArray(m);
return ans;
}
}
static int[] compute_prefix_function(char[] p) {
int[] pi = new int[p.length]; pi[0] = -1; int k = -1;
for (int i = 1; i < p.length; i++) {
while (k >= 0 && p[k + 1] != p[i]) k = pi[k];
if (p[k + 1] == p[i]) k++; pi[i] = k;
}
return pi;
}
static boolean KMP_Matcher(String pattern, String text) {
char[] p = pattern.toCharArray(); char[] t = text.toCharArray();
int[] pi = compute_prefix_function(p); int q = -1;
int cuenta = 0;
for (int i = 0; i < text.length(); i++) {
while (q >= 0 && p[q + 1] != t[i]) q = pi[q];
if (p[q + 1] == t[i]) q++;
if (q == p.length - 1) {
cuenta++;
q = pi[q];
}
}
return cuenta >= 2;
}
public static void main(String[] args)
{
Scanner sc = new Scanner();
String entrada = sc.next();
int mejor = 0;
for(int i = 0; i < entrada.length(); i++)
{
for(int j = i + 1; j <= entrada.length(); j++)
{
String sub = entrada.substring(i, j);
if(KMP_Matcher(sub, entrada))
mejor = Math.max(j - i, mejor);
}
}
System.out.println(mejor);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
/**
* @author Finn Lidbetter
*/
import java.util.*;
import java.io.*;
import java.awt.geom.*;
public class TaskA {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int n = Integer.parseInt(br.readLine());
String[] s = br.readLine().split(" ");
int[] arr = new int[n];
for (int i=0; i<n; i++) {
arr[i] = Integer.parseInt(s[i]);
}
Arrays.sort(arr);
boolean[] vis = new boolean[n];
int nColours = 0;
int nVis = 0;
int index = 0;
while (nVis<n) {
while (index<n && nVis<n) {
if (vis[index]) {
index++;
continue;
}
int val = arr[index];
nColours++;
while (index<n && nVis<n) {
if (vis[index]) {
index++;
continue;
}
if (arr[index]%val==0) {
vis[index] = true;
nVis++;
}
index++;
}
index = 0;
}
}
System.out.println(nColours);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
static Map<BigInteger, BigInteger> mp = new HashMap<BigInteger, BigInteger>();
public static void main(String[] args) {
mp.clear();
Scanner cin = new Scanner(new BufferedInputStream(System.in));
BigInteger n = cin.nextBigInteger();
BigInteger x = cin.nextBigInteger();
mp.put(x, BigInteger.ONE);
BigInteger sum = x;
BigInteger ans = BigInteger.ZERO;
for (int i = 2;i <= n.intValue(); i++) {
x=cin.nextBigInteger();
BigInteger tmp = x.multiply(BigInteger.valueOf(i-1)).subtract(sum);
if (mp.containsKey(x.subtract(BigInteger.ONE))) tmp = tmp.subtract(mp.get(x.subtract(BigInteger.ONE)));
if (mp.containsKey(x.add(BigInteger.ONE))) tmp = tmp.add(mp.get(x.add(BigInteger.ONE)));
ans = ans.add(tmp);
sum = sum.add(x);
BigInteger xx;
if (mp.containsKey(x)) xx = mp.get(x);
else xx = BigInteger.ZERO;
mp.put(x, xx.add(BigInteger.ONE));
}
System.out.println(ans);
}
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Soln {
public static int[] io(int n) {
int[] d = new int[n];
for (int i=0;i<n;i++) d[i] = f.nextInt();
return d;
}
public static int binlog( int bits ){
int log = 0;
if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; }
if( bits >= 256 ) { bits >>>= 8; log += 8; }
if( bits >= 16 ) { bits >>>= 4; log += 4; }
if( bits >= 4 ) { bits >>>= 2; log += 2; }
return log + ( bits >>> 1 );
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static final long mod = (long)Math.pow(10, 9) + 7;
static FastReader f=new FastReader();
public static void main (String[] args) throws IOException{
int n = f.nextInt();
int[] a = io(n);
HashMap<Integer,ArrayList<ivl>> hm = new HashMap<>();
for (int i=0;i<n;i++) {
int sum = 0;
for (int j=i;j<n;j++) {
sum+=a[j];
if (hm.get(sum)==null) hm.put(sum,new ArrayList<ivl>());
hm.get(sum).add(new ivl(i,j));
}
}
HashSet<ivl> hs = new HashSet<ivl>();
for (ArrayList<ivl> arr : hm.values()) {
Collections.sort(arr,new comp());
HashSet<ivl> temp = new HashSet<ivl>();
temp.add(arr.get(0));
int lastr = arr.get(0).r;
int num = 1;
for (ivl curr:arr) {
if (curr.l>lastr) {
lastr = curr.r;
num++;
temp.add(curr);
}
}
if (temp.size()>hs.size()) hs = temp;
}
System.out.println(hs.size());
for (ivl curr:hs) {
System.out.println((curr.l+1)+" "+(curr.r+1));
}
}
static class ivl{
int l,r;
ivl(int l,int r){
this.l=l;this.r=r;
}
}
static class comp implements Comparator<ivl>{
public int compare(ivl a,ivl b) {
if (a.r - b.r == 0) return a.l-b.l;
return a.r-b.r;
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class A {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void solve() throws IOException {
int n = readInt();
long k = readInt();
Long[] a = new Long[n];
for(int i = 0; i < n; i++){
a[i] = readLong();
}
Arrays.sort(a);
TreeSet<Long> set = new TreeSet<Long>();
for(int i = 0; i < n; i++){
set.add(a[i]);
}
if(k == 1) {
out.println(n);
return;
}
int res = 0;
TreeSet<Long> used = new TreeSet<Long>();
for(Long cur: set){
if(!used.contains(cur)){
int num = 1;
used.add(cur);
Long temp = cur * 1;
while(true){
if(set.contains(k*temp)){
num++;
used.add(k*temp);
temp *= k;
}
else{
res += (num+1)/2;
break;
}
}
}
}
out.println(res);
}
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());
}
int[] readArr(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = readInt();
}
return res;
}
long[] readArrL(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = readLong();
}
return res;
}
public static void main(String[] args) {
new A().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);
}
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
public class OlyaAndMagicalSquare {
public static void solveCase(FastIO io) {
int N = io.nextInt();
long K = io.nextLong();
CountMap cm = new CountMap();
cm.increment(N, BigInteger.ONE);
long rem = K;
int moves = 1;
int sqSize = N;
while (sqSize > 0) {
long need = (1L << moves) - 1;
BigInteger biNeed = BigInteger.valueOf(need);
cm.decrement(sqSize, biNeed);
if (need > rem) {
break;
}
cm.increment(sqSize - 1, biNeed.multiply(BigInteger.valueOf(4)));
rem -= need;
++moves;
--sqSize;
}
BigInteger biRem = BigInteger.valueOf(rem);
for (int i = N; i > 0; --i) {
BigInteger have = cm.getCount(i);
if (have.compareTo(biRem) >= 0) {
biRem = BigInteger.ZERO;
break;
}
biRem = biRem.subtract(have);
cm.decrement(i, have);
cm.increment(i - 1, have.multiply(BigInteger.valueOf(4)));
}
if (biRem.equals(BigInteger.ZERO)) {
io.printf("YES %d\n", sqSize);
} else {
io.println("NO");
}
// long N = io.nextLong();
// long K = io.nextLong();
// // io.println(1L << 62);
// boolean good;
// if (N >= 31) {
// good = true;
// } else {
// good = ((1L << (N << 1)) / 3 >= K);
// }
// if (!good) {
// io.println("NO");
// return;
// }
// int split = getMaxSplit(K);
// if (N >= 40) {
// io.printf("YES %d\n", N - split);
// return;
// }
// long used = (1L << split) - 1;
// long rem = K - used;
}
private static class CountMap extends HashMap<Integer, BigInteger> {
public void increment(int k, BigInteger v) {
put(k, getCount(k).add(v));
}
public void decrement(int k, BigInteger v) {
BigInteger next = getCount(k).subtract(v);
if (next.equals(BigInteger.ZERO)) {
remove(k);
} else {
put(k, next);
}
}
public BigInteger getCount(int k) {
return getOrDefault(k, BigInteger.ZERO);
}
}
private static int getMaxSplit(long k) {
for (int i = 1;; ++i) {
if ((1L << (i + 1)) - 2 - i > k) {
return i - 1;
}
}
}
public static void solve(FastIO io) {
int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
Scanner in;
PrintWriter out;
static class House implements Comparable <House>{
int len;
int pos;
House(Scanner in){
pos = in.nextInt() * 2;
len = in.nextInt() * 2;
}
public int compareTo(House arg0) {
return this.pos-arg0.pos;
}
}
void solve(){
int n = in.nextInt();
int size = in.nextInt();
House []h = new House[n];
for (int i = 0; i < h.length; i++){
h[i] = new House(in);
}
Arrays.sort(h);
int ans = 2;
for (int i = 0; i < h.length - 1; i++){
int next = i + 1;
int sz = h[next].pos - h[i].pos - (h[next].len + h[i].len) / 2;
if (sz == size * 2) {
ans ++;
} else if (sz > size * 2) {
ans += 2;
}
}
out.println(ans);
}
public void run(){
in = new Scanner(System.in);
out = new PrintWriter(System.out);
try {
solve();
} finally {
out.close();
}
}
void asserT(boolean e){
if (!e){
throw new Error();
}
}
public static void main(String[] args) {
new Main().run();
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CodeForces
{
public static void main(String[] args)
{
Scanner input = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println(input.nextInt() / 2 + 1);
}
}
|
constant
|
964_A. Splits
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.Set;
import java.util.Map.Entry;
import java.util.HashMap;
import java.util.Iterator;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String num = input.nextLine();
System.out.println("25");
}
}
|
constant
|
630_A. Again Twenty Five!
|
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;
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);
F solver = new F();
solver.solve(1, in, out);
out.close();
}
static class F {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.ni(), m = in.ni();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
a[i] = in.na(m);
}
if (n == 1) {
int ans = Integer.MAX_VALUE;
for (int i = 1; i < m; i++) {
ans = Math.min(ans, Math.abs(a[0][i] - a[0][i - 1]));
}
out.println(ans);
return;
}
int[][] mk = new int[n][n];
int[][] mk1 = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int minK = Integer.MAX_VALUE;
int minK1 = Integer.MAX_VALUE;
int minK2 = Integer.MAX_VALUE;
for (int l = 0; l < m; l++) {
minK = Math.min(minK, Math.abs(a[i][l] - a[j][l]));
if (l > 0) {
minK1 = Math.min(minK1, Math.abs(a[i][l] - a[j][l - 1]));
minK2 = Math.min(minK2, Math.abs(a[i][l - 1] - a[j][l]));
}
}
mk[i][j] = mk[j][i] = minK;
mk1[i][j] = minK1;
mk1[j][i] = minK2;
}
}
int ans = 0;
for (int first = 0; first < n; first++) {
int[][] dp = new int[1 << n][n];
for (int mask = 1; mask < (1 << n) - 1; mask++) {
int bc = Integer.bitCount(mask);
if ((mask & (1 << first)) != 0) {
if (bc == 1) {
dp[mask][first] = Integer.MAX_VALUE;
}
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0) {
for (int j = 0; j < n; j++) {
if ((mask & (1 << j)) == 0) {
dp[mask | (1 << j)][j] = Math.max(dp[mask | (1 << j)][j], Math.min(dp[mask][i], mk[i][j]));
}
}
}
}
}
}
for (int i = 0; i < n; i++) {
if (i != first) {
ans = Math.max(ans, Math.min(dp[(1 << n) - 1][i], mk1[first][i]));
}
}
}
out.println(ans);
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String ns() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(ns());
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
}
}
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), k = in.nextInt();
int x[] = new int[n];
for (int i = 0; i < n; i++) {
int p = in.nextInt(), t = in.nextInt();
x[i] = (50 - p) * 100 + t;
}
Arrays.sort(x);
int cnt = 0;
for (int q: x)
if (q == x[k - 1]) cnt++;
System.out.println(cnt);
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CF267A {
public static void main(String[] args) {
int n=0, a, b;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
try {
n = Integer.parseInt(stdin.readLine());
} catch (IOException e) {
}
while(n-->0){
String[] row = null;
try {
row = stdin.readLine().split(" ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a = Integer.parseInt(row[0]);
b = Integer.parseInt(row[1]);
if(a<b) System.out.println(calc(a,b));
else System.out.println(calc(b,a));
}
}
static int calc(int a, int b){
if(a==0) return 0;
if(a==b) return 1;
if(a==1) return b;
else return b/a+calc(b%a, a);
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.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 anand.oza
*/
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);
APaintTheNumbers solver = new APaintTheNumbers();
solver.solve(1, in, out);
out.close();
}
static class APaintTheNumbers {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.readIntArray(n);
Arrays.sort(a);
int answer = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 0)
continue;
answer++;
for (int j = 0; j < n; j++) {
if (j == i)
continue;
if (a[j] % a[i] == 0) {
a[j] = 0;
}
}
a[i] = 0;
}
out.println(answer);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] readIntArray(int n) {
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextInt();
}
return x;
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class A23 {
static StreamTokenizer in;
static PrintWriter out;
static int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
static String nextString() throws IOException {
in.nextToken();
return in.sval;
}
public static void main(String[] args) throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
String s = nextString();
for (int i = s.length(); i > 0; i--) {
for (int j = 0; j+i-1 < s.length(); j++)
for (int k = j+1; k+i-1 < s.length(); k++)
if (s.substring(j, j+i).equals(s.substring(k, k+i))) {
out.println(i);
out.flush();
return;
}
}
out.println("0");
out.flush();
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.Scanner;
public class GenerateLogin {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
char last = b.charAt(0);
String ans = ""+a.charAt(0);
for(int i = 1;i<a.length();i++){
if(a.charAt(i)>=last)break;
ans+=a.charAt(i);
}
ans+=last;
System.out.println(ans);
}
}
|
linear
|
909_A. Generate Login
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Problem implements Runnable {
private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private BufferedReader in;
private PrintWriter out;
private StringTokenizer tok = new StringTokenizer("");
private void init() throws FileNotFoundException {
Locale.setDefault(Locale.US);
String fileName = "";
/* if (ONLINE_JUDGE && fileName.isEmpty()) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
if (fileName.isEmpty()) {*/
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
/* } else {
in = new BufferedReader(new FileReader(fileName + ".in"));
out = new PrintWriter(fileName + ".out");
/* }
}*/
}
String readString() {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() {
return Integer.parseInt(readString());
}
long readLong() {
return Long.parseLong(readString());
}
double readDouble() {
return Double.parseDouble(readString());
}
int[] readIntArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = readInt();
}
return a;
}
public static void main(String[] args) {
//new Thread(null, new _Solution(), "", 128 * (1L << 20)).start();
new Problem().run();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
@Override
public void run() {
try {
timeBegin = System.currentTimeMillis();
init();
solve();
out.close();
time();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
int[][] dist;
int n, m;
private void solve() throws IOException {
n = readInt();
m = readInt();
int k=readInt();
dist = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
dist[i][j] = -1;
for (int i = 0; i < k; i++) {
dist[readInt()-1][readInt()-1]=0;
}
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
if (dist[i][j]==0)
bfs(i, j);
int max=0,X=0,Y=0;
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
if (dist[i][j]>=max){
max=dist[i][j];
X=i+1; Y=j+1;
}
out.println(X+" "+Y);
}
public void bfs(int x, int y) {
int[] dx = {0, 1, 0, -1};
int[] dy = {1, 0, -1, 0};
dist[x][y] = 0;
ArrayDeque<P> q = new ArrayDeque<>();
q.add(new P(x, y));
while (!q.isEmpty()) {
P v = q.poll();
for (int i = 0; i < 4; i++) {
int nx = v.x + dx[i];
int ny = v.y + dy[i];
if (inside(nx, ny) && (dist[nx][ny] == -1 || (dist[nx][ny] > dist[v.x][v.y] + 1&&dist[nx][ny]!=0))) {
q.add(new P(nx, ny));
dist[nx][ny] = dist[v.x][v.y] + 1;
}
}
}
}
public boolean inside(int x, int y) {
if (x < n && y < m && x >= 0 && y >= 0) {
return true;
}
return false;
}
}
class P {
int x, y;
public P(int x, int y) {
this.x = x;
this.y = y;
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class D implements Runnable {
public static void main(String[] args) {
new Thread(new D()).start();
}
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return "0";
}
}
return st.nextToken();
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.flush();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
static final double EPS = 1e-9;
static double qEq(double a, double b, double c) {
double d = b * b - 4 * a * c;
if (d < -EPS) {
return Double.NaN;
}
return Math.max((-b + Math.sqrt(d)) / (2 * a), (-b - Math.sqrt(d))
/ (2 * a));
}
static int compare(double a, double b) {
return Math.abs(a - b) < EPS ? 0 : Double.compare(a, b);
}
void solve() {
double a = nextDouble();
double v = nextDouble();
double l = nextDouble();
double d = nextDouble();
double w = nextDouble();
if (compare(w, v) >= 0) {
double t1 = v / a;
double d1 = a * t1 * t1 * .5;
if (compare(d1, l) >= 0) {
out.println(Math.sqrt(2 * l / a));
} else {
out.println(t1 + (l - d1) / v);
}
return;
}
double t1 = w / a;
double d1 = a * t1 * t1 * .5;
if (compare(d1, d) >= 0) {
double t2 = v / a;
double d2 = a * t2 * t2 * .5;
if (compare(d2, l) >= 0) {
out.println(Math.sqrt(2 * l / a));
} else {
out.println(t2 + (l - d2) / v);
}
return;
}
double left = d - d1;
double timeToV = (v - w) / a;
double distToV = a * timeToV * timeToV * .5 + w * timeToV;
// System.err.println(t1 + " " + left + " " + timeToV + " " + distToV
// + " " + d1);
if (compare(distToV, left * .5) >= 0) {
double t2 = qEq(a * .5, w, -left * .5);
// System.err.println(t2 + " " + (a * t2 * t2 * .5 + w * t2));
t2 += t1 + t2;
if (compare(distToV, l - d) >= 0) {
out.println(t2 + qEq(a * .5, w, d - l));
} else {
out.println(t2 + timeToV + (l - d - distToV) / v);
}
return;
}
double t2 = t1 + 2 * timeToV + (left - 2 * distToV) / v;
if (compare(distToV, l - d) >= 0) {
out.println(t2 + qEq(a * .5, w, d - l));
} else {
out.println(t2 + timeToV + (l - d - distToV) / v);
}
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
import static java.lang.Integer.*;
public class BDiv1 {
static int n;
static int a;
static int b;
static HashMap<Integer,Integer> graphA=new HashMap<>();
static HashMap<Integer,Integer> graphB=new HashMap<>();
static int [] array;
static int [] original;
static boolean x=true;
public static void main(String[] args) throws Exception{
BufferedReader buf =new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st =new StringTokenizer(buf.readLine());
n=parseInt(st.nextToken());
a=parseInt(st.nextToken());
b=parseInt(st.nextToken());
st =new StringTokenizer(buf.readLine());
array=new int[n];
original=new int [n];
for (int i=0;i<n;i++){
array[i]=parseInt(st.nextToken());
original[i]=array[i];
}
Arrays.sort(array);
for (int i=0;i<n;i++){
int k= Arrays.binarySearch(array,a-array[i]);
if (k>=0){
graphA.put(array[i],array[k]);
graphA.put(array[k],array[i]);
}
}
for (int i=0;i<n;i++){
int k= Arrays.binarySearch(array,b-array[i]);
if (k>=0){
graphB.put(array[i],array[k]);
graphB.put(array[k],array[i]);
}
}
for (int i=0;i<n;i++){
Integer j=graphA.get(array[i]);
if (j!=null){
if (graphB.containsKey(array[i]) && graphB.containsKey(j)){
graphA.remove(array[i]);
graphA.remove(j);
}
else if (graphB.containsKey(array[i]) && !graphB.containsKey(j)){
graphB.remove(graphB.get(array[i]));
graphB.remove(array[i]);
}
else if (!graphB.containsKey(array[i]) && graphB.containsKey(j)){
graphB.remove(graphB.get(j));
graphB.remove(j);
}
}
}
int [] res=new int [n];
for (int i=0;i<n;i++){
if (graphA.containsKey(original[i]))res[i]=0;
else if (graphB.containsKey(original[i])) res[i]=1;
else {
System.out.println("NO");
return;
}
}
System.out.println("YES");
for (int k:res)System.out.print(k+" ");
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
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();
char[] poks = in.next().toCharArray();
boolean[] was = new boolean[52];
for (int i = 0; i < n; i++) {
if (Character.isLowerCase(poks[i])) {
was[poks[i] - 'a'] = true;
} else {
was[poks[i] - 'A' + 26] = true;
}
}
int count = 0;
for (int i = 0; i < 52; i++) {
count += was[i] ? 1 : 0;
}
int[] vis = new int[52];
int pre = 0;
int chr = 0;
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int pos = poks[i] - 'a';
if (Character.isUpperCase(poks[i])) {
pos = poks[i] - 'A' + 26;
}
if (vis[pos] == 0) {
chr++;
}
vis[pos]++;
while (chr == count) {
ans = Math.min(ans, i - pre + 1);
pos = poks[pre] - 'a';
if (Character.isUpperCase(poks[pre])) {
pos = poks[pre] - 'A' + 26;
}
vis[pos]--;
if (vis[pos] == 0) chr--;
pre++;
}
}
out.println(ans);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
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());
}
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
/**
* Codeforces Beta Round 16
*
* @author ProjectYoung
*/
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 CF16E {
private void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
double[][] prob = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
prob[i][j] = in.nextDouble();
}
}
int[] fish = new int[n];
for (int i = 0; i < n; i++) {
fish[i] = 1 << i;
}
double[] res = new double[1 << n];
res[0] = 1.0;
for (int mask = 1; mask < (1 << n) - 1; mask++) {
for (int i = 0; i < n; i++) {
if ((mask & fish[i]) == 0) {
continue;
}
int lastMask = mask ^ fish[i];
int live = n;
for (int j = 0; j < n; j++) {
if ((lastMask & fish[j]) != 0) {
live--;
}
}
double p = 0.0;
for (int j = 0; j < n; j++) {
if ((lastMask & fish[j]) != 0 || j == i) {
continue;
}
p += prob[j][i];
}
res[mask] += res[lastMask] * p * 2 / live / (live - 1);
}
}
for (int i = 0; i < n; i++) {
out.printf("%.6f ", res[((1 << n) - 1) ^ fish[i]]);
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
new CF16E().solve(in, out);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
static int m;
static long pow(long b, int p) {
long ret = 1;
while (p > 0) {
if ((p&1) == 1) ret = b*ret%m;
b = b*b%m;
p >>= 1;
}
return ret;
}
public static void main(String[] args) throws IOException {
int n = readInt(); m = readInt();
long[] fac = new long[n + 1], pow2 = new long[n + 1];
long[][] C = new long[n + 1][n + 1], dp = new long[n + 1][n + 1];
fac[0] = pow2[0] = 1;
for (int i = 1; i <= n; ++i) {
fac[i] = i*fac[i - 1]%m;
pow2[i] = 2*pow2[i - 1]%m;
for (int j = 0; j <= i; ++j)
C[i][j] = fac[i]*(pow(fac[j], m - 2)*pow(fac[i - j], m - 2)%m)%m;
}
for (int i = 1; i <= n; ++i) {
dp[i][i] = pow2[i - 1];
for (int j = 0; j <= i; ++j)
for (int k = 1; i + k + 1 <= n; ++k)
dp[i + k + 1][j + k] = (dp[i + k + 1][j + k] + dp[i][j]*(C[j + k][k]*pow2[k - 1]%m))%m;
}
long ans = 0;
for (int i = 1; i <= n; ++i)
ans = (ans + dp[n][i])%m;
System.out.println(ans);
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author gaidash
*/
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) {
final int SIZE = 256;
final int UNDEF = -1;
int nPixels = in.nextInt();
int groupSize = in.nextInt();
int[] a = in.nextIntArray(nPixels);
boolean[] exists = new boolean[SIZE];
int[] left = new int[SIZE];
int[] right = new int[SIZE];
int[] ret = new int[nPixels];
Arrays.fill(ret, UNDEF);
for (int i = 0; i < nPixels; i++) {
for (int p = 0; p < SIZE; p++) {
if (exists[p] && left[p] <= a[i] && a[i] <= right[p]) {
ret[i] = left[p];
left[a[i]] = left[p];
right[a[i]] = right[p];
break;
}
}
if (ret[i] == UNDEF) {
int l = Math.max(a[i] - groupSize + 1, 0);
int r = l + groupSize - 1;
for (int p = a[i] - 1; p >= 0; p--) {
if (exists[p]) {
if (p >= l) {
int d = p - l;
l = p + 1;
r += d + 1;
}
if (right[p] >= l) {
right[p] = l - 1;
}
}
}
for (int p = a[i] + 1; p < SIZE; p++) {
if (exists[p] && left[p] <= r) {
r = left[p] - 1;
}
}
left[a[i]] = l;
right[a[i]] = r;
ret[i] = l;
}
exists[a[i]] = true;
}
// for (int p : a) {
// System.out.println("Segment for pixel " + p + " = " + "(" + left[p] + " , " + right[p] + ")");
// }
out.print(ret);
}
}
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(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
quadratic
|
980_C. Posterized
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class CC {
public static void main(String[] args)throws Throwable {
MyScanner sc=new MyScanner();
PrintWriter pw=new PrintWriter(System.out);
n=sc.nextInt();
s=new char [n];
for(int i=0;i<n;i++)
s[i]=sc.next().charAt(0);
mem=new int [2*n+1][n+1];
for(int [] x : mem)
Arrays.fill(x, -1);
pw.println(dp(0, 0));
pw.flush();
pw.close();
}
static int n;
static char [] s;
static int [][] mem;
static int dp(int i,int j){
if(i==n)
return j==0? 1 : 0;
if(mem[i][j]!=-1)
return mem[i][j];
int ans=0;
if(s[i]=='f'){
ans+=dp(i+1, j+1);
ans%=mod;
}else{
ans+=dp(i+1, j);
ans%=mod;
if(j>0){
ans+=dp(i, j-1);
ans%=mod;
}
}
return mem[i][j]=ans;
}
static int mod=(int)(1e9+7);
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
|
909_C. Python Indentation
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.