src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
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;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int l, r, sum = 0;
int[] a = new int[n+5];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
if (a[i] > a[j]) sum++;
int q = in.nextInt();
while (q-- > 0){
l = in.nextInt();
r = in.nextInt();
sum += (r-l+1)/2;
if (sum % 2 == 1) out.println("odd");
else out.println("even");
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.Scanner;
public class R025A {
int n;
int[] nums;
public R025A() {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
nums = new int[n];
for(int i=0; i<n; i++) {
nums[i] = scanner.nextInt();
}
}
private void process() {
int odd = 0;
int even = 0;
int lastOdd = 0;
int lastEven = 0;
for(int i=0; i<n; i++) {
if(nums[i] % 2 == 0) {
even++;
lastEven = i+1;
} else {
odd++;
lastOdd = i+ 1;
}
}
if(odd == 1) System.out.println(lastOdd);
else System.out.println(lastEven);
}
public static void main(String[] args) {
new R025A().process();
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.StringTokenizer;
public class CF {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n=sc.nextInt();
pw.print(n+n/2);
pw.close();
sc.close();
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
/*
* Code Author: Sanket Udgirkar.
* DA-IICT
*/
import java.util.*;
import java.io.*;
public class Tester
{
public static long mod=(long)1e9+7;
public static void main(String[] args)
{
InputReader s=new InputReader(System.in);
OutputStream outputStream = System.out;
//PrintWriter out=new PrintWriter(outputStream);
String str=s.nextLine();
System.out.println("25");
//out.close();
}
static long gcd(long a,long b)
{
if(b==0)
return a;
a%=b;
return gcd(b,a);
}
static long exp(long a, long b)
{
if(b==0)
return 1;
if(b==1)
return a;
if(b==2)
return a*a;
if(b%2==0)
return exp(exp(a,b/2),2);
else
return a*exp(exp(a,(b-1)/2),2);
}
static class Pair implements Comparable<Pair>
{
long x,f;
Pair(long ii, long cc)
{
x=ii;
f=cc;
}
public int compareTo(Pair o)
{
return Long.compare(this.x, o.x);
}
}
public static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream)
{
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine()
{
String fullLine=null;
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try {
fullLine=reader.readLine();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
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.lang.reflect.Array;
import java.text.DecimalFormat;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.io.InputStream;
public class BuildIn {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
public static void solve(InputReader in, PrintWriter out) throws IOException
{
int n = in.nextInt();
int[] list = new int[n];
for(int i = 0; i < n; i++)
{
list[i]=in.nextInt();
}
int count = 0;
for(int i = 0; i < n-1; i++)
{
for(int j = i+1; j < n; j++)
{
if(list[j]<list[i])
{
count++;
}
}
}
boolean sta = true;
if(count%2==1) sta = false;
int m = in.nextInt();
for(int i = 0; i <m; i++)
{
int a = in.nextInt();
int b = in.nextInt();
if((b-a)%4==2) sta = !sta;
if((b-a)%4==1) sta = !sta;
if(sta) out.println("even");
else out.println("odd");
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.*;
import java.lang.*;
import java.util.*;
import static java.lang.Integer.*;
import static java.lang.Long.*;
import static java.lang.Math.*;
import static java.lang.System.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main {
Main() throws IOException {
String a = nextLine();
String b = nextLine();
long ans = 0;
int s = 0;
for (int i = 0; i < b.length() - a.length(); ++i) {
s += b.charAt(i) == '1' ? 1 : 0;
}
for (int i = 0; i < a.length(); ++i) {
s += b.charAt(i + b.length() - a.length()) == '1' ? 1 : 0;
ans += a.charAt(i) == '1' ? b.length() - a.length() + 1 - s : s;
s -= b.charAt(i) == '1' ? 1 : 0;
}
out.println(ans);
}
//////////////////////////////
PrintWriter out = new PrintWriter(System.out, false);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer stok = null;
String nextLine() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
stok = new StringTokenizer(in.readLine());
}
return stok.nextToken();
}
public static void main(String args[]) throws IOException {
if (args.length > 0) {
setIn(new FileInputStream(args[0] + ".inp"));
setOut(new PrintStream(args[0] + ".out"));
}
Main solver = new Main();
solver.out.flush(); // could be replace with a method, but nah, this is just competitive programming :p
}
}
|
linear
|
608_B. Hamming Distance Sum
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.HashMap;
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 programajor
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
String x = in.next();
map.put(x, map.getOrDefault(x, 0) + 1);
}
int ans = 0;
for (int i = 0; i < n; i++) {
String x = in.next();
if (map.containsKey(x)) {
map.put(x, map.get(x) - 1);
if (map.get(x) == 0) {
map.remove(x);
}
} else {
ans++;
}
}
out.print(ans);
}
}
static class InputReader {
private BufferedReader reader;
private 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());
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.math.*;
public class A {
Scanner sc = new Scanner(System.in);
void run(){
String s = sc.next();
String subS;
int max = 0;
for (int i=0;i<s.length();i++) {
for (int j=i+1;j<s.length()+1;j++) {
subS = s.substring(i, j);
for (int k=i+1;k<s.length();k++) {
if ( s.startsWith(subS,k) ){
if ( max < subS.length() )
max = subS.length();
}
}
}
}
System.out.println(max);
return;
}
public static void main(String[] args){
new A().run();
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class C {
public static int mod = 1000000000 + 7;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String n = br.readLine();
int k = Integer.parseInt(br.readLine());
int l = n.length();
if(k == 0) {
System.out.println(1);
}else {
int max = 1000;
if (l <= 10) {
max = Integer.min(1000, Integer.parseInt(n, 2));
}
int[] steps = new int[max + 1];
for (int i = 2; i <= max; i++) {
int ones = numberOfOnes(i);
steps[i] = 1 + steps[ones];
}
if (l <= 10) {
int ans = 0;
for (int i = 1; i <= max; i++) {
if (steps[i] == k) {
ans++;
}
}
System.out.println(ans);
} else {
int[][] C = binomial(max);
int ans = 0;
int count = 0;
for (int i = 0; i < l; i++) {
if (n.charAt(i) == '1') {
for (int j = count; j < max; j++) {
if (steps[j] == k - 1) {
ans = (ans + C[l - i - 1][j - count]) % mod;
if (i == 0 && k == 1) {
ans = (ans + mod - 1) % mod;
}
}
}
count++;
}
}
int ones = 0;
for (int i = 0; i < l; i++) {
if (n.charAt(i) == '1') {
ones++;
}
}
if (steps[ones] == k-1) {
ans = (ans + 1) % mod;
}
System.out.println(ans);
}
}
}
public static int numberOfOnes(int x) {
char[] s = Integer.toBinaryString(x).toCharArray();
int count = 0;
for (char c : s) {
if (c == '1') {
count++;
}
}
return count;
}
public static int[][] binomial(int n) {
int[][] C = new int[n + 1][n + 1];
for (int i = 0; i <= n; i++) {
C[i][0] = 1;
for (int j = 1; j <= i; j++) {
C[i][j] = ((C[i - 1][j - 1] % mod) + (C[i - 1][j] % mod)) % mod;
}
}
return C;
}
}
|
linear
|
914_C. Travelling Salesman and Special Numbers
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
String str=in.next();
int cnt=0;
for(int i=0;i<str.length();++i) {
if(str.charAt(i)=='1') {
++cnt;
}
}
int i=0;
for(;i<str.length();++i) {
if(str.charAt(i)=='0') {
System.out.print("0");
}
else if(str.charAt(i)=='2') {
while(cnt-->0) {//
System.out.print("1");
}
System.out.print("2");
}
}
while(cnt-->0) {
System.out.print("1");
}
in.close();
}
}
|
linear
|
1009_B. Minimum Ternary String
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args){
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt(), r = scan.nextInt();
int[] x = scan.nextIntArray(n);
double[] y = new double[n];
for(int i = 0; i < n; i++) {
double best = 0;
for(int j = 0; j < i; j++) {
if(Math.abs(dist(x[i], y[j], x[j], y[j])-2*r) <= 1e-7) {
best = Math.max(best, y[j]);
continue;
}
double lo = y[j]-r-r, hi = y[j]+r+r;
for(int bs = 0; bs < 200; bs++) {
double mid = (lo+hi)/2.0;
if(dist(x[i], mid, x[j], y[j])-2*r <= 1e-7) lo = mid;
else hi = mid;
}
if(dist(x[i], lo, x[j], y[j])-2*r <= 1e-7) best = Math.max(best, lo);
}
if(best == 0) y[i] = r;
else y[i] = best;
}
for(int i = 0; i < n; i++) out.printf("%.6f ", y[i]);
out.close();
}
static double dist(double x, double y, double xx, double yy) {return Math.sqrt((x-xx)*(x-xx)+(y-yy)*(y-yy));}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n){
long[] a = new long[n];
for(int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public double[] nextDoubleArray(int n){
double[] a = new double[n];
for(int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public char[][] nextGrid(int n, int m){
char[][] grid = new char[n][m];
for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
return grid;
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
for (int i = 0; i < n; i++) b[i] = sc.nextInt();
int c[] = new int[2 * n];
c[0] = a[0];
for (int i = 1; i < n; i++) {
c[i * 2] = a[i];
c[i * 2 - 1] = b[i];
if (a[i] == 1 || b[i] == 1) {
System.out.print(-1);
System.exit(0);
}
}
c[2 * n - 1] = b[0];
if (a[0] == 1 || b[0] == 1) {
System.out.print(-1);
System.exit(0);
}
System.out.println(bin_search(c, m));
}
private static double bin_search(int[] c, int m) {
double start = 0;
double end = Integer.MAX_VALUE;
double mid;
while (start + 0.0000001 < end) {
mid = (start + end) / 2;
if (test(mid, m, c)) end = mid;
else start = mid;
}
return end;
}
private static boolean test(double fuel, int m, int[] c) {
for (int i = 0; i < c.length; i++) {
fuel -= (m + fuel) / c[i];
if (fuel < 0) {
return false;
}
}
return true;
}
}
|
nlogn
|
1010_A. Fly
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A implements Runnable {
public static void main(String[] args) {
new A().run();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
boolean eof;
String buf;
public FastScanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
nextToken();
}
public FastScanner(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
nextToken();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
break;
}
}
String ret = buf;
buf = eof ? "-1" : st.nextToken();
return ret;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
void close() {
try {
br.close();
} catch (Exception e) {
}
}
boolean isEOF() {
return eof;
}
}
FastScanner sc;
PrintWriter out;
public void run() {
Locale.setDefault(Locale.US);
try {
sc = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
sc.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() {
return sc.nextInt();
}
String nextToken() {
return sc.nextToken();
}
long nextLong() {
return sc.nextLong();
}
double nextDouble() {
return sc.nextDouble();
}
void solve() {
String s = nextToken();
for (int len = s.length(); len >= 1; len--) {
for (int i = 0; i + len <= s.length(); i++) {
int cnt = 0;
for (int j = 0; j + len <= s.length(); j++) {
boolean ok = true;
for (int k = 0; k < len; k++) {
if (s.charAt(i + k) != s.charAt(j + k)) {
ok = false;
break;
}
}
if (ok) {
cnt++;
}
}
if (cnt > 1) {
out.println(len);
return;
}
}
}
out.println(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.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 Alex
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
int n;
int startrow;
int startcol;
long want;
boolean check(long time) {
long max = (long) 2 * time * (time + 1) + 1;
long highest = startrow - time;
if(highest < 0) {
max -= Math.abs(highest) * Math.abs(highest);
}
long lowest = startrow + time;
if(lowest >= n) {
max -= Math.abs(lowest - n + 1) * Math.abs(lowest - n + 1);
}
long leftmost = startcol - time;
if(leftmost < 0) {
max -= Math.abs(leftmost) * Math.abs(leftmost);
}
long rightmost = startcol + time;
if(rightmost >= n) {
max -= Math.abs(rightmost - n + 1) * Math.abs(rightmost - n + 1);
}
long upperright = time - (startrow + 1) - (n - startcol);
if(upperright >= 0) {
max += (upperright + 1) * (upperright + 2) / 2;
}
long lowerright = time - (n - startrow) - (n - startcol);
if(lowerright >= 0) {
max += (lowerright + 1) * (lowerright + 2) / 2;
}
long upperleft = time - (startrow + 1) - (startcol + 1);
if(upperleft >= 0) {
max += (upperleft + 1) * (upperleft + 2) / 2;
}
long lowerleft = time - (n - startrow) - (startcol + 1);
if(lowerleft >= 0) {
max += (lowerleft + 1) * (lowerleft + 2) / 2;
}
return max >= want;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
startrow = in.readInt() - 1;
startcol = in.readInt() - 1;
want = in.readLong();
long low = 0, high = 2 * n;
while(low < high) {
long mid = (low + high) / 2;
if(check(mid)) high = mid;
else low = mid + 1;
}
out.printLine(low);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if(numChars == -1)
throw new InputMismatchException();
if(curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch(IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if(c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while(!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if(c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if(c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while(!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if(filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
}
|
logn
|
256_B. Mr. Bender and Square
|
CODEFORCES
|
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
long x=nl(),k=nl();
if(x==0) {
pw.println(0);
return;
}
long d=modpow(2,k,M);
long ans=mul(2,d,M);
ans=mul(ans,x,M)%M;
ans++;
ans%=M;
ans=(ans-d+M)%M;
pw.println(ans);
}
// long mul(long a, long b,long M)
// {
// return (a*1L*b)%M;
// }
long mul(long x, long y, long m) {
long ans = 0;
while (y>0) {
if ((y & 1)>0) {
ans += x;
if (ans >= m) ans -= m;
}
x = x + x;
if (x >= m) x -= m;
y >>= 1;
}
return ans;
}
long modpow(long a, long b,long M)
{
long r=1;
while(b>0)
{
if((b&1)>0) r=mul(r,a,M);
a=mul(a,a,M);
b>>=1;
}
return r;
}
long M=(long)1e9+7;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Main().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
public static void main(String[] args) /*throws FileNotFoundException*/ {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA{
static boolean twofind(String s, String t){
int index = s.indexOf(t);
int index2 = s.indexOf(t, index + 1);
if(index2 != -1)return true;
return false;
}
public void solve(int testNumber, FastScanner scan, FastPrinter out) /*throws FileNotFoundException*/ {
//Scanner sscan = new Scanner(new File("input.txt"));
//PrintStream oout = new PrintStream(new File("output.txt"));
String s = scan.next();
String ans = "";
boolean ok = false;
for(int i = s.length(); i >= 0; i--){
for(int j = 0; j <= s.length() - 1; j++){
try{
if(twofind(s, s.substring(j, j + i))){
ans = s.substring(j, j + i); break;
}
}catch(Exception e){
break;
}
}
if(!ans.equals(""))break;
}
out.println(ans.length());
//sscan.close();
//oout.close();
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try{
int ret = super.read();
return ret;
}catch(Exception e){
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
if (c < 0) {
return null;
}
while (c >= 0 && !isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public long nextLong() {
return Long.parseLong(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
public BigDecimal nextBigDecimal(){
return new BigDecimal(next());
}
public String readLine(){
try{
return super.readLine();
}catch(IOException e){
return null;
}
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[][] x = new int [200010][10];
String a = sc.nextLine();
String b = sc.nextLine();
int n = a.length();
int m = b.length();
for (int i = 1; i <= m; i++) {
for (int j = 0; j < 2; j++) {
x[i][j] = x[i - 1][j];
}
++x[i][b.charAt(i - 1) - '0'];
}
long res = 0;
for (int i = 0, c; i < n; i++) {
c = a.charAt(i) - '0';
for (int j = 0; j < 2; j++) {
res += Math.abs(c - j) * (x[m - n + i + 1][j] - x[i][j]);
}
}
System.out.println(res);
}
}
|
linear
|
608_B. Hamming Distance Sum
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Scanner;
public class D {
public static void main(String [] args){
Scanner cin = new Scanner(System.in);
PrintWriter cout = new PrintWriter(System.out);
long l = cin.nextLong(), r = cin.nextLong(), k = 1;
if (l == r)cout.println(0);
else {
while (((r>>k)<<k)>l)k++;k--;
cout.println(((r>>k)<<k)^(((r>>k)<<k)-1));
}
cout.flush();
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long k = sc.nextLong();
if ((k - 1) * k / 2 + 1 < n) {
System.out.println(-1);
return;
}
long left = 0;
long right = k;
while (left < right) {
long m = (left + right) / 2;
if (k * (k - 1)/2 - (k - m) * (k - m - 1) / 2 +1 < n)
left = m + 1;
else
right = m;
}
System.out.println(left);
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class A {
static MyScanner sc;
static PrintWriter pw;
public static void main(String[] args) throws Throwable {
sc = new MyScanner();
pw = new PrintWriter(System.out);
n = sc.nextInt();
T = sc.nextLong();
p = new int[n];
l = new int[n];
x = new int[n];
t = new int[n];
adj = new ArrayList[n];
for (int i = 0; i < n; i++)
x[i] = sc.nextInt();
for (int i = 0; i < n; i++)
t[i] = sc.nextInt();
adj[0] = new ArrayList<>();
for (int i = 1; i < n; i++) {
adj[i] = new ArrayList<>();
p[i] = sc.nextInt() - 1;
l[i] = sc.nextInt();
adj[p[i]].add(i);
}
ftCnt = new long[N];
ftSum = new long[N];
ans = new long[n];
dfs(0);
pw.println(ans[0]);
pw.flush();
pw.close();
}
static int n;
static long T;
static int[] p, l, x, t;
static ArrayList<Integer>[] adj;
static long[] ans;
static void dfs(int u) {
update(t[u], x[u], 1L * x[u] * t[u]);
ans[u] = getMaxCnt();
long[] vals = {-1, -1, -1};
for (int v : adj[u]) {
T -= 2 * l[v];
dfs(v);
vals[0] = ans[v];
Arrays.sort(vals);
T += 2 * l[v];
}
if (u != 0) {
if (vals[1] != -1)
ans[u] = Math.max(ans[u], vals[1]);
} else {
if (vals[2] != -1)
ans[u] = Math.max(ans[u], vals[2]);
}
update(t[u], -x[u], -1L * x[u] * t[u]);
}
static int N = (int) 1e6 + 2;
static long[] ftCnt, ftSum;
static void update(int idx, long cnt, long val) {
while (idx < N) {
ftCnt[idx] += cnt;
ftSum[idx] += val;
idx += (idx & -idx);
}
}
static long getSum(int idx) {
long ret = 0;
while (idx > 0) {
ret += ftSum[idx];
idx -= (idx & -idx);
}
return ret;
}
static long getCnt(int idx) {
long ret = 0;
while (idx > 0) {
ret += ftCnt[idx];
idx -= (idx & -idx);
}
return ret;
}
static long getMaxCnt() {
int start = 1, end = N - 1, ans = N - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (getSum(mid) >= T) {
ans = mid;
end = mid - 1;
} else
start = mid + 1;
}
long remT = T - (ans > 1 ? getSum(ans - 1) : 0);
long cnt = (ans > 1 ? getCnt(ans - 1) : 0);
long cntOfVal = getCnt(ans) - cnt;
cnt += Math.min(cntOfVal, remT / ans);
return cnt;
}
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;
}
}
}
|
nlogn
|
1099_F. Cookies
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class _8C {
static int[] x = new int[30], y = new int[30];
static int[][] dist = new int[30][30];
static int n;
static final int M = 1000;
static int[] bitPos = new int[M];
static {
Arrays.fill(bitPos, -1);
for (int i=0; i<24; i++)
bitPos[(1 << i) % M] = i;
}
static int sqr(int i) {
return i * i;
}
public static void main(String[] args) throws Exception {
Reader.init(System.in);
BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));
x[0] = Reader.nextInt();
y[0] = Reader.nextInt();
n = Reader.nextInt();
for (int i=1; i<=n; i++) {
x[i] = Reader.nextInt();
y[i] = Reader.nextInt();
}
for (int i=0; i<=n; i++)
for (int j=0; j<=n; j++)
dist[i][j] = sqr(x[i] - x[j]) + sqr(y[i] - y[j]);
int[] f = new int[1 << n];
int[] r = new int[1 << n];
for (int mask=1; mask<(1 << n); mask++) {
int lowbit = mask & -mask;
int lowbitPos = bitPos[lowbit % M];
f[mask] = dist[lowbitPos + 1][0] * 2 + f[mask ^ lowbit];
r[mask] = lowbit;
for (int i=mask^(lowbit); i>0; i=i^(i & -i)) {
int otherBit = i & -i;
int otherBitPos = bitPos[otherBit % M];
int tmp = dist[0][lowbitPos + 1] + dist[lowbitPos + 1][otherBitPos + 1] + dist[otherBitPos + 1][0] + f[mask ^ otherBit ^ lowbit];
if (tmp < f[mask]) {
f[mask] = tmp;
r[mask] = lowbit | otherBit;
}
}
}
System.out.println(f[(1 << n) - 1]);
int mask = (1 << n) - 1;
while(mask > 0) {
if ((r[mask] ^ (r[mask] & -r[mask])) == 0) {
System.out.print("0 " + (bitPos[r[mask] % M] + 1) + " ");
}
else {
int bit1 = r[mask] & -r[mask];
int bit2 = r[mask] ^ bit1;
System.out.print("0 " + (bitPos[bit1 % M] + 1) + " " + (bitPos[bit2 % M] + 1) + " ");
}
mask ^= r[mask];
}
System.out.println("0");
cout.close();
}
static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
final U _1;
final V _2;
private Pair(U key, V val) {
this._1 = key;
this._2 = val;
}
public static <U extends Comparable<U>, V extends Comparable<V>> Pair<U, V> instanceOf(U _1, V _2) {
return new Pair<U, V>(_1, _2);
}
@Override
public String toString() {
return _1 + " " + _2;
}
@Override
public int hashCode() {
int res = 17;
res = res * 31 + _1.hashCode();
res = res * 31 + _2.hashCode();
return res;
}
@Override
public int compareTo(Pair<U, V> that) {
int res = this._1.compareTo(that._1);
if (res < 0 || res > 0)
return res;
else
return this._2.compareTo(that._2);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Pair))
return false;
Pair<?, ?> that = (Pair<?, ?>) obj;
return _1.equals(that._1) && _2.equals(that._2);
}
}
/** Class for buffered reading int and double values */
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
// TODO add check for eof if necessary
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 class ArrayUtil {
static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(long[] a, int i, int j) {
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(double[] a, int i, int j) {
double tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(char[] a, int i, int j) {
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(boolean[] a, int i, int j) {
boolean tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void reverse(int[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(long[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(double[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(char[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(boolean[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static long sum(int[] a) {
int sum = 0;
for (int i : a)
sum += i;
return sum;
}
static long sum(long[] a) {
long sum = 0;
for (long i : a)
sum += i;
return sum;
}
static double sum(double[] a) {
double sum = 0;
for (double i : a)
sum += i;
return sum;
}
static int max(int[] a) {
int max = Integer.MIN_VALUE;
for (int i : a)
if (i > max)
max = i;
return max;
}
static int min(int[] a) {
int min = Integer.MAX_VALUE;
for (int i : a)
if (i < min)
min = i;
return min;
}
static long max(long[] a) {
long max = Long.MIN_VALUE;
for (long i : a)
if (i > max)
max = i;
return max;
}
static long min(long[] a) {
long min = Long.MAX_VALUE;
for (long i : a)
if (i < min)
min = i;
return min;
}
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author EndUser
*/
public class R455D2PC {
public static void main(String[] args) {
final int MAX = 5000;
final int MODULO = 1000000007;
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
int pre = 0;
int size = 0;
int[] block = new int[MAX];
for (int i = 0; i < n; i++) {
String command = in.nextLine();
if (command.startsWith("s")) {
block[size++] = pre;
pre = 0;
} else {
pre++;
}
}
if (pre != 0) {
System.out.println(0);
return;
}
int[][] result = new int[2][MAX + 1];
int currentMax = 0;
int preIndex = 0;
result[preIndex][0] = 1;
for (int i = 1; i < size; i++) {
int currentIndex = preIndex ^ 1;
int j = block[i - 1];
for (int k = currentMax; k >= 0; k--) {
result[currentIndex][k + j] = (result[currentIndex][k + j + 1] + result[preIndex][k]) % MODULO;
}
for (int k = j - 1; k >= 0; k--) {
result[currentIndex][k] = result[currentIndex][j];
}
currentMax += j;
preIndex = currentIndex;
// for (int k = 0; k <= currentMax; k++) {
// System.out.print(result[preIndex][k] + " ");
//
// }
// System.out.println("");
}
int sum = 0;
for (int i = 0; i <= currentMax; i++) {
sum = (sum + result[preIndex][i]) % MODULO;
}
System.out.println(sum);
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.awt.Point;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Start {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
public static void main(String[] args) {
new Start().run();
}
public static void mergeSort(int[] a) {
mergeSort(a, 0, a.length - 1);
}
private static void mergeSort(int[] a, int levtIndex, int rightIndex) {
final int MAGIC_VALUE = 50;
if (levtIndex < rightIndex) {
if (rightIndex - levtIndex <= MAGIC_VALUE) {
insertionSort(a, levtIndex, rightIndex);
} else {
int middleIndex = (levtIndex + rightIndex) / 2;
mergeSort(a, levtIndex, middleIndex);
mergeSort(a, middleIndex + 1, rightIndex);
merge(a, levtIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int levtIndex, int middleIndex,
int rightIndex) {
int length1 = middleIndex - levtIndex + 1;
int length2 = rightIndex - middleIndex;
int[] levtArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, levtIndex, levtArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = levtIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = levtArray[i++];
} else {
a[k] = levtArray[i] <= rightArray[j] ? levtArray[i++]
: rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int levtIndex, int rightIndex) {
for (int i = levtIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= levtIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
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);
}
}
class LoL implements Comparable<LoL> {
int x;
int y;
public LoL(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(LoL arg0) {
if (arg0.x == x) {
return y - arg0.y;
}
return arg0.x - x;
}
}
public void solve() throws IOException {
int n = readInt();
int a = readInt()-1;
int b = readInt()-1;
int [] d = new int [n];
for (int i = 0; i <n; i++){
d[i] = readInt();
}
mergeSort(d);
out.print(d[b+1]-d[b]);
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class D {
public static int dir[][]={{-1,0},{1,0},{0,-1},{0,1}};
public static void main(String[] args) {
// Scanner sc=new Scanner(System.in);
FastScanner sc = new FastScanner();
FastOutput out = new FastOutput(System.out);
int n=sc.nextInt();
int m=sc.nextInt();
int k=sc.nextInt();
int ans[][][]=new int[n][m][11];
int arr[][]=new int[n*m][4];
for(int i=0;i<n;i++){
for(int j=0;j<m-1;j++){
int x=sc.nextInt();
arr[i*m+j][3]=x;
arr[i*m+j+1][2]=x;
}
}
for(int i=0;i<n-1;i++){
for(int j=0;j<m;j++){
int x=sc.nextInt();
arr[i*m+j][1]=x;
arr[(i+1)*m+j][0]=x;
}
}
if(k%2==1){
for(int i=0;i<n;i++){
StringBuilder sb=new StringBuilder("");
for(int j=0;j<m;j++){
ans[i][j][10]=-1;
sb.append(ans[i][j][10]+" ");
}
out.println(sb.toString());
}
}else{
for(int ceng=1;ceng<=k/2;ceng++){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
ans[i][j][ceng]=Integer.MAX_VALUE/3;
for(int dr=0;dr<4;dr++){
int nx=i+dir[dr][0];
int ny=j+dir[dr][1];
if(nx<n&&ny<m&&nx>=0&&ny>=0){
ans[i][j][ceng]=Math.min(ans[i][j][ceng], ans[nx][ny][ceng-1]+arr[i*m+j][dr]);
}
}
}
}
}
for(int i=0;i<n;i++){
StringBuilder sb=new StringBuilder("");
for(int j=0;j<m;j++){
sb.append(ans[i][j][k/2]*2+" ");
}
out.println(sb.toString());
}
}
out.close();
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readIntArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private static final int THRESHOLD = 1 << 13;
private final Writer os;
private StringBuilder cache = new StringBuilder(THRESHOLD * 2);
public FastOutput append(CharSequence csq) {
cache.append(csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append(csq, start, end);
return this;
}
private void afterWrite() {
if (cache.length() < THRESHOLD) {
return;
}
flush();
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput append(int c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput append(String c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput println(String c) {
return append(c).println();
}
public FastOutput println() {
return append(System.lineSeparator());
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author kessido
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
long MOD = MathExtentions.DEFAULT_MOD;
long x = in.NextLong();
long k = in.NextLong();
if (x == 0) {
out.println(0);
return;
}
x %= MOD;
long res = x * MathExtentions.powerMod(2, k + 1, MOD);
res %= MOD;
res -= MathExtentions.powerMod(2, k, MOD) - 1;
res %= MOD;
while (res < 0) res += MOD;
while (res >= MOD) res -= MOD;
out.println(res);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine(), " \t\n\r\f,");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long NextLong() {
return Long.parseLong(next());
}
}
static class MathExtentions {
public static final long DEFAULT_MOD = 1_000_000_007;
public static long powerMod(final long x, final long y, final long m) {
if (y == 0)
return 1;
long p = powerMod(x, y / 2, m) % m;
p = (p * p) % m;
if (y % 2 == 0)
return p;
else
return (x * p) % m;
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import static java.lang.Math.*;
import java.io.*;
import java.util.*;
public class A {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch(Exception e) {}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
boolean bit(int m, int i) {
return (m & (1 << i)) > 0;
}
int n, x, y, c;
long cnt(int m) {
long ret=0;
for (int i=max(1, y-m); i<=min(n, y+m); i++) {
int x1 = max(1, x - (m - abs(i - y)));
int x2 = min(n, x + (m - abs(i - y)));
ret += x2 - x1 + 1;
}
return ret;
}
public void run() {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
n = nextInt();
x = nextInt();
y = nextInt();
c = nextInt();
int l = 0, r = 1000000;
int ans=0;
while (l <= r) {
int m = (l+r) / 2;
if (cnt(m) >= c) {
ans = m;
r = m-1;
} else l=m+1;
}
out.println(ans);
out.close();
}
class Pair implements Comparable<Pair> {
long x,y;
public Pair(long x, long y) {
this.x=x;
this.y=y;
}
public int compareTo(Pair o) {
if (x != o.x) return sign(o.x - x);
return sign(y - o.y);
}
}
int sign(long x) {
if (x < 0) return -1;
if (x > 0) return 1;
return 0;
}
public static void main(String[] args) throws Exception {
new A().run();
}
}
|
logn
|
256_B. Mr. Bender and Square
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class BNew {
double gAns = 0;
public static void main(String[] args) throws IOException {
new BNew().solve();
}
private void solve() throws IOException {
MyScanner in = new MyScanner(new BufferedReader(new InputStreamReader(System.in)));
int n = in.nextInt();
int k = in.nextInt();
int A = in.nextInt();
List<Senator> allSenators = new ArrayList<Senator>();
for (int i = 0; i < n; i++) {
int level = in.nextInt();
int loyalty = in.nextInt();
allSenators.add(new Senator(level, loyalty));
}
allSenators = Collections.unmodifiableList(allSenators);
int npow2 = 1 << n;
rec(allSenators, 0, k, A);
for (int okSenatorMask = 0; okSenatorMask < npow2; okSenatorMask++) {
List<Senator> okSenators = copy(getSenatorsByMask(okSenatorMask, allSenators));
liftLeastSenators(okSenators, k);
List<Senator> updatedSenators = new ArrayList<Senator>(okSenators);
List<Senator> otherSenators = getSenatorsByMask(npow2 - 1 - okSenatorMask, allSenators);
updatedSenators.addAll(otherSenators);
check(updatedSenators, A);
}
in.close();
PrintWriter pw = new PrintWriter(System.out);
System.out.printf("%.6f\n", gAns);
pw.close();
}
private void rec(List<Senator> senators, int senatorId, int k, int A) {
if (senatorId == senators.size()) {
check(senators, A);
return;
}
Senator senator = senators.get(senatorId);
int up = Math.min(k, (100 - senator.loyalty) / 10);
final int old = senator.loyalty;
for (int i = 0; i <= up; i++) {
senator.loyalty = old + i * 10;
rec(senators, senatorId + 1, k - i, A);
}
senator.loyalty = old;
}
private void check(List<Senator> senators, double A) {
double winProp = 0.0;
for (int mask = 0; mask < 1 << senators.size(); mask++) {
double caseP = 1.0;
int okCnt = 0;
int notOkLevelSum = 0;
for (int i = 0; i < senators.size(); i++) {
Senator senator = senators.get(i);
double senatorLoyalty = senator.loyalty / 100.0;
boolean ok = (mask & (1 << i)) != 0;
if (ok) {
caseP *= senatorLoyalty;
okCnt++;
} else {
caseP *= (1 - senatorLoyalty);
notOkLevelSum += senator.level;
}
}
if (okCnt * 2 > senators.size()) {
winProp += caseP;
} else {
double killProp = A / (A + notOkLevelSum);
winProp += caseP * killProp;
}
}
gAns = Math.max(gAns, winProp);
}
List<Senator> copy(List<Senator> senators) {
List<Senator> copied = new ArrayList<Senator>();
for (Senator senator : senators) {
copied.add(new Senator(senator.level, senator.loyalty));
}
return copied;
}
void liftLeastSenators(List<Senator> senators, int k) {
if (senators.isEmpty()) {
return;
}
for (int i = 0; i < k; i++) {
Senator least = senators.get(0);
for (Senator senator : senators) {
if (senator.loyalty < least.loyalty) {
least = senator;
}
}
if (least.loyalty < 100) {
least.loyalty += 10;
}
}
}
List<Senator> getSenatorsByMask(int mask, List<Senator> allSenators) {
List<Senator> list = new ArrayList<Senator>();
for (int i = 0; i < allSenators.size(); i++) {
if ((mask & (1 << i)) != 0) {
list.add(allSenators.get(i));
}
}
return list;
}
static class Senator {
final int level;
int loyalty;
Senator(int level, int loyalty) {
this.level = level;
this.loyalty = loyalty;
}
@Override
public String toString() {
return "{" +
"level=" + level +
", loyalty=" + loyalty +
'}';
}
}
static class MyScanner {
final BufferedReader myBr;
StringTokenizer st = new StringTokenizer("");
MyScanner(BufferedReader br) {
myBr = br;
}
String nextToken() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(myBr.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
void close() throws IOException {
myBr.close();
}
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
int size= Integer.parseInt(r.readLine());
String line = r.readLine();
int counter =0;
for (int i = 0; i < line.length(); i++) {
if(line.charAt(i)=='H')counter++;
}
int minimum = Integer.MAX_VALUE;
for (int i = 0; i < line.length(); i++) {
if(line.charAt(i)=='H'){
int current = 0;
for (int j = i; j < i+counter; j++) {
if(line.charAt(j%line.length())=='T')current++;
}
minimum = Math.min(current, minimum);
}
}
System.out.println(minimum);
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.util.*;
import java.lang.Math;
public class Main{
public static void main(String[] args){
Scanner ak=new Scanner(System.in);
long n,k,x;
n=ak.nextLong();
k=ak.nextLong();
x=(long)((-3+Math.sqrt(9+8*(n+k)))/2);
System.out.println(n-x);
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Dzmitry Paulenka
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, Scanner in, PrintWriter out) {
long n = in.nextLong();
long k = in.nextLong();
if (n == 1) {
out.println(0);
return;
}
if (k * (k - 1) < 2 * (n - 1)) {
out.println(-1);
return;
}
long sq2 = 4 * k * k - 4 * k + 1 - 4 * (2 * n - 2);
long km = Math.max(2, (long) ((Math.sqrt(sq2) + 3) / 2.0) - 3);
while (((km + k - 2)*(k - km + 1) >= 2*(n-1))) {
++km;
}
out.println(k - km + 2);
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Solver {
StringTokenizer st;
BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws NumberFormatException, IOException {
Solver solver = new Solver();
solver.open();
solver.solve();
solver.close();
}
public void open() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
public String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
public class result implements Comparable{
public int t = 0;
public int p = 0;
public result(int p,int t){
this.t = t;
this.p = p;
}
@Override
public int compareTo(Object o) {
result r = (result)o;
int out = r.p-p;
if (out==0) out = t-r.t;
return out;
}
}
public void solve() throws NumberFormatException, IOException {
int n = nextInt();
int k = nextInt();
result[] table = new result[n];
for (int i=0;i<n;i++){
int p = nextInt();
int t = nextInt();
table[i] = new result(p,t);
}
Arrays.sort(table);
int result = 1;
k--;
for (int i=k-1;i>=0 && table[i].p==table[k].p && table[i].t==table[k].t;i--){
result++;
}
for (int i=k+1;i<n && table[i].p==table[k].p && table[i].t==table[k].t;i++){
result++;
}
out.println(result);
}
public void close() {
out.flush();
out.close();
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class C {
public static int mod = 1000000000 + 7;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String n = br.readLine();
int k = Integer.parseInt(br.readLine());
int l = n.length();
if(k == 0) {
System.out.println(1);
}else {
int max = 1000;
if (l <= 10) {
max = Integer.min(1000, Integer.parseInt(n, 2));
}
int[] steps = new int[max + 1];
for (int i = 2; i <= max; i++) {
int ones = numberOfOnes(i);
steps[i] = 1 + steps[ones];
}
if (l <= 10) {
int ans = 0;
for (int i = 1; i <= max; i++) {
if (steps[i] == k) {
ans++;
}
}
System.out.println(ans);
} else {
int[][] C = binomial(max);
int ans = 0;
int count = 0;
for (int i = 0; i < l; i++) {
if (n.charAt(i) == '1') {
for (int j = count; j < max; j++) {
if (steps[j] == k - 1) {
ans = (ans + C[l - i - 1][j - count]) % mod;
if (i == 0 && k == 1) {
ans = (ans + mod - 1) % mod;
}
}
}
count++;
}
}
int ones = 0;
for (int i = 0; i < l; i++) {
if (n.charAt(i) == '1') {
ones++;
}
}
if (steps[ones] == k-1) {
ans = (ans + 1) % mod;
}
System.out.println(ans);
}
}
}
public static int numberOfOnes(int x) {
char[] s = Integer.toBinaryString(x).toCharArray();
int count = 0;
for (char c : s) {
if (c == '1') {
count++;
}
}
return count;
}
public static int[][] binomial(int n) {
int[][] C = new int[n + 1][n + 1];
for (int i = 0; i <= n; i++) {
C[i][0] = 1;
for (int j = 1; j <= i; j++) {
C[i][j] = ((C[i - 1][j - 1] % mod) + (C[i - 1][j] % mod)) % mod;
}
}
return C;
}
}
|
linear
|
914_C. Travelling Salesman and Special Numbers
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.util.*;
import java.lang.*;
import java.util.HashMap;
import java.util.PriorityQueue;
public class templ implements Runnable{
static class pair implements Comparable
{
int f;
int s;
pair(int fi,int se)
{
f=fi;
s=se;
}
public int compareTo(Object o)//ascending order
{
pair pr=(pair)o;
if(s>pr.s)
return 1;
if(s==pr.s)
{
if(f>pr.f)
return 1;
else
return -1;
}
else
return -1;
}
public boolean equals(Object o)
{
pair ob=(pair)o;
int ff;
int ss;
if(o!=null)
{
ff=ob.f;
ss=ob.s;
if((ff==this.f)&&(ss==this.s))
return true;
}
return false;
}
public int hashCode()
{
return (this.f+" "+this.s).hashCode();
}
}
public class triplet implements Comparable
{
int f,t;
int s;
triplet(int f,int s,int t)
{
this.f=f;
this.s=s;
this.t=t;
}
public boolean equals(Object o)
{
triplet ob=(triplet)o;
int ff;
int ss;
int tt;
if(o!=null)
{
ff=ob.f;
ss=ob.s;
tt=ob.t;
if((ff==this.f)&&(ss==this.s)&&(tt==this.t))
return true;
}
return false;
}
public int hashCode()
{
return (this.f+" "+this.s+" "+this.t).hashCode();
}
public int compareTo(Object o)//ascending order
{
triplet tr=(triplet)o;
if(t>tr.t)
return 1;
else
return -1;
}
}
void merge1(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i]<=R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void sort1(int arr[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort1(arr, l, m);
sort1(arr , m+1, r);
merge1(arr, l, m, r);
}
}
public static void main(String args[])throws Exception
{
new Thread(null,new templ(),"templ",1<<27).start();
}
public void run()
{
try
{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=in.ni();
int x=in.ni();
long l=1,r=n;
while(l<=r)
{
long mid=(l+r)/2;
long k=(mid*(mid+1))/2-(n-mid);
if(k==x)
{
out.println((n-mid));
break;
}
else if(k<x)
l=mid+1;
else
r=mid-1;
}
out.close();
}
catch(Exception e){
return;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public 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 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;
}
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static FastReader sc=new FastReader();
static long dp[][][];
static int mod=1000000007;
public static void main(String[] args) throws IOException
{
//CHECK FOR N=1
//CHECK FOR N=1
//CHECK FOR N=1
//CHECK FOR N=1
PrintWriter out=new PrintWriter(System.out);
// StringBuffer sb=new StringBuffer("");
int ttt=1;
// ttt =i();
outer :while (ttt-- > 0)
{
int n=i();
int m=i();
int k=i();
int A[][]=input(n,m-1);
int B[][]=input(n-1, m);
dp=new long[n+1][m+1][k+1];
for(int ii=0;ii<n;ii++) {
for(int jj=0;jj<m;jj++) {
Arrays.fill(dp[ii][jj],-1);
}
}
if(k%2!=0) {
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
System.out.print("-1 ");
}
System.out.println();
}
}
else {
go(A, B, 0, 0, k/2, n, m);
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
System.out.print(dp[i][j][k/2]*2+" ");
}
System.out.println();
}
}
}
out.close();
//System.out.println(sb.toString());
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1
//CHECK FOR N=1
//CHECK FOR N=1
}
static long go(int A[][],int B[][],int i,int j,int k,int l,int p) {
if(k==0)
return 0;
if(i>=l || j>=p)
return Integer.MAX_VALUE;
if(dp[i][j][k]!=-1)
return dp[i][j][k];
// if(i==m && j==n && k<org) {
// return Integer.MAX_VALUE;
// }
long op1=Long.MAX_VALUE;
if(i+1<l)
op1=Math.min(op1,go(A, B, i+1, j, k-1,l,p)+B[i][j]);
if(i-1>=0)
op1=Math.min(op1,go(A, B, i-1, j, k-1,l,p)+B[i-1][j]);
if(j+1<p)
op1=Math.min(op1,go(A, B, i, j+1, k-1,l,p)+A[i][j]);
if(j-1>=0)
op1=Math.min(op1,go(A, B, i, j-1, k-1,l,p)+A[i][j-1]);
go(A, B, i+1, j, k, l, p);
go(A, B, i, j+1, k, l, p);
return dp[i][j][k]=op1;
}
static int[] input(int n) {
int A[]=new int[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextInt();
}
return A;
}
static long[] inputL(int n) {
long A[]=new long[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextLong();
}
return A;
}
static String[] inputS(int n) {
String A[]=new String[n];
for(int i=0;i<n;i++) {
A[i]=sc.next();
}
return A;
}
static long sum(int A[]) {
long sum=0;
for(int i : A) {
sum+=i;
}
return sum;
}
static long sum(long A[]) {
long sum=0;
for(long i : A) {
sum+=i;
}
return sum;
}
static void reverse(long A[]) {
int n=A.length;
long B[]=new long[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void reverse(int A[]) {
int n=A.length;
int B[]=new int[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void input(int A[],int B[]) {
for(int i=0;i<A.length;i++) {
A[i]=sc.nextInt();
B[i]=sc.nextInt();
}
}
static int[][] input(int n,int m){
int A[][]=new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
A[i][j]=i();
}
}
return A;
}
static char[][] charinput(int n,int m){
char A[][]=new char[n][m];
for(int i=0;i<n;i++) {
String s=s();
for(int j=0;j<m;j++) {
A[i][j]=s.charAt(j);
}
}
return A;
}
static int max(int A[]) {
int max=Integer.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static int min(int A[]) {
int min=Integer.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long max(long A[]) {
long max=Long.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static long min(long A[]) {
long min=Long.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long [] prefix(long A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] prefix(int A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] suffix(long A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static long [] suffix(int A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static void print(int A[]) {
for(int i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(long A[]) {
for(long i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static long mod(long x) {
int mod=1000000007;
return ((x%mod + mod)%mod);
}
static String reverse(String s) {
StringBuffer p=new StringBuffer(s);
p.reverse();
return p.toString();
}
static int i() {
return sc.nextInt();
}
static String s() {
return sc.next();
}
static long l() {
return sc.nextLong();
}
static void sort(int[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static void sort(long[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static String sort(String s) {
Character ch[]=new Character[s.length()];
for(int i=0;i<s.length();i++) {
ch[i]=s.charAt(i);
}
Arrays.sort(ch);
StringBuffer st=new StringBuffer("");
for(int i=0;i<s.length();i++) {
st.append(ch[i]);
}
return st.toString();
}
static HashMap<Integer,Integer> hash(int A[]){
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Integer,Integer> tree(int A[]){
TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static boolean prime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static class Pair implements Comparable<Pair>
{
int x;
int y;
int z;
Pair(int x,int y,int z){
this.x=x;
this.y=y;
this.z=z;
}
@Override
// public int compareTo(Pair o) {
// if(this.x>o.x)
// return 1;
// else if(this.x<o.x)
// return -1;
// else {
// if(this.y>o.y)
// return 1;
// else if(this.y<o.y)
// return -1;
// else
// return 0;
// }
// }
public int compareTo(Pair o) {
int p=this.x-this.y;
int q=o.x-o.y;
if(p>q)
return 1;
else if(p<q)
return -1;
return 0;
}
}
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
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.math.BigDecimal;
import java.util.Scanner;
public class ReallyBigNumbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long n = scan.nextLong();
long s = scan.nextLong();
long ans = 0;
long l = 0;
long r = n;
while (l <= r) {
// Key is in a[lo..hi] or not present.
long mid = l + (r - l) / 2;
if(isReallyBig(mid, s)){
ans = mid;
r = mid-1;
}
else l = mid+1;
}
if(ans == 0) System.out.println(ans);
else
System.out.println(n-ans+1);
}
static boolean isReallyBig(long m, long s){
String x = m+"";
long sum = 0;
for(int i = 0; i < x.length(); i++){
sum += x.charAt(i)-'0';
}
if(m-sum >= s) return true;
return false;
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ProblemA {
public static void main(String[] args) throws IOException {
BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String[] data = s.readLine().split(" ");
int n = Integer.valueOf(data[0]);
int k = Integer.valueOf(data[1]);
long[] a = new long[n];
String[] ai = s.readLine().split(" ");
for (int i = 0 ; i < n ; i++) {
a[i] = Integer.valueOf(ai[i]);
}
for (int i = 0 ; i < n ; i++) {
int tm = (int)(Math.random() * n);
long tmp = a[tm];
a[tm] = a[i];
a[i] = tmp;
}
Arrays.sort(a);
Set<Long> invalid = new HashSet<Long>();
int cnt = 0;
for (int i = 0 ; i < n ; i++) {
if (!invalid.contains(a[i])) {
cnt++;
invalid.add(a[i] * k);
}
}
out.println(cnt);
out.flush();
}
public static void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class round569d2b {
public static void main(String args[]) {
FastScanner in = new FastScanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
if (n % 2 == 0) {
for (int i = 0; i < n; i++) {
if (arr[i] >= 0) {
arr[i] = -1*arr[i]-1;
}
}
}
else {
int max = Integer.MIN_VALUE;
int maxIndex = 0;
for (int i = 0; i < n; i++) {
int elem = arr[i];
if (elem < 0) {
elem = -1*elem-1;
}
if (elem > max) {
max = elem;
maxIndex = i;
}
}
for (int i = 0; i < n; i++) {
if (i == maxIndex) {
if (arr[i] < 0) {
arr[i] = -1*arr[i]-1;
}
}
else {
if (arr[i] >= 0) {
arr[i] = -1*arr[i]-1;
}
}
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n ;i++) {
sb.append(arr[i] + " ");
}
System.out.println(sb);
}
// ======================================================================================
// =============================== Reference Code =======================================
// ======================================================================================
static int greatestDivisor(int n) {
int limit = (int) Math.sqrt(n);
int max = 1;
for (int i = 2; i <= limit; i++) {
if (n % i == 0) {
max = Integer.max(max, i);
max = Integer.max(max, n / i);
}
}
return max;
}
// Method to return all primes smaller than or equal to
// n using Sieve of Eratosthenes
static boolean[] sieveOfEratosthenes(int n) {
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a prime
if (prime[p] == true) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
// Binary search for number greater than or equal to target
// returns -1 if number not found
private static int bin_gteq(int[] a, int key) {
int low = 0;
int high = a.length;
int max_limit = high;
while (low < high) {
int mid = low + (high - low) / 2;
if (a[mid] < key) {
low = mid + 1;
} else
high = mid;
}
return high == max_limit ? -1 : high;
}
public static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
public String toString() {
return "(" + x + "," + y + ")";
}
}
static class Tuple3<X, Y, Z> {
public final X x;
public final Y y;
public final Z z;
public Tuple3(X x, Y y, Z z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return "(" + x + "," + y + "," + z + ")";
}
}
static Tuple3<Integer, Integer, Integer> gcdExtended(int a, int b, int x, int y) {
// Base Case
if (a == 0) {
x = 0;
y = 1;
return new Tuple3(0, 1, b);
}
int x1 = 1, y1 = 1; // To store results of recursive call
Tuple3<Integer, Integer, Integer> tuple = gcdExtended(b % a, a, x1, y1);
int gcd = tuple.z;
x1 = tuple.x;
y1 = tuple.y;
// Update x and y using results of recursive
// call
x = y1 - (b / a) * x1;
y = x1;
return new Tuple3(x, y, gcd);
}
// Returns modulo inverse of a
// with respect to m using extended
// Euclid Algorithm. Refer below post for details:
// https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
static int inv(int a, int m) {
int m0 = m, t, q;
int x0 = 0, x1 = 1;
if (m == 1)
return 0;
// Apply extended Euclid Algorithm
while (a > 1) {
// q is quotient
q = a / m;
t = m;
// m is remainder now, process
// same as euclid's algo
m = a % m;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
// Make x1 positive
if (x1 < 0)
x1 += m0;
return x1;
}
// k is size of num[] and rem[].
// Returns the smallest number
// x such that:
// x % num[0] = rem[0],
// x % num[1] = rem[1],
// ..................
// x % num[k-2] = rem[k-1]
// Assumption: Numbers in num[] are pairwise
// coprime (gcd for every pair is 1)
static int findMinX(int num[], int rem[], int k) {
// Compute product of all numbers
int prod = 1;
for (int i = 0; i < k; i++)
prod *= num[i];
// Initialize result
int result = 0;
// Apply above formula
for (int i = 0; i < k; i++) {
int pp = prod / num[i];
result += rem[i] * inv(pp, num[i]) * pp;
}
return result % prod;
}
/**
* Source: Matt Fontaine
*/
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int chars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (chars == -1)
throw new InputMismatchException();
if (curChar >= chars) {
curChar = 0;
try {
chars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (chars <= 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();
}
}
}
|
linear
|
1180_B. Nick and Array
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
s.nextLine();
while(s.hasNext()) {
int first = s.nextInt();
int second = s.nextInt();
System.out.println(calculate(first,second));
}
}
public static int calculate(int first, int second) {
int operations = 0;
while(first != 0 && second != 0) {
int temp;
if(first < second) {
temp = second/first;
operations += temp;
second -= (first*temp);
}
else {
temp = first/second;
operations += temp;
first -= (second*temp);
}
}
return operations;
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n,b = 0;
n=in.nextInt();
if (n%2==0) {
b=n+n/2;
System.out.println(b);
}
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.Scanner;
public class A {
static InputStreamReader in = new InputStreamReader(System.in);
static BufferedReader bf = new BufferedReader(in);
static StreamTokenizer st = new StreamTokenizer(bf);
static Scanner sc = new Scanner(System.in);
static class Sort implements Comparable<Sort> {
int x, a;
public int compareTo(Sort arg0) {
if (this.x > arg0.x)
return 1;
return 0;
}
}
public static void main(String[] args) throws IOException {
int n = nextInt();
double t = nextInt();
Sort[] p = new Sort[n];
for (int i = 0; i < n; i++) {
p[i] = new Sort();
p[i].x = nextInt();
p[i].a = nextInt();
}
int ans = 2;
Arrays.sort(p);
for (int i = 1; i < p.length; i++) {
double k = p[i].x - p[i].a / 2.0 - p[i - 1].x - p[i - 1].a / 2.0;
if (t == k)
ans++;
else if (k > t)
ans += 2;
}
System.out.println(ans);
}
private static String nextString() throws IOException {
st.nextToken();
return st.sval;
}
private static int nextInt() throws IOException {
st.nextToken();
return (int) st.nval;
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task task = new Task();
task.solve(in, out);
out.close();
}
static class Rectangle {
int x1, y1;
int x2, y2;
}
static class Task {
/**
* BEFORE SUBMITTING!!!
* MAKE SURE IT IS RIGHT!!!!!
* LONG!!
* Check if m,n aren't misused
* Make sure the output format is right (YES/NO vs Yes/No, newlines vs spaces)
* Run with n = 1 or n = 0
* Make sure two ints aren't multiplied to get a long
*
*/
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
//ideas: procurar linha que os divide e procurar dentro desses sub-retangulos
// procurar até ser 1
//corner cases: se procurar até ser 1 e não verificar se tem 1 do outro lado posso chegar a 1,2...not good
// tenho que procurar 1,1
int l = 1;
int r = n;
int ans = 0;
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,1,1,mid, n) == 0) {
l = mid + 1;
} else {
ans = mid;
r = mid - 1;
}
}
//par 1,1
//FDS ISTO
if(ans < n && ask(in,out,ans + 1, 1,n,n) == 1) {
Rectangle r1 = find(in,out,1,1,ans,n,n);
Rectangle r2 = find(in,out,ans + 1,1,n,n,n);
System.out.printf("! %d %d %d %d %d %d %d %d\n", r1.x1, r1.y1, r1.x2, r1.y2, r2.x1, r2.y1, r2.x2, r2.y2);
} else {
l = 1;
r = n;
ans = 0;
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,1,1,n, mid) == 0) {
l = mid + 1;
} else {
ans = mid;
r = mid - 1;
}
}
Rectangle r1 = find(in,out,1,1,n,ans,n);
Rectangle r2 = find(in,out,1,ans + 1,n,n,n);
System.out.printf("! %d %d %d %d %d %d %d %d\n", r1.x1, r1.y1, r1.x2, r1.y2, r2.x1, r2.y1, r2.x2, r2.y2);
}
}
//HASDFDSJGHDFJKSGDFJSGJDFSGJDSFGJF
//FKING WORK
public Rectangle find(InputReader in, PrintWriter out,int x1, int y1, int x2, int y2, int n) {
Rectangle rec = new Rectangle();
int ansx1 = x1;
int ansx2 = x2;
int ansy1 = y1;
int ansy2 = y2;
int l = x1;
int r = x2;
// quero o minimo v >= x2
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,x1,y1,mid,y2) == 1) {
ansx2 = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
//out.printf("x2 = %d", ansx2);
r = x2;
l = x1;
// quero o maximo v <= x1
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,mid,y1,x2,y2) == 1) {
ansx1 = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
//out.printf("x1 = %d", ansx1);
l = y1;
r = y2;
// quero o minimo v >= y2
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,x1,y1,x2,mid) == 1) {
ansy2 = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
//out.printf("y2 = %d", ansy2);
r = y2;
l = y1;
// quero o maximo v <= y1
while(r >= l) {
int mid = (r + l) / 2;
if(ask(in,out,x1,mid,x2,y2) == 1) {
ansy1 = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
//out.printf("y1 = %d", ansy1);
rec.x1 = ansx1;
rec.x2 = ansx2;
rec.y1 = ansy1;
rec.y2 = ansy2;
return rec;
}
public int ask(InputReader in, PrintWriter out, int x1, int y1, int x2, int y2) {
System.out.printf("? %d %d %d %d\n",x1,y1,x2,y2);
System.out.flush();
return in.nextInt();
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
}
return null;
}
}
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
import java.util.Scanner;
public class DigitsSequence {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
long k,c,n,d;
c=1;
d=9;
n=1;
k= sc.nextLong();
while(k>(c*d)) {
k-=(c*d);
n*=10;
d*=10;
c++;
}
n+=(k-1)/c;
char[] num = String.valueOf(n).toCharArray();
System.out.println(num[(int)((k-1)%c)]);
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int inv = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (a[j] > a[i]) {
inv++;
}
}
}
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int l = in.nextInt();
int r = in.nextInt();
int s = (r - l + 1) * (r - l) / 2;
inv = (inv + s) % 2;
out.println(inv % 2 == 0 ? "even" : "odd");
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String next() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Solution
{
public static void main(String [] args) throws IOException
{
PrintWriter pw=new PrintWriter(System.out);//use pw.println() not pw.write();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(br.readLine());
/*
inputCopy
5 3
xyabd
outputCopy
29
inputCopy
7 4
problem
outputCopy
34
inputCopy
2 2
ab
outputCopy
-1
inputCopy
12 1
abaabbaaabbb
outputCopy
1
*/
int n=Integer.parseInt(st.nextToken());
int k=Integer.parseInt(st.nextToken());
st=new StringTokenizer(br.readLine());
String str=st.nextToken();
char [] arr=str.toCharArray();
Arrays.sort(arr);
int weight=arr[0]-96;
char a=arr[0];
int included=1;
for(int i=1;i<arr.length;++i)
{
if(included==k)
break;
char c=arr[i];
if(c-a<2)
continue;
weight+=arr[i]-96;
++included;
a=arr[i];
}
if(included==k)
pw.println(weight);
else
pw.println(-1);
pw.close();//Do not forget to write it after every program return statement !!
}
}
/*
→Judgement Protocol
Test: #1, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
5 3
xyabd
Output
29
Answer
29
Checker Log
ok 1 number(s): "29"
Test: #2, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
7 4
problem
Output
34
Answer
34
Checker Log
ok 1 number(s): "34"
Test: #3, time: 139 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
2 2
ab
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #4, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
12 1
abaabbaaabbb
Output
1
Answer
1
Checker Log
ok 1 number(s): "1"
Test: #5, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 13
qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa
Output
169
Answer
169
Checker Log
ok 1 number(s): "169"
Test: #6, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 14
qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #7, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
1 1
a
Output
1
Answer
1
Checker Log
ok 1 number(s): "1"
Test: #8, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 1
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Output
1
Answer
1
Checker Log
ok 1 number(s): "1"
Test: #9, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 2
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #10, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
13 13
uwgmkyqeiaocs
Output
169
Answer
169
Checker Log
ok 1 number(s): "169"
Test: #11, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
13 13
hzdxpbfvrltnj
Output
182
Answer
182
Checker Log
ok 1 number(s): "182"
Test: #12, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
1 1
n
Output
14
Answer
14
Checker Log
ok 1 number(s): "14"
Test: #13, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
10 8
smzeblyjqw
Output
113
Answer
113
Checker Log
ok 1 number(s): "113"
Test: #14, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
20 20
tzmvhskkyugkuuxpvtbh
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #15, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
30 15
wjzolzzkfulwgioksfxmcxmnnjtoav
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #16, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
40 30
xumfrflllrrgswehqtsskefixhcxjrxbjmrpsshv
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #17, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 31
ahbyyoxltryqdmvenemaqnbakglgqolxnaifnqtoclnnqiabpz
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #18, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
10 7
iuiukrxcml
Output
99
Answer
99
Checker Log
ok 1 number(s): "99"
Test: #19, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
38 2
vjzarfykmrsrvwbwfwldsulhxtykmjbnwmdufa
Output
5
Answer
5
Checker Log
ok 1 number(s): "5"
Test: #20, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
12 6
fwseyrarkwcd
Output
61
Answer
61
Checker Log
ok 1 number(s): "61"
Test: #21, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
2 2
ac
Output
4
Answer
4
Checker Log
ok 1 number(s): "4"
Test: #22, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
1 1
c
Output
3
Answer
3
Checker Log
ok 1 number(s): "3"
Test: #23, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
2 2
ad
Output
5
Answer
5
Checker Log
ok 1 number(s): "5"
Test: #24, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER
Input
2 1
ac
Output
-1
Answer
1
Checker Log
wrong answer 1st number
*/
|
linear
|
1011_A. Stages
|
CODEFORCES
|
import java.util.*;
public class ehab4 {
public static void main( String[] args ) {
Scanner in = new Scanner( System.in );
int a = 0, b = 0;
System.out.println( "? 0 0 " );
System.out.flush();
int c = in.nextInt();
for ( int i = 29; i >= 0; i-- ) {
System.out.println( "? " + ( a + ( 1 << i ) ) + " " + b );
System.out.flush();
int q1 = in.nextInt();
System.out.println( "? " + a + " " + ( b + ( 1 << i ) ) );
System.out.flush();
int q2 = in.nextInt();
if ( q1 == q2 ) {
if ( c == 1 )
a += ( 1 << i );
else if ( c == -1 )
b += ( 1 << i );
c = q1;
}
else if ( q1 == -1 ) {
a += ( 1 << i );
b += ( 1 << i );
}
else if ( q1 == -2 )
return;
}
System.out.println( "! " + a + " " + b );
System.out.flush();
}
}
|
logn
|
1088_D. Ehab and another another xor problem
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class D{
static int bot;
static int n,m;
static int [][]a;
static int [][]Min;
static int [][]memo;
static int K;
static int dp(int msk,int ones,int last) {
if(ones==n) {
return Min[last][bot]>=K?1:0;
}
if(memo[last][msk]!=-1)
return memo[last][msk];
int ans=0;
for(int nxt=0;nxt<n;nxt++)
if((msk & (1<<nxt)) ==0 && Min[last][nxt]>=K)
{
ans|=dp(msk|1<<nxt,ones+1,nxt);
}
return memo[last][msk]= ans;
}
static boolean check(int top,int bottom) {
for(int j=0;j+1<m;j++)
{
int diff=Math.abs(a[bottom][j]-a[top][j+1]);
if(diff<K)
return false;
}
return true;
}
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner();
PrintWriter out=new PrintWriter(System.out);
n=sc.nextInt();
m=sc.nextInt();
a=new int [n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
a[i][j]=sc.nextInt();
Min=new int [n][n];
if(n==1) {
int lo=0,hi=(int)1e9;
int ans=0;
while(lo<=hi) {
K=lo+hi>>1;
if(check(0, 0))
{
ans=K;
lo=K+1;
}
else
hi=K-1;
}
System.out.println(ans);
return;
}
for(int i1=0;i1<n;i1++)
for(int i2=0;i2<n;i2++)
{
if(i1==i2)
continue;
int min=(int) 1e9;
for(int j=0;j<m;j++)
min=Math.min(Math.abs(a[i1][j]-a[i2][j]), min);
Min[i1][i2]=min;
}
memo=new int [n][1<<n];
int ans=0;
int lo=0,hi=(int)1e9;
while(lo<=hi) {
K=lo+hi>>1;
for(int []x:memo)
Arrays.fill(x, -1);
int ok=0;
for(int top=0;top<n && ok==0;top++)
for(int bottom=0;bottom<n && ok==0 ;bottom++) {
bot=bottom;
if(top==bottom || !check(top, bottom))
continue;
int dp=dp(1<<top | 1<<bottom, 2, top);
ok|=dp;
}
if(ok==1)
{
ans=K;
lo=K+1;
}
else
hi=K-1;
}
out.println(ans);
out.close();
}
static class Scanner
{
BufferedReader br;
StringTokenizer st;
Scanner(){
br=new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException{
br=new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while(st==null || !st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException{
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
}
}
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws IOException {
FastScanner in= new FastScanner(System.in);
PrintWriter out= new PrintWriter(System.out);
int n= in.nextInt();
int r= in.nextInt();
int [] x= new int[n];
for (int i = 0; i < x.length; i++) {
x[i]= in.nextInt();
}
double [] res= new double[n];
res[0]= r;
for (int i = 1; i < x.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++) {
double dis= Math.abs(x[i]-x[j]);
double rr= 4.0*r*r-1.0*dis*dis;
if(rr>=0) {
double del= Math.sqrt(rr);
res[i]= Math.max(res[i], res[j]+del);
found= true;
}
}
if(!found) {
res[i]= r;
}
}
for (int i = 0; i < res.length; i++) {
out.print(res[i]+" ");
}
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public String next() throws IOException {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
return next();
}
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt(), R = sc.nextInt();
double answer[] = new double[N];
int[] x = new int[N];
for (int i = 0; i < N; i++)
x[i] = sc.nextInt();
for (int i = 0; i < N; i++) {
answer[i] = R;
for (int j = 0; j < i; j++) {
int dist = Math.abs(x[i] - x[j]);
if(dist <= 2 * R) {
double t = answer[j] + Math.sqrt(4 * R * R - dist * dist);
answer[i] = Math.max(answer[i], t);
}
}
}
for(int i = 0; i < N; ++i)
out.print(answer[i] + " ");
out.println();
out.flush();
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class A implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
public static void main(String[] args) {
new Thread(null, new A(), "", 64*1024*1024).start();
}
public void run() {
try {
long t1 = 0, t2 = 0, m1 = 0, m2 = 0;
if (LOCAL) {
t1 = System.currentTimeMillis();
m1 = Runtime.getRuntime().freeMemory();
}
Locale.setDefault(Locale.US);
if (LOCAL) {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
solve();
in.close();
out.close();
if (LOCAL) {
t2 = System.currentTimeMillis();
m2 = Runtime.getRuntime().freeMemory();
System.err.println("Time = " + (t2 - t1) + " ms.");
System.err.println("Memory = " + ((m1 - m2) / 1024) + " KB.");
}
} catch (Throwable e) {
e.printStackTrace(System.err);
throw new RuntimeException();
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String line = in.readLine();
if (line == null) return null;
tok = new StringTokenizer(line);
}
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());
}
static class Mergesort {
private Mergesort() {}
public static void sort(int[] a) {
mergesort(a, 0, a.length - 1);
}
public static void sort(long[] a) {
mergesort(a, 0, a.length - 1);
}
public static void sort(double[] a) {
mergesort(a, 0, a.length - 1);
}
private static final int MAGIC_VALUE = 42;
private static void mergesort(int[] a, int leftIndex, int rightIndex) {
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergesort(a, leftIndex, middleIndex);
mergesort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void mergesort(long[] a, int leftIndex, int rightIndex) {
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergesort(a, leftIndex, middleIndex);
mergesort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void mergesort(double[] a, int leftIndex, int rightIndex) {
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergesort(a, leftIndex, middleIndex);
mergesort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
int[] leftArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void merge(long[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
long[] leftArray = new long[length1];
long[] rightArray = new long[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void merge(double[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
double[] leftArray = new double[length1];
double[] rightArray = new double[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
private static void insertionSort(long[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
long current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
private static void insertionSort(double[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
double current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
}
void debug(Object... o) {
if (LOCAL) {
System.err.println(Arrays.deepToString(o));
}
}
final static boolean LOCAL = System.getProperty("ONLINE_JUDGE") == null;
//------------------------------------------------------------------------------
void solve() throws IOException {
int n = readInt();
long k = readLong();
if (k == 1) {
out.println(n);
return;
}
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = readLong();
}
Mergesort.sort(a);
int ans = 0;
boolean[] processed = new boolean[n];
debug(a);
for (int i = 0; i < n; i++) {
if (processed[i]) {
continue;
}
processed[i] = true;
long cur = a[i];
ans++;
int index = Arrays.binarySearch(a, cur * k);
if (index >= 0) {
processed[index] = true;
}
}
out.println(ans);
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import static java.util.Arrays.*;
import static java.lang.Math.*;
import java.math.*;
public class Main {
void run() throws IOException {
int n = nint();
char[] s = token().toCharArray();
int h = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'H') h++;
}
int r = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int t = 0;
for (int j = i; j < i + h; j++) {
if (s[j % n] == 'T') t++;
}
r = min(r, t);
}
out.println(r);
}
class pair implements Comparable <pair> {
int x, y;
pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo (pair p) {
if (x != p.x) {
return x - p.x;
} else {
return y - p.y;
}
}
}
// static PrintWriter out;
// static Scanner in;
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
//final String FILENAME = "jury"; in = new Scanner (new File (FILENAME + ".in")); out = new PrintWriter (new File(FILENAME + ".out"));
// in = new Scanner (System.in); out = new PrintWriter (System.out);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
st = new StringTokenizer(" ");
new Main().run();
/*out = new PrintWriter (System.out);
final int NUMBER_OF_TESTS = 35;
for (int i = 1; i <= NUMBER_OF_TESTS; i++) {
Scanner test = new Scanner (new File ("tests/" + i + ".in"));
Scanner right = new Scanner (new File ("tests/" + i + ".out"));
String get_right = right.nextLine();
String get_test = new Main().run(test);
if (get_right.equals(get_test)) {
out.println("Test #" + i + ": " + "OK!");
} else {
out.println("Test #" + i + ": " + "ERROR!");
out.println("Expected: " + get_right);
out.println("Received: " + get_test);
break;
}
}*/
out.close();
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer st;
String token() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nint() throws IOException {
return Integer.parseInt(token());
}
long nlong() throws IOException {
return Long.parseLong(token());
}
double ndouble() throws IOException {
return Double.parseDouble(token());
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution {
Scanner in;
PrintWriter out;
boolean isPrime(int x) {
for (int i = 2; i * i <= x; ++i) {
if (x % i == 0) {
return false;
}
}
return true;
}
void solve() throws IOException {
in = new Scanner(System.in);
//in = new Scanner(new FileReader("input.txt"));
out = new PrintWriter(System.out);
int N = in.nextInt();
int K = in.nextInt();
List<Integer> primes = new ArrayList<Integer>();
for (int i = 2; i <= N; ++i) {
if (isPrime(i)) {
primes.add(i);
}
}
int c = 0;
for (int i = 2; i <= N; ++i) {
if (!isPrime(i)) continue;
for (int j = 0; j + 1 < primes.size(); ++j) {
int p1 = primes.get(j);
int p2 = primes.get(j + 1);
if (p1 + p2 + 1 == i) {
++c;
//out.println(i);
break;
}
}
}
if (c >= K) out.println("YES");
else out.println("NO");
out.close();
}
public static void main(String args[]) throws IOException {
new Solution().solve();
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.util.*;
import static java.lang.System.*;
public class D276 {
Scanner sc = new Scanner(in);
public void run() {
long l=sc.nextLong(),r=sc.nextLong();
long tes=l^r;
int d=0;
while(tes!=0){
tes/=2;
d++;
}
ln((1L<<d)-1);
}
public static void main(String[] _) {
new D276().run();
}
public static void pr(Object o) {
out.print(o);
}
public static void ln(Object o) {
out.println(o);
}
public static void ln() {
out.println();
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class X
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String s1 = br.readLine();
String s2 = br.readLine();
int i=0;
char c1,c2;
int cost = 0;
while(i<n)
{
c1 = s1.charAt(i);
c2 = s2.charAt(i);
if(c1 != c2)
{
if((i+1)<n && s1.charAt(i+1) != s2.charAt(i+1) && s1.charAt(i) != s1.charAt(i+1))
{
cost +=1;
i++;
}
else
{
cost +=1;
}
}
i++;
}
System.out.println(cost);
}
}
|
linear
|
1037_C. Equalize
|
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.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ilyakor
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int r = in.nextInt();
ArrayList<PointDouble> centers = new ArrayList<>();
ArrayList<Integer> xs = new ArrayList<>();
for (int i = 0; i < n; ++i) {
int x = in.nextInt();
double y = r;
for (int j = 0; j < centers.size(); j++) {
int ox = xs.get(j);
if (Math.abs(ox - x) > 2 * r) continue;
PointDouble c = centers.get(j);
double t = Math.abs(ox - x);
double h = Math.sqrt(Math.abs(4.0 * r * r - t * t));
double val = c.y + h;
if (y < val) y = val;
}
out.print(String.format("%.20f ", y));
centers.add(new PointDouble(x, y));
xs.add(x);
}
out.printLine();
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
static class PointDouble {
public double x;
public double y;
public PointDouble(double x, double y) {
this.x = x;
this.y = y;
}
public PointDouble() {
x = 0;
y = 0;
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Liavontsi Brechka
*/
public class Main
{
public static void main(String[] args)
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
F1BlokiRavnoiSummiProstayaRedakciya solver = new F1BlokiRavnoiSummiProstayaRedakciya();
solver.solve(1, in, out);
out.close();
}
static class F1BlokiRavnoiSummiProstayaRedakciya
{
InputReader in;
Map<Long, List<F1BlokiRavnoiSummiProstayaRedakciya.Block>> sums;
public void solve(int testNumber, InputReader in, PrintWriter out)
{
this.in = in;
int n = ni();
long[] a = nla(n);
sums = new HashMap<>();
for (int i = 0; i < n; i++)
{
long sum = 0;
for (int j = i; j < n; j++)
{
sum += a[j];
sums.computeIfAbsent(sum, k -> new ArrayList<>()).add(
new F1BlokiRavnoiSummiProstayaRedakciya.Block(i, j, sum));
}
}
for (Map.Entry<Long, List<F1BlokiRavnoiSummiProstayaRedakciya.Block>> e : sums.entrySet())
{
Collections.sort(e.getValue());
}
List<F1BlokiRavnoiSummiProstayaRedakciya.Block> res = Collections.emptyList();
for (Map.Entry<Long, List<F1BlokiRavnoiSummiProstayaRedakciya.Block>> e : sums.entrySet())
{
List<F1BlokiRavnoiSummiProstayaRedakciya.Block> blocks = e.getValue();
List<F1BlokiRavnoiSummiProstayaRedakciya.Block> updated = new ArrayList<>();
if (blocks.size() <= res.size())
continue;
for (F1BlokiRavnoiSummiProstayaRedakciya.Block next : blocks)
{
if (updated.size() == 0)
updated.add(next);
else
{
F1BlokiRavnoiSummiProstayaRedakciya.Block prev = updated.get(updated.size() - 1);
if (next.l > prev.r)
updated.add(next);
}
}
if (updated.size() > res.size())
res = updated;
}
StringBuilder resS = new StringBuilder();
resS.append(res.size()).append('\n');
for (F1BlokiRavnoiSummiProstayaRedakciya.Block block : res)
resS.append(block.l + 1).append(' ').append(block.r + 1).append('\n');
out.println(resS);
}
private long[] nla(int size)
{
return in.nextLongArray(size);
}
private int ni()
{
return in.nextInt();
}
static class Block implements Comparable<F1BlokiRavnoiSummiProstayaRedakciya.Block>
{
int l;
int r;
long sum;
public Block(int l, int r, long sum)
{
this.l = l;
this.r = r;
this.sum = sum;
}
public int compareTo(F1BlokiRavnoiSummiProstayaRedakciya.Block o)
{
int res = Integer.compare(r, o.r);
if (res == 0)
res = Integer.compare(l, o.l);
return res;
}
}
}
static class InputReader
{
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream in)
{
reader = new BufferedReader(new InputStreamReader(in));
}
public long[] nextLongArray(int size)
{
long[] array = new long[size];
for (int i = 0; i < size; ++i)
{
array[i] = nextLong();
}
return array;
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
tokenizer = new StringTokenizer(readLine());
}
return tokenizer.nextToken();
}
public String readLine()
{
String line;
try
{
line = reader.readLine();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return line;
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Codeforces {
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
final double eps = 1e-7;
String toks[] = in.readLine().split(" ");
int n = Integer.parseInt(toks[0]);
double r = Double.parseDouble(toks[1]);
double x[] = new double[n];
toks = in.readLine().split(" ");
for (int i = 0; i < n; i++) {
x[i] = Double.parseDouble(toks[i]);
}
double lo, hi, mid;
double y[] = new double[n];
y[0] = r;
for (int i = 1; i < n; i++) {
y[i] = r;
for(int j=0; j<i; j++) {
lo = y[j]; hi = 2000*2000;
while( Math.abs(hi-lo) >= eps ) {
mid = (hi+lo)/2;
if( Math.sqrt( (x[i]-x[j])*(x[i]-x[j]) + (y[j]-mid)*(y[j]-mid) ) + eps > 2*r ) {
hi = mid;
} else {
lo = mid;
}
}
if(Math.sqrt( (x[i]-x[j])*(x[i]-x[j]) + (y[j]-lo)*(y[j]-lo) ) < 2*r + eps) {
y[i] = Math.max(y[i], lo);
}
}
}
for (double z : y) {
System.out.printf(Locale.US, "%.7f ", z);
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
long l = in.readLong(), r = in.readLong();
int pow = 62;
long mask = 1L << pow;
while (((r | l) & mask) == 0){
pow--;
mask = 1L << pow;
}
while (true) {
if (((r ^ l) & mask) == mask || pow < 0) {
break;
}
mask >>= 1;
l = l & ~(1L << pow);
r = r & ~(1L << pow);
pow--;
}
pow++;
out.print((1L << pow) - 1);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.util.*;
public class substraction {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while (t>0) {
long a=sc.nextLong();
long b=sc.nextLong();
int op=0;
if (a>b) {
while (a%b!=0) {
op+=a/b;
a=a%b;
long c=b;
b=a;
a=c;
}
op+=a/b;
}
else{
while (b%a!=0) {
op+=b/a;
b=b%a;
long c=a;
a=b;
b=c;
}
op+=b/a;
}
System.out.println(op);
t--;
}
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.math.MathContext;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public static final long mod = 1000L * 1000L * 1000L + 9L;
public void solve(int testNumber, InputReader in, OutputWriter out) {
long n = in.nextLong();
long m = in.nextLong();
long k = in.nextLong();
long z = n - m;
long left = m - z * (k - 1L);
if (left < 0) left = 0;
long res = IntegerUtlis.pow(2L, left / k, mod) - 1L;
res *= 2L * k;
res %= mod;
res += left % k;
res %= mod;
res += m - left;
res %= mod;
res += mod;
res %= mod;
out.printLine(res);
}
}
class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public long nextLong() {
long sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10L + (long)(c - '0');
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
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();
}
}
class IntegerUtlis {
public static long pow(long x, long y, long mod) {
x %= mod;
long res = 1;
while (y > 0) {
if (y % 2 == 1) {
--y;
res = BigInteger.valueOf(res).multiply(BigInteger.valueOf(x)).mod(BigInteger.valueOf(mod)).longValue();
} else {
y /= 2;
x = BigInteger.valueOf(x).multiply(BigInteger.valueOf(x)).mod(BigInteger.valueOf(mod)).longValue();
}
}
return res % mod;
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
public class Main {
static PrintWriter out;
static InputReader ir;
static void solve() {
int n=ir.nextInt();
int r=ir.nextInt();
int[] x=ir.nextIntArray(n);
double[] ret=new double[n];
for(int i=0;i<n;i++){
double ma=r;
for(int j=0;j<i;j++){
if(Math.abs(x[i]-x[j])<=2*r){
ma=Math.max(ma,ret[j]+Math.sqrt(4*(double)Math.pow(r, 2)-Math.pow(x[i]-x[j],2)));
}
}
ret[i]=ma;
}
for(int i=0;i<n;i++){
out.print(ret[i]+(i==n-1?"\n":" "));
}
}
public static void main(String[] args) throws Exception {
ir = new InputReader(System.in);
out = new PrintWriter(System.out);
solve();
out.flush();
}
static class InputReader {
private InputStream in;
private byte[] buffer = new byte[1024];
private int curbuf;
private int lenbuf;
public InputReader(InputStream in) {
this.in = in;
this.curbuf = this.lenbuf = 0;
}
public boolean hasNextByte() {
if (curbuf >= lenbuf) {
curbuf = 0;
try {
lenbuf = in.read(buffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return false;
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[curbuf++];
else
return -1;
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private void skip() {
while (hasNextByte() && isSpaceChar(buffer[curbuf]))
curbuf++;
}
public boolean hasNext() {
skip();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (!isSpaceChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public char[][] nextCharMap(int n, int m) {
char[][] map = new char[n][m];
for (int i = 0; i < n; i++)
map[i] = next().toCharArray();
return map;
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class R023A {
String str;
int n;
public R023A() {
Scanner scanner = new Scanner(System.in);
str = scanner.next();
n = str.length();
}
private void process() {
int length = -1;
for(int i=1; i<n; i++) {
Set<String> set = new HashSet<String>();
length = n - i;
for(int j=0; j<=i; j++) {
String sub = str.substring(j, j+length);
set.add(sub);
}
if(set.size() < i+1) {
System.out.println(length);
return;
}
}
System.out.println(0);
}
public static void main(String[] args) {
new R023A().process();
}
}
|
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.IOException;
import java.io.BufferedReader;
import java.io.Reader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyInput in = new MyInput(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
int n;
MyInput in;
PrintWriter out;
public void solve(int testNumber, MyInput in, PrintWriter out) {
this.in = in;
this.out = out;
n = in.nextInt();
if (n / 2 % 2 == 1) {
answer(-1);
return;
}
int low = 0, high = n / 2;
int diff = query(low + n / 2) - query(low);
while (diff != 0) {
int mid = (low + high) / 2;
int d = query(mid + n / 2) - query(mid);
if (d == 0 || diff > 0 == d > 0) {
diff = d;
low = mid;
} else {
high = mid;
}
}
answer(low);
}
int query(int i) {
out.println("? " + (i % n + 1));
out.flush();
return in.nextInt();
}
void answer(int i) {
out.println("! " + (i < 0 ? i : (i % n + 1)));
}
}
static class MyInput {
private final BufferedReader in;
private static int pos;
private static int readLen;
private static final char[] buffer = new char[1024 * 8];
private static char[] str = new char[500 * 8 * 2];
private static boolean[] isDigit = new boolean[256];
private static boolean[] isSpace = new boolean[256];
private static boolean[] isLineSep = new boolean[256];
static {
for (int i = 0; i < 10; i++) {
isDigit['0' + i] = true;
}
isDigit['-'] = true;
isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
isLineSep['\r'] = isLineSep['\n'] = true;
}
public MyInput(InputStream is) {
in = new BufferedReader(new InputStreamReader(is));
}
public int read() {
if (pos >= readLen) {
pos = 0;
try {
readLen = in.read(buffer);
} catch (IOException e) {
throw new RuntimeException();
}
if (readLen <= 0) {
throw new MyInput.EndOfFileRuntimeException();
}
}
return buffer[pos++];
}
public int nextInt() {
int len = 0;
str[len++] = nextChar();
len = reads(len, isSpace);
int i = 0;
int ret = 0;
if (str[0] == '-') {
i = 1;
}
for (; i < len; i++) ret = ret * 10 + str[i] - '0';
if (str[0] == '-') {
ret = -ret;
}
return ret;
}
public char nextChar() {
while (true) {
final int c = read();
if (!isSpace[c]) {
return (char) c;
}
}
}
int reads(int len, boolean[] accept) {
try {
while (true) {
final int c = read();
if (accept[c]) {
break;
}
if (str.length == len) {
char[] rep = new char[str.length * 3 / 2];
System.arraycopy(str, 0, rep, 0, str.length);
str = rep;
}
str[len++] = (char) c;
}
} catch (MyInput.EndOfFileRuntimeException e) {
}
return len;
}
static class EndOfFileRuntimeException extends RuntimeException {
}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
* User: piyushd
* Date: 3/26/11
* Time: 10:53 PM
* To change this template use File | Settings | File Templates.
*/
public class TaskC {
final int INF = 123456;
int[][][] memo;
int N, M;
int solve(int row, int prevFreeMask, int curStayMask) {
if(row == N) return (curStayMask == 0) ? 0 : -INF;
if(memo[row][prevFreeMask][curStayMask] != -1) return memo[row][prevFreeMask][curStayMask];
int res = 0;
for(int mask = 0; mask < (1<<M); mask++) {
if((mask & curStayMask) == curStayMask) {
int freeCellsMask = (1<<M) - 1 - mask;
int toMoveMask = freeCellsMask;
for(int i = 0; i < M; i++) {
if((toMoveMask & (1<<i)) > 0) {
if(i > 0) {
if((mask & (1<<(i - 1))) > 0) {
toMoveMask -= (1<<i);
continue;
}
}
if(i < M - 1) {
if((mask & (1<<(i + 1))) > 0) {
toMoveMask -= (1<<i);
continue;
}
}
}
}
if (row > 0) {
for (int prevFillMask = toMoveMask; prevFillMask > 0; prevFillMask = (prevFillMask - 1) & toMoveMask) {
int bc1 = Integer.bitCount(freeCellsMask);
int bc2 = Integer.bitCount(prevFreeMask & prevFillMask);
res = Math.max(res, bc1 - bc2 + solve(row + 1, freeCellsMask, toMoveMask ^ prevFillMask));
}
}
res = Math.max(res, Integer.bitCount(freeCellsMask) + solve(row + 1, freeCellsMask, toMoveMask));
}
}
return memo[row][prevFreeMask][curStayMask] = res;
}
void run() {
N = nextInt();
M = nextInt();
if(M > N) {
int temp = M;
M = N;
N = temp;
}
this.memo = new int[N + 1][1<<M][1<<M];
for(int[][] g : memo) for(int[] f : g) Arrays.fill(f, -1);
System.out.println(solve(0, 0, 0));
}
int nextInt(){
try{
int c = System.in.read();
if(c == -1) return c;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return c;
}
if(c == '-') return -nextInt();
int res = 0;
do{
res *= 10;
res += c - '0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
long nextLong(){
try{
int c = System.in.read();
if(c == -1) return -1;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return -1;
}
if(c == '-') return -nextLong();
long res = 0;
do{
res *= 10;
res += c-'0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
double nextDouble(){
return Double.parseDouble(next());
}
String next(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(Character.isWhitespace(c))
c = System.in.read();
do{
res.append((char)c);
}while(!Character.isWhitespace(c=System.in.read()));
return res.toString();
}catch(Exception e){
return null;
}
}
String nextLine(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(c == '\r' || c == '\n')
c = System.in.read();
do{
res.append((char)c);
c = System.in.read();
}while(c != '\r' && c != '\n');
return res.toString();
}catch(Exception e){
return null;
}
}
public static void main(String[] args){
new TaskC().run();
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
/**
*
* @author is2ac
*/
public class C_CF {
public static void main(String[] args) {
FastScanner57 fs = new FastScanner57();
PrintWriter pw = new PrintWriter(System.out);
int t = fs.ni();
//int t = 1;
for (int tc = 0; tc < t; tc++) {
int n = fs.ni();
int[] q = new int[n+5];
int ind = 0;
q[0] = 1;
for (int i = 0; i < n; i++) {
int a = fs.ni();
while (q[ind]!=a) ind--;
StringBuilder sb = new StringBuilder();
for (int j = 0; j < ind; j++) {
sb.append(q[j]-1);
sb.append(".");
}
sb.append(a);
q[ind]++;
q[ind+1] = 1;
ind++;
pw.println(sb);
}
}
pw.close();
}
static class BIT18 {
int[] bit;
public BIT18(int size) {
bit = new int[size];
}
public void update(int ind, int delta) {
while (ind < bit.length) {
bit[ind] += delta;
ind = ind + (ind & (-1 * ind));
}
}
public int sum(int ind) {
int s = 0;
while (ind > 0) {
s += bit[ind];
ind = ind - (ind & (-1 * ind));
}
return s;
}
public int query(int l, int r) {
return sum(r) - sum(l);
}
}
// 0 -> left was chosen
// 1 -> right was chosen
public static long recur(int ind, int p, int prev, long[] v, Long[][] dp, long[][] lr, List<List<Integer>> list) {
long last = v[0];
long ls = 0L;
long rs = 0L;
if (p == 1) {
last = v[1];
}
if (ind != 0) {
ls += (long) Math.abs(last - lr[ind][0]);
}
if (ind != 0) {
rs += (long) Math.abs(last - lr[ind][1]);
}
if (dp[ind][p] != null) {
return dp[ind][p];
}
long[] cur = lr[ind];
List<Integer> temp = list.get(ind);
for (int val : temp) {
if (prev == val) {
continue;
}
ls += recur(val, 0, ind, cur, dp, lr, list);
rs += recur(val, 1, ind, cur, dp, lr, list);
}
return dp[ind][p] = Math.max(ls, rs);
}
public static void sort(long[] a) {
List<Long> list = new ArrayList();
for (int i = 0; i < a.length; i++) {
list.add(a[i]);
}
Collections.sort(list);
for (int i = 0; i < a.length; i++) {
a[i] = list.get(i);
}
}
public static long gcd(long n1, long n2) {
if (n2 == 0) {
return n1;
}
return gcd(n2, n1 % n2);
}
}
class UnionFind16 {
int[] id;
public UnionFind16(int size) {
id = new int[size];
for (int i = 0; i < size; i++) {
id[i] = i;
}
}
public int find(int p) {
int root = p;
while (root != id[root]) {
root = id[root];
}
while (p != root) {
int next = id[p];
id[p] = root;
p = next;
}
return root;
}
public void union(int p, int q) {
int a = find(p), b = find(q);
if (a == b) {
return;
}
id[b] = a;
}
}
class FastScanner57 {
BufferedReader br;
StringTokenizer st;
public FastScanner57() {
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[] intArray(int N) {
int[] ret = new int[N];
for (int i = 0; i < N; i++) {
ret[i] = ni();
}
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N) {
long[] ret = new long[N];
for (int i = 0; i < N; i++) {
ret[i] = nl();
}
return ret;
}
double nd() {
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.io.*;
import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
Scanner cin=new Scanner(new BufferedInputStream(System.in));
int n=cin.nextInt(),
m=cin.nextInt(),
k=cin.nextInt();
int[] a=new int[51];
for (int i=0;i<n;i++) {
a[i]=-cin.nextInt();
}
Arrays.sort(a);
if (m<=k) {
System.out.println(0);
return;
}
for (int i=0;i<Math.min(k,n);i++) {
m+=a[i];
if (m-(k-1-i)<=0) {
System.out.println(i+1);
return;
}
}
for (int i=k;i<n;i++) {
m+=a[i]+1;
if (m<=0) {
System.out.println(i+1);
return;
}
}
System.out.println(-1);
cin.close();
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.Collection;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Queue;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Nafiur Rahman Khadem Shafin 🙂
*/
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);
ProblemCFireAgain solver = new ProblemCFireAgain ();
solver.solve (1, in, out);
out.close ();
}
static class ProblemCFireAgain {
private static final byte[] dx = {-1, 0, 0, 1};
private static final byte[] dy = {0, -1, 1, 0};
private static int[][] lvl;
private static int max;
private static int n;
private static int m;
private static int k;
private static ProblemCFireAgain.Pair[] bgn;
private static ProblemCFireAgain.Pair res;
private static void bfs2d () {
Queue<ProblemCFireAgain.Pair> bfsq = new LinkedList<ProblemCFireAgain.Pair> ();
for (ProblemCFireAgain.Pair src : bgn) {
lvl[src.a][src.b] = 0;
bfsq.add (src);
}
while (!bfsq.isEmpty ()) {
ProblemCFireAgain.Pair op = bfsq.poll ();
int plvl = lvl[op.a][op.b];
// System.out.println ("ber hoise "+op+" "+plvl);
if (plvl>max) {
res = op;
max = plvl;
}
for (int i = 0; i<4; i++) {
int newX = op.a+dx[i];
int newY = op.b+dy[i];
// System.out.println (newX+" "+newY+" "+n+" "+m);
if (newX>0 && newX<=n && newY>0 && newY<=m && lvl[newX][newY] == -1) {
bfsq.add (new ProblemCFireAgain.Pair (newX, newY));
lvl[newX][newY] = (plvl+1);
// System.out.println ("dhukse "+newX+" "+newY);
}
}
}
}
public void solve (int testNumber, InputReader _in, PrintWriter _out) {
/*
* file input-output 😮. Multi source bfs. Same as snackdown problem.
* */
try (InputReader in = new InputReader (new FileInputStream ("input.txt"));
PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter ("output.txt")))) {
n = in.nextInt ();
m = in.nextInt ();
k = in.nextInt ();
bgn = new ProblemCFireAgain.Pair[k];
for (int i = 0; i<k; i++) {
bgn[i] = new ProblemCFireAgain.Pair (in.nextInt (), in.nextInt ());
}
max = Integer.MIN_VALUE;
lvl = new int[n+5][m+5];
for (int i = 0; i<n+4; i++) {
Arrays.fill (lvl[i], -1);
}
bfs2d ();
// System.out.println (max);
out.println (res);
} catch (Exception e) {
// e.printStackTrace ();
}
}
private static class Pair {
int a;
int b;
Pair (int a, int b) {
this.a = a;
this.b = b;
}
public String toString () {
return a+" "+b;
}
public boolean equals (Object o) {
if (this == o) return true;
if (!(o instanceof ProblemCFireAgain.Pair)) return false;
ProblemCFireAgain.Pair pair = (ProblemCFireAgain.Pair) o;
return a == pair.a && b == pair.b;
}
public int hashCode () {
return Objects.hash (a, b);
}
}
}
static class InputReader implements AutoCloseable {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader (InputStream stream) {
reader = new BufferedReader (new InputStreamReader (stream));
tokenizer = null;
}
public String next () {
while (tokenizer == null || !tokenizer.hasMoreTokens ()) {
try {
String str;
if ((str = reader.readLine ()) != null) tokenizer = new StringTokenizer (str);
else return null;//to detect eof
} catch (IOException e) {
throw new RuntimeException (e);
}
}
return tokenizer.nextToken ();
}
public int nextInt () {
return Integer.parseInt (next ());
}
public void close () throws Exception {
reader.close ();
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.Scanner;
public class prob1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
if(n == 1)
{
// throw new RuntimeException();
int m = input.nextInt();
System.out.println("NO");
// System.out.println(input.next());
return;
}
int[] num = new int[n];
boolean flag = false;
for(int i = 0; i < n; i++)
{
num[i] = input.nextInt();
if(num[i] != num[0])
flag = true;
}
if(!flag)
{
System.out.println("NO");
return;
}
int min = Integer.MAX_VALUE;
for(int i = 0; i < n; i++)
if(num[i] < min)
min = num[i];
int min2 = Integer.MAX_VALUE;
for(int i = 0; i < n; i++)
if(num[i] <= min2 && num[i] > min)
min2 = num[i];
System.out.println(min2);
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.*;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException
{
Scanner sc = new Scanner(new File("input.txt"));
int n = sc.nextInt();
int m =sc.nextInt();
sc.nextLine();
int k =sc.nextInt();
int les[][] = new int[n][m];
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//sc.nextLine();
ArrayList<Integer[]> list = new ArrayList();
sc.nextLine();
for(int i = 0;i<k;i++)
{
Integer[] ii = new Integer[2];
ii[0] = sc.nextInt()-1;
ii[1] = sc.nextInt()-1;
list.add(ii);
}
sc.close();
int maxr = 0;
int maxi = 0;
int maxj = 0;
for(int i = 0;i<n;i++)
{
for(int j = 0;j<m;j++)
{
int minr = 100000;
int mini = 0;
int minj = 0;
for(int f = 0;f<k;f++)
{
Integer[] ii = list.get(f);
int ww = Math.abs(ii[0] - i);
int hh = Math.abs(ii[1] - j);
int r = ww+hh;
if(r<minr)
{
minr = r;
mini=i;
minj=j;
}
}
if(maxr<minr&&minr<100000)
{
maxi = mini;
maxj = minj;
maxr = minr;
}
}
}
out.print((maxi+1)+" "+(maxj+1));
out.close();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class C364C {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
static int n;
static int[] a;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
n = nextInt();
int ans = n, cc, cur = 0;
a = new int [52];
char[] c = next().toCharArray();
int l = 0, len = 0;
for (int i = 0; i < n; ++i) {
if (Character.isUpperCase(c[i])) {
cur = 26 + c[i] - 'A';
} else
cur = c[i] - 'a';
if (a[cur] == 0) {
a[cur]++;
len++;
ans = i - l + 1;
} else {
a[cur]++;
for (; l < i; ++l) {
if (Character.isUpperCase(c[l])) {
cc = 26 + c[l] - 'A';
} else
cc = c[l] - 'a';
if (a[cc] > 1) {
--a[cc];
} else break;
}
if (i - l + 1 < ans) {
ans = i - l + 1;
}
}
}
/*int l = 0, r = n - 1;
for (l = 0; l < n; ++l) {
if (Character.isUpperCase(c[l])) {
if (a[26 + c[l] - 'A'] > 1) {
a[26 + c[l] - 'A']--;
} else break;
} else {
if (a[c[l] - 'a'] > 1) {
a[c[l] - 'a']--;
} else break;
}
}
for (r = n - 1; r >= 0; --r) {
if (Character.isUpperCase(c[r])) {
if (a[26 + c[r] - 'A'] > 1) {
a[26 + c[r] - 'A']--;
} else break;
} else {
if (a[c[r] - 'a'] > 1) {
a[c[r] - 'a']--;
} else break;
}
}*/
pw.print(ans);
pw.close();
}
private static int sumf(int[] fen, int id) {
int summ = 0;
for (; id >= 0; id = (id & (id + 1)) - 1)
summ += fen[id];
return summ;
}
private static void addf(int[] fen, int id) {
for (; id < fen.length; id |= id + 1)
fen[id]++;
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Sol122A {
BufferedReader in;
StringTokenizer st;
PrintWriter out;
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(next());
}
long nextLong() throws Exception {
return Long.parseLong(next());
}
double nextDouble() throws Exception {
return Double.parseDouble(next());
}
void solve() throws Exception {
long x = nextLong();
out.println((x % 4) * (x % 7) * (x % 74) * (x % 47) * (x % 44) * (x % 77) * (x % 444) * (x % 447) * (x % 474) * (x % 477) * (x % 744) * (x % 747) * (x % 774) * (x % 777) == 0 ? "YES" : "NO");
}
void run() {
try {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
new Sol122A().run();
}
}
|
constant
|
122_A. Lucky Division
|
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 sumit
*/
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);
CChessboard solver = new CChessboard();
solver.solve(1, in, out);
out.close();
}
static class CChessboard {
int[] nextPermutation(int[] array) {
int i = array.length - 1;
while (i > 0 && array[i - 1] >= array[i]) {
i--;
}
if (i <= 0) {
return null;
}
int j = array.length - 1;
while (array[j] <= array[i - 1]) {
j--;
}
int temp = array[i - 1];
array[i - 1] = array[j];
array[j] = temp;
j = array.length - 1;
while (i < j) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
return array;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int arr[][][] = new int[4][n][n];
int sum[] = new int[4];
for (int k = 0; k < 4; k++) {
for (int i = 0; i < n; i++) {
String str = in.next();
for (int j = 0; j < n; j++) {
arr[k][i][j] = (str.charAt(j) - '0');
}
}
}
for (int k = 0; k < 4; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((i + j) % 2 == arr[k][i][j])
sum[k]++;
}
}
}
int perm[] = new int[4];
for (int i = 0; i < 4; i++)
perm[i] = i;
int min = Integer.MAX_VALUE;
while (true) {
perm = nextPermutation(perm);
if (perm == null)
break;
int sm = 0;
for (int j = 0; j < 4; j++) {
if (j % 2 == 0) {
sm += (sum[perm[j]]);
} else {
sm += (n * n - sum[perm[j]]);
}
}
min = Math.min(min, sm);
sm = 0;
for (int j = 0; j < 4; j++) {
if (j % 2 == 0) {
sm += (n * n - sum[perm[j]]);
} else {
sm += (sum[perm[j]]);
}
}
min = Math.min(sm, min);
}
out.printLine(min);
}
}
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 InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
quadratic
|
961_C. Chessboard
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String[] args) {
// long start = System.currentTimeMillis();
// long end = System.currentTimeMillis();
// System.out.println(" Execution time was "+(end-start)+" ms.");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for(int i = 0;i<n;i++){
a[i]=kb.nextInt();
b[i]=a[i];
}
Arrays.sort(a);
int count = 0;
for(int i=0;i<n;i++){
if(a[i]!=b[i])count++;
}
if(count<=2)
System.out.println("YES");
else
System.out.println("NO");
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
/**
*
* @author saurabh
*/
public class myTemplate {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception{
// TODO code application logic here
java.io.BufferedReader br = new java.io.BufferedReader(new
java.io.InputStreamReader(System.in));
int ch[],arr[];
int x,i,j,k,t,n=Integer.parseInt(br.readLine());
//System.out.println(n);
if(n>0)
System.out.println(n);
else
{
//n= -n;
//n=-n;
x= n/100;
x = x*10 + n%10;
// System.out.println(x);
if(n/10 > x)
System.out.println(n/10);
else
System.out.println(x);
}
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc =new Scanner(System.in);
long a=sc.nextLong();
if(a%4==0){System.out.println(a/2 + " " + a/2);}
if(a%4==1){System.out.println(9 + " " + (a-9));}
if(a%4==2){System.out.println(6 + " " + (a-6));}
if(a%4==3 && a>15){System.out.println(15 + " " + (a-15));}
if(a==15){System.out.println("6 9");}
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
//package Round584;
import java.util.Arrays;
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
int a []=new int[n];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
Arrays.sort(a);
// System.out.println(Arrays.toString(a));
int k=a.length;
for(int i=a.length-1;i>=0;i--) {
int A=a[i];
for (int j=0;j<i;j++) {
if(A%a[j]==0) {
k--;
break;
}
}
}
System.out.println(k);
sc.close();
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class CottageVillage
{
Scanner in;
PrintWriter out;
CottageVillage()
{
in = new Scanner(System.in);
out = new PrintWriter(System.out);
}
public void finalize()
{
out.flush();
in.close();
out.close();
}
int ans(House a, House b, int t)
{
int diff = b.cordl - a.cordr;
if(diff < t) return 0;
if(diff == t) return 1;
return 2;
}
void solve()
{
int
n = in.nextInt(),
t = in.nextInt() * 2;
House[] hs = new House[n];
for(int i = 0; i < n; ++i)
{
int
c = in.nextInt(),
l = in.nextInt();
hs[i] = new House(2 * c - l, 2 * c + l);
}
Arrays.sort(hs);
//atleast 2 possible configs
int co = 2;
for(int i = 0; i < n - 1; ++i)
co += ans(hs[i], hs[i + 1], t);
out.println(co);
}
public static void main(String[] args) throws FileNotFoundException
{
CottageVillage t = new CottageVillage();
t.solve();
t.finalize();
}
}
class House implements Comparable<House>
{
public int cordl, cordr;
public House(int c, int l)
{
cordl = c;
cordr = l;
}
@Override
public int compareTo(House h)
{
return cordl - h.cordl;
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.*;
public class IQTest
{
public static void main(String[] args)
{
try
{
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String str = in.readLine();
int n = Integer.parseInt(str);
int odd = -1, even = -1, odds = 0, evens = 0;
//while (n-- > 0)
//{
str = in.readLine();
String[] numbers = str.split(" ");
int index = 1;
for (String number: numbers)
{
int i = Integer.parseInt(number);
if (i % 2 == 0)
{
++evens;
if (even == -1)
even = index;
}
else
{
++odds;
if (odd == -1)
odd = index;
}
++index;
}
//}
System.out.println((evens > odds ? odd : even));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
// Author : RegalBeast
import java.io.*;
import java.util.*;
public class Main {
static final FastReader FR = new FastReader();
static final BufferedWriter BW = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException {
StringBuilder solution = new StringBuilder();
int rows = FR.nextInt();
int cols = FR.nextInt();
int moves = FR.nextInt();
Map<Integer, Integer> horizontalEdgeWeights = new HashMap<Integer, Integer>();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols - 1; c++) {
int hash = getHash(r, c);
horizontalEdgeWeights.put(hash, FR.nextInt());
}
}
Map<Integer, Integer> verticalEdgeWeights = new HashMap<Integer, Integer>();
for (int r = 0; r < rows - 1; r++) {
for (int c = 0; c < cols; c++) {
int hash = getHash(r, c);
verticalEdgeWeights.put(hash, FR.nextInt());
}
}
List<List<Integer>> result = getResult(rows, cols, moves, horizontalEdgeWeights, verticalEdgeWeights);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
int value = (result != null ? result.get(r).get(c) : -1);
solution.append(value + " ");
}
solution.append("\n");
}
BW.write(solution.toString());
BW.close();
}
static List<List<Integer>> getResult(int rows, int cols, int moves, Map<Integer, Integer> horizontalEdgeWeights, Map<Integer, Integer> verticalEdgeWeights) {
if ((moves & 1) == 1) {
return null;
}
int mid = moves >> 1;
List<List<List<Integer>>> minForDistance = new ArrayList<List<List<Integer>>>(rows);
for (int r = 0; r < rows; r++) {
minForDistance.add(new ArrayList<List<Integer>>(cols));
for (int c = 0; c < cols; c++) {
minForDistance.get(r).add(new ArrayList<Integer>(Collections.nCopies(mid+1, Integer.MAX_VALUE)));
minForDistance.get(r).get(c).set(0, 0);
}
}
for (int m = 1; m <= mid; m++) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
int minBoredom = minForDistance.get(r).get(c).get(m);
int hash = getHash(r, c);
if (r > 0) {
if (minForDistance.get(r-1).get(c).get(m-1) < Integer.MAX_VALUE) {
int candidateBoredom = minForDistance.get(r-1).get(c).get(m-1) + verticalEdgeWeights.get(getHash(r-1, c));
minBoredom = Math.min(minBoredom, candidateBoredom);
}
}
if (c > 0) {
if (minForDistance.get(r).get(c-1).get(m-1) < Integer.MAX_VALUE) {
int candidateBoredom = minForDistance.get(r).get(c-1).get(m-1) + horizontalEdgeWeights.get(getHash(r, c-1));
minBoredom = Math.min(minBoredom, candidateBoredom);
}
}
if (r + 1 < rows) {
if (minForDistance.get(r+1).get(c).get(m-1) < Integer.MAX_VALUE) {
int candidateBoredom = minForDistance.get(r+1).get(c).get(m-1) + verticalEdgeWeights.get(hash);
minBoredom = Math.min(minBoredom, candidateBoredom);
}
}
if (c + 1 < cols) {
if (minForDistance.get(r).get(c+1).get(m-1) < Integer.MAX_VALUE) {
int candidateBoredom = minForDistance.get(r).get(c+1).get(m-1) + horizontalEdgeWeights.get(hash);
minBoredom = Math.min(minBoredom, candidateBoredom);
}
}
minForDistance.get(r).get(c).set(m, minBoredom);
}
}
}
List<List<Integer>> result = new ArrayList<List<Integer>>(rows);
for (int r = 0; r < rows; r++) {
result.add(new ArrayList<Integer>(cols));
for (int c = 0; c < cols; c++) {
result.get(r).add(minForDistance.get(r).get(c).get(mid) << 1);
}
}
return result;
}
static int getHash(int row, int col) {
return (row * 1000 + col);
}
static int getRow(int hash) {
return hash / 1000;
}
static int getCol(int hash) {
return hash % 1000;
}
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
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.util.Scanner;
public class A023 {
public static void main(String[] args) {
System.out.println(f());
}
static int f() {
Scanner in = new Scanner(System.in);
String line = in.next();
for (int length = line.length(); length > 0; length--) {
for (int start = 0; start + length <= line.length(); start++) {
if(line.indexOf(line.substring(start,start+length),start+1)>=0) {
return length;
}
}
}
return 0;
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main
{
long mod = 1000000007;
long pow(long x,long y)
{
if(y==0)
return 1;
else if(y==1)
return x%mod;
else if(y%2==0)
return pow((x*x)%mod,y/2)%mod;
else
return (x*pow((x*x)%mod,y/2)%mod)%mod;
}
void solve()
{
FastReader sc =new FastReader();
long x = sc.nextLong();
long k = sc.nextLong();
if(x == 0) {
System.out.println(0);
return;
}
long ans = pow(2, k);
x = (2*x)%mod;
x = (x - 1 + mod)%mod;
ans = (ans*x)%mod;
ans = (ans + 1)%mod;
System.out.println(ans);
}
public static void main(String[] args)
{
new Main().solve();
}
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
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.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 John Martin
*/
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);
ASubtractions solver = new ASubtractions();
solver.solve(1, in, out);
out.close();
}
static class ASubtractions {
public void solve(int testNumber, InputReader c, OutputWriter w) {
int tc = c.readInt();
while (tc-- > 0) {
int a = c.readInt(), b = c.readInt();
int res = 0;
while (a != 0 && b != 0) {
res += b / a;
b = b % a;
int t = b;
b = a;
a = t;
}
w.printLine(res);
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.lang.*;
import java.util.*;
import java.io.*;
public class Main {
static void deal(int n,int[] arr) {
int[] a = new int[n];
a[0] = 1;
int l = 1;
out.println(toString(a,l));
for(int i=1;i<n;i++) {
if(arr[i] == 1) {
a[l] = 1;
l++;
} else {
int index = l-1;
while(index>=0 && a[index] != arr[i]-1) {
index--;
}
a[index]++;
l = index+1;
}
out.println(toString(a,l));
}
}
static String toString(int[] arr,int l) {
StringBuilder sb = new StringBuilder();
for(int i=0;i<l-1;i++) {
sb.append(arr[i]);
sb.append('.');
}
sb.append(arr[l-1]);
return sb.toString();
}
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int t = sc.nextInt();
for(int i=0;i<t;i++) {
int n = sc.nextInt();
int[] arr = new int[n];
for(int j=0;j<n;j++) arr[j] = sc.nextInt();
deal(n,arr);
}
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class ProblemD_05 {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException{
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException{
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException{
return Integer.parseInt(readString());
}
long readLong() throws IOException{
return Long.parseLong(readString());
}
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
public static void main(String[] args){
new ProblemD_05().run();
}
public void run(){
try{
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = "+(t2-t1));
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
void solve() throws IOException{
double a = readDouble();
double v = readDouble();
double l = readDouble();
double d = readDouble();
double w = readDouble();
double t = 0;
double td = d > v * v / (2 * a)? v / a + (d - v * v / (2 * a)) / v: sqrt(2 *d / a);
if (w >= min(a * td, v)){
t += td;
w = min(a * td, v);
}else{
double v0 = sqrt(w * w / 2 + a * d);
if (v0 * v0 <= v * v){
t += (2 * v0 - w) / a;
}else{
t += (2 * v - w) / a;
double s2 = d - (2 * v * v - w * w) / (2 * a);
t += s2 / v;
}
}
double t1 = (sqrt(w * w + 2 * a * (l - d)) - w) / a;
if (t1 > (v - w) / a) t1 = (v - w) / a;
t += t1;
double s1 = w * t1 + a * t1 * t1 / 2;
double t2 = (l - d - s1) / v;
t += t2;
out.printf(Locale.US, "%.12f", t);
}
static int[][] step8 = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, -1}, {-1, 1}, {1, 1}};
static int[][] stepKnight = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}};
static long gcd(long a, long b){
if (a == 0) return b;
return gcd(b % a, a);
}
static long lcm(long a, long b){
return a / gcd(a, b)*b;
}
static long[] gcdPlus(long a, long b){
long[] d = new long[3];
if (a == 0){
d[0] = b;
d[1] = 0;
d[2] = 1;
}else{
d = gcdPlus(b % a, a);
long r = d[1];
d[1] = d[2] - b/a*d[1];
d[2] = r;
}
return d;
}
static long binpow(long a, int n){
if (n == 0) return 1;
if ((n & 1) == 0){
long b = binpow(a, n/2);
return b*b;
}else return binpow(a, n - 1)*a;
}
static long binpowmod(long a, int n, long m){
if (m == 1) return 0;
if (n == 0) return 1;
if ((n & 1) == 0){
long b = binpowmod(a, n/2, m);
return (b*b) % m;
}else return binpowmod(a, n - 1, m)*a % m;
}
static long phi(long n){
int[] p = Sieve((int)ceil(sqrt(n)) + 2);
long phi = 1;
for (int i = 0; i < p.length; i++){
long x = 1;
while (n % p[i] == 0){
n /= p[i];
x *= p[i];
}
phi *= x - x/p[i];
}
if (n != 1) phi *= n - 1;
return phi;
}
static long f(long n, int x, int k){ //Кол-во десятичных чисел (включая 0), содержащих в себе цифры от 0 до k-1
if (n == 0) return 1;
long b = binpow(10, x - 1);
long c = n / b;
return (c < k? c: k)*binpow(k, x - 1) + (c < k? 1: 0)*f(n % b, x - 1, k);
}
static long fib(int n){
if (n == 0) return 0;
if ((n & 1) == 0){
long f1 = fib(n/2 - 1);
long f2 = fib(n/2 + 1);
return f2*f2 - f1*f1;
}else{
long f1 = fib(n/2);
long f2 = fib(n/2 + 1);
return f1*f1 + f2*f2;
}
}
static BigInteger BigFib(int n){
if (n == 0) return BigInteger.ZERO;
if ((n & 1) == 0){
BigInteger f1 = BigFib(n/2 - 1);
f1 = f1.multiply(f1);
BigInteger f2 = BigFib(n/2 + 1);
f2 = f2.multiply(f2);
return f2.subtract(f1);
}else{
BigInteger f1 = BigFib(n/2);
f1 = f1.multiply(f1);
BigInteger f2 = BigFib(n/2 + 1);
f2 = f2.multiply(f2);
return f2.add(f1);
}
}
static public class PointD{
double x, y;
public PointD(double x, double y){
this.x = x;
this.y = y;
}
}
static double d(Point p1, Point p2){
return sqrt(d2(p1, p2));
}
static public double d(PointD p1, PointD p2){
return sqrt(d2(p1, p2));
}
static double d2(Point p1, Point p2){
return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
}
static public double d2(PointD p1, PointD p2){
return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
}
static boolean IsProbablyPrime(long n){
if (n == 1) return false;
if ((n & 1) == 0) return false;
for (int j = 3; j < sqrt(n) + 1; j += 2){
if (n % j == 0) return false;
}
return true;
}
static int[] Sieve(int n){
boolean[] b = new boolean[n+1];
Arrays.fill(b, true);
b[0] = false;
b[1] = false;
long nLong = n;
int j=0;
for (int i = 1; i <= n; i++) {
if (b[i]){
j++;
if (((long)i)*i <= nLong) {
for (int k = i*i; k <= n; k += i) {
b[k] = false;
}
}
}
}
int[] p = new int[j];
Arrays.fill(p, 0);
j=0;
for (int i = 2; i <= n; i++) {
if (b[i]){
p[j]=i;
j++;
}
}
return p;
}
static int[][] Palindromes(String s){
char[] c = s.toCharArray();
int n = c.length;
int[][] d = new int[2][n];
int l = 0, r = -1;
for (int i = 0; i < n; i++){
int j = (i > r? 0: min(d[0][l+r-i+1], r-i+1)) + 1;
for (; i - j >= 0 && i + j - 1< n && c[i-j] == c[i+j-1]; j++);
d[0][i] = --j;
if (i + d[0][i] - 1 > r){
r = i + d[0][i] - 1;
l = i - d[0][i];
}
}
l = 0;
r = -1;
for (int i = 0; i < n; i++){
int j = (i > r? 0: min(d[1][l+r-i], r-i)) + 1;
for (; i - j >= 0 && i + j < n && c[i-j] == c[i+j]; j++);
d[1][i] = --j;
if (i + d[1][i] > r){
r = i + d[1][i];
l = i - d[1][i];
}
}
return d;
}
static public class Permutation {
int[] a;
int n;
public Permutation(int n){
this.n=n;
a=new int[n];
for (int i=0; i<n; i++){
a[i]=i;
}
}
public boolean nextPermutation(){ //Пишется с do{}while(nextPermutation(a));
int i=n-1;
for (i=n-2; i>=0; i--){
if (a[i]<a[i+1]){
break;
}
}
if (i==-1){
return false;
}
int jMin=i+1;
for (int j=n-1; j>i; j--){
if (a[i]<a[j]&&a[j]<a[jMin]){
jMin=j;
}
}
swap(i, jMin);
for (int j=1; j<=(n-i)/2; j++){
swap(i+j, n-j);
}
return true;
}
public int get(int i){
return a[i];
}
void swap(int i, int j){
int r=a[i];
a[i]=a[j];
a[j]=r;
}
}
static public class Fraction implements Comparable<Fraction>, Cloneable{
public final Fraction FRACTION_ZERO = new Fraction();
public final Fraction FRACTION_ONE = new Fraction(1);
public long numerator = 0;
public long denominator = 1;
public Fraction(){
numerator = 0;
denominator = 1;
}
public Fraction(long numerator){
this.numerator = numerator;
denominator = 1;
}
public Fraction(long numerator, long denominator){
this.numerator = numerator;
this.denominator = denominator;
Cancellation();
}
public Fraction(double numerator, double denominator, int accuracy){
this.numerator = (long)(numerator*pow(10,accuracy));
this.denominator = (long)(denominator*pow(10,accuracy));
Cancellation();
}
public Fraction(String s){
if (s.charAt(0) == '-'){
denominator = -1;
s = s.substring(1);
}
if (s.indexOf("/") != -1){
denominator *= Integer.parseInt(s.substring(s.indexOf("/") + 1));
}
if (s.indexOf(" ") != -1){
numerator = Integer.parseInt(s.substring(0, s.indexOf(" "))) * abs(denominator) + Integer.parseInt(s.substring(s.indexOf(" ") + 1, s.indexOf("/")));
}else{
if (s.indexOf("/") != -1){
numerator = Integer.parseInt(s.substring(0, s.indexOf("/")));
}else{
numerator = Integer.parseInt(s)*abs(denominator);
}
}
this.Cancellation();
}
void Cancellation(){
long g = gcd(abs(numerator), abs(denominator));
numerator /= g;
denominator /= g;
if (denominator < 0){
numerator *= -1;
denominator *= -1;
}
}
public String toString(){
String s = "";
if (numerator == 0){
return "0";
}
if (numerator < 0){
s += "-";
}
if (abs(numerator) >= denominator){
s += Long.toString(abs(numerator) / denominator) + " ";
}
if (abs(numerator) % denominator != 0){
s += Long.toString(abs(numerator) % denominator);
}else{
s = s.substring(0, s.length()-1);
}
if (denominator != 1){
s += "/" + Long.toString(denominator);
}
return s;
}
public Fraction add(Fraction f){
Fraction fResult = new Fraction();
fResult.denominator = lcm(denominator, f.denominator);
fResult.numerator = numerator * fResult.denominator / denominator + f.numerator * fResult.denominator / f.denominator;
fResult.Cancellation();
return fResult;
}
public Fraction subtract(Fraction f){
Fraction fResult = new Fraction();
fResult.denominator = lcm(denominator, f.denominator);
fResult.numerator = numerator * fResult.denominator / denominator - f.numerator * fResult.denominator / f.denominator;
fResult.Cancellation();
return fResult;
}
public Fraction multiply(Fraction f){
Fraction fResult = new Fraction();
fResult.numerator = numerator * f.numerator;
fResult.denominator = denominator * f.denominator;
fResult.Cancellation();
return fResult;
}
public Fraction divide(Fraction f){
Fraction fResult = new Fraction();
fResult.numerator = numerator * f.denominator;
fResult.denominator = denominator * f.numerator;
fResult.Cancellation();
return fResult;
}
@Override
public int compareTo(Fraction f){
long g = gcd(denominator, f.denominator);
long res = numerator * (f.denominator / g) - f.numerator * (denominator / g);
if (res < 0){
return -1;
}
if (res > 0){
return 1;
}
return 0;
}
public Fraction clone(){
Fraction fResult = new Fraction(numerator, denominator);
return fResult;
}
public Fraction floor(){
Fraction fResult = this.clone();
fResult.numerator = (fResult.numerator / fResult.denominator) * fResult.denominator;
return fResult;
}
public Fraction ceil(){
Fraction fResult = this.clone();
fResult.numerator = (fResult.numerator/fResult.denominator + 1) * fResult.denominator;
return fResult;
}
public Fraction binpow(int n){
if (n==0) return FRACTION_ONE;
if ((n&1)==0){
Fraction f=this.binpow(n/2);
return f.multiply(f);
}else return binpow(n-1).multiply(this);
}
}
static public class FenwickTree_1{ //One-dimensional array
int n;
long[] t;
public FenwickTree_1(int n){
this.n = n;
t = new long[n];
}
public long sum(int xl, int xr){
return sum(xr) - sum(xl);
}
public long sum(int x){
long result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1){
result += t[i];
}
return result;
}
public void update(int x, long delta){
for (int i = x; i < n; i = (i | (i + 1))){
t[i] += delta;
}
}
}
static public class FenwickTree_2{ //Two-dimensional array
int n, m;
long[][] t;
public FenwickTree_2(int n, int m){
this.n = n;
this.m = m;
t = new long[n][m];
}
public long sum(int xl, int yl, int xr, int yr){
return sum(xr, yr) - sum(xl - 1, yr) - sum(xr, yl - 1) + sum(xl - 1, yl - 1);
}
public long sum(int x, int y){
long result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1){
for (int j = y; j >= 0; j = (j & (j + 1)) - 1){
result+=t[i][j];
}
}
return result;
}
public void update(int x, int y, long delta){
for (int i = x; i < n; i = (i | (i + 1))){
for (int j = y; j < m; j = (j | (j + 1))){
t[i][j] += delta;
}
}
}
}
static public class FenwickTree_3{ //Three-dimensional array
int n, m, l;
long[][][] t;
public FenwickTree_3(int n, int m, int l){
this.n = n;
this.m = m;
this.l = l;
t = new long[n][m][l];
}
public long sum(int xl, int yl, int zl, int xr, int yr, int zr){
return sum(xr, yr, zr) - sum(xl - 1, yr, zr)
+ sum(xl - 1, yr, zl - 1) - sum(xr, yr, zl - 1)
- sum(xr, yl - 1, zr) + sum(xl - 1, yl - 1, zr)
- sum(xl - 1, yl - 1, zl - 1) + sum(xr, yl - 1, zl - 1);
}
public long sum(int x, int y, int z){
long result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1){
for (int j = y; j >= 0; j = (j & (j + 1)) - 1){
for (int k = z; k >= 0; k = (k & (k + 1)) - 1){
result += t[i][j][k];
}
}
}
return result;
}
public void update(int x, int y, int z, long delta){
for (int i = x; i < n; i = (i | (i + 1))){
for (int j = y; j < n; j = (j | (j + 1))){
for (int k = z; k < n; k = (k | (k + 1))){
t[i][j][k] += delta;
}
}
}
}
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Round111A {
public static void main(String[] args) throws IOException {
new Round111A().run();
}
public void run() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Scanner scanner = new Scanner(reader);
PrintWriter writer = new PrintWriter(System.out);
int n = scanner.nextInt();
int sum = 0;
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
sum += a[i];
}
Arrays.sort(a, Collections.reverseOrder());
int s = 0;
int i = 0;
while (i < n && (s <= sum / 2)) {
s += a[i];
i++;
}
writer.print(i);
scanner.close();
writer.close();
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class P19 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
Map<Integer, Integer> mapa = new HashMap<Integer, Integer>();
String str = in.next();
int len = str.length();
int maxCurrent = 0;
for (int i = 0; i < len; ++i) {
for (int j = 1; j <= len; ++j) {
if (i + j > len) continue;
//System.out.format("Adding from %d to %d -> %s\n",i, i+j,str.substring(i, i + j));
int hashCode = str.substring(i, i + j).hashCode();
Integer current = mapa.get(hashCode);
if (current == null)
current = 0;
current++;
mapa.put(hashCode, current);
if (current > 1)
maxCurrent = Math.max(maxCurrent, j);
}
}
out.println(maxCurrent);
out.flush();
out.close();
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class A {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// BufferedReader rd = new BufferedReader(new
// InputStreamReader(System.in));
// StringTokenizer t = new StringTokenizer(rd.readLine(), " ");
int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt();
int pl[] = new int[n];
if (k >= m) {
System.out.println(0);
System.exit(0);
}
m -= k;
for (int i = 0; i < n; i++) {
pl[i] = sc.nextInt() - 1;
}
Arrays.sort(pl);
int out = 0;
for (int i = n - 1; i >= 0; i--) {
m -= pl[i];
out++;
if (m <= 0)
break;
}
if (m <= 0)
System.out.println(out);
else
System.out.println(-1);
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
//package CodeForces3;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author DELL
*/
public class HexadecimalsTheorem {
public void solve() {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
ArrayList<Long> a = new ArrayList<Long>();
a.add(0l);
a.add(1L);
a.add(1L);
int i = 1, j = 2;
while ((a.get(i) + a.get(j)) <= n) {
a.add((a.get(i) + a.get(j)));
i++;
j++;
}
if (a.contains(n)) {
if (n == 0) {
System.out.println("0 0 0");
} else if (n == 1) {
System.out.println("0 0 1");
} else if (n == 2) {
System.out.println("0 1 1");
} else {
System.out.println(a.get(j - 4) + " " + a.get(j - 3) + " " + a.get(j - 1));
}
} else {
System.out.println("I'm too stupid to solve this problem");
}
}
public static void main(String[] args) {
new HexadecimalsTheorem().solve();
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class C {
public static void main(String[] args) throws Exception {
final int fuck = 2001;
Scanner in = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter(new File("output.txt"));
int n = in.nextInt(), m = in.nextInt();
int[] D = new int[ fuck*fuck ],
dx = new int[] { 1, -1, 0, 0},
dy = new int[] { 0, 0, -1, 1};
Arrays.fill(D, -1);
ArrayDeque<Integer> Q = new ArrayDeque<>();
int k = in.nextInt(), ans = 0;
for(int i = 0; i < k; ++i) {
int x = in.nextInt(), y = in.nextInt();
D[ans = (x * fuck + y)] = 0;
Q.offer(ans);
}
while(!Q.isEmpty()) {
int idx = Q.poll();
int x = idx / fuck, y = idx % fuck;
for(int i = 0; i < 4; ++i) {
int wtf = (dx[i] + x) * fuck + (dy[i] + y);
if(dx[i] + x <= n && dx[i] + x >= 1 && dy[i] + y <= m && dy[i] + y >= 1 && D[wtf] == -1) {
D[wtf] = D[idx] + 1;
Q.offer(wtf);
if(D[wtf] >= D[ans])
ans = wtf;
}
}
}
out.println((ans / fuck) + " " + (ans % fuck));
out.close();
in.close();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
/**
*
* @author rohan
*/
public class Main {
static int mod = (int) (1e9+7);
static int MAX = (int)2e5+5;
static void solve()
{
int n = i();
String[] s = new String[n];
for(int i = 0 ; i<n ; i++)
{
s[i] = s();
}
int[][] dp = new int[n][n];
dp[0][0] = 1;
for(int i = 1; i<n; i++)
{
if(s[i-1].equals("f"))
{
for (int j = i-1 ; j>=0 ; j--)
{
dp[i][j+1] = dp[i-1][j];
}
}
else
{
int suff = 0;
for(int j = i-1; j>=0 ; j--)
{
suff += dp[i-1][j];
if(suff>=mod) suff-= mod;
dp[i][j] = suff;
}
}
}
int sum = 0;
for (int i=0 ; i<n; i++)
{
sum = sum+dp[n-1][i];
if(sum>=mod)
sum-=mod;
}
out.println(sum);
out.close();
}
///////////////////////////////////////////////////////////////////
static InputReader sc = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args)
{
new Thread(null,new Runnable() {
@Override
public void run() {
try{
solve();
}
catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<26).start();
}
static class Pair implements Comparable<Pair>{
int x,y,i;
Pair (int x,int y,int i)
{
this.x = x;
this.y = y;
this.i = i;
}
Pair (int x,int y)
{
this.x = x;
this.y = y;
}
public int compareTo(Pair o)
{
return -(this.y-o.y);
}
public boolean equals(Object o)
{
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y==y;
}
return false;
}
@Override
public String toString()
{
return x + " "+ y + " "+i;
}
public int hashCode()
{
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}
}
static class Merge
{
public static void sort(int inputArr[])
{
int length = inputArr.length;
doMergeSort(inputArr,0, length - 1);
}
private static void doMergeSort(int[] arr,int lowerIndex, int higherIndex) {
if (lowerIndex < higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
doMergeSort(arr,lowerIndex, middle);
doMergeSort(arr,middle + 1, higherIndex);
mergeParts(arr,lowerIndex, middle, higherIndex);
}
}
private static void mergeParts(int[]array,int lowerIndex, int middle, int higherIndex)
{
int[] temp=new int[higherIndex-lowerIndex+1];
for (int i = lowerIndex; i <= higherIndex; i++) {
temp[i-lowerIndex] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (temp[i-lowerIndex] < temp[j-lowerIndex])
{
array[k] = temp[i-lowerIndex];
i++;
}
else
{
array[k] = temp[j-lowerIndex];
j++;
}
k++;
}
while (i <= middle) {
array[k] = temp[i-lowerIndex];
k++;
i++;
}
while(j<=higherIndex){
array[k]=temp[j-lowerIndex];
k++;
j++;
}
}
}
static long add(long a,long b){
long x=(a+b);
while(x>=mod) x-=mod;
return x;
}
static long sub(long a,long b){
long x=(a-b);
while(x<0) x+=mod;
return x;
}
static long mul(long a,long b){
a%=mod;
b%=mod;
long x=(a*b);
return x%mod;
}
static boolean isPal(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long gcd(long x,long y){
if(y==0)
return x;
else
return gcd(y,x%y);
}
static int gcd(int x,int y){
if(y==0)
return x;
else
return gcd(y,x%y);
}
static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
static long mulmod(long a,long b,long m) {
if (m <= 1000000009) return a * b % m;
long res = 0;
while (a > 0)
{
if ((a&1)!=0)
{
res += b;
if (res >= m) res -= m;
}
a >>= 1;
b <<= 1;
if (b >= m) b -= m;
}
return res;
}
static int abs(int a,int b){
return (int)Math.abs(a-b);
}
public static long abs(long a,long b){
return (long)Math.abs(a-b);
}
static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static int i()
{
return sc.nextInt();
}
static long l(){
return sc.nextLong();
}
static int[] iarr(int n)
{
return sc.nextIntArray(n);
}
static long[] larr(int n)
{
return sc.nextLongArray(n);
}
static String s(){
return sc.nextLine();
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.*;
public class C {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long s = sc.nextLong();
BigInteger k = findFirst(BigInteger.valueOf(s));
if (BigInteger.valueOf(n).compareTo(k) >= 0)
{
System.out.println(n - k.longValue() + 1);
}
else
{
System.out.println("0");
}
}
public static BigInteger findFirst(BigInteger s) // first number where sum of digs >= s
{
BigInteger b = BigInteger.ZERO;
while (cd(b).compareTo(b.subtract(s)) > 0)
{
BigInteger c = BigInteger.ONE;
while (cd(b.add(c)).compareTo(b.add(c).subtract(s)) > 0) {
c = c.multiply(BigInteger.TEN);
}
// possibly overshot
c = c.divide(BigInteger.TEN);
if (c.compareTo(BigInteger.TEN) < 0) c = BigInteger.TEN; // always add at least 10
b = b.add(c);
}
return b;
}
public static BigInteger cd(BigInteger n)
{
BigInteger t = BigInteger.ZERO;
while (n.compareTo(BigInteger.ZERO) > 0)
{
t = t.add(n.mod(BigInteger.TEN));
n = n.divide(BigInteger.TEN);
}
return t;
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.util.*;
public class A {
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
long l = in.nextLong();
long r = in.nextLong();
if(r - l < 2) System.out.println(-1);
else {
if(l % 2 == 0)
System.out.println(l + " " + (l+1) + " " + (l+2));
else {
if(r - l < 3) System.out.println(-1);
else
System.out.println((l+1) + " " + (l+2) + " " + (l+3));
}
}
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ProblemA {
private final BufferedReader in;
private final PrintStream out;
private StringTokenizer tok = new StringTokenizer("");
private String nextLine = null;
public static void main(String[] args) throws Exception {
new ProblemA();
}
private ProblemA() throws Exception {
in = new BufferedReader(new InputStreamReader(System.in));
out = System.out;
start();
end();
}
private int nextInt() {
return Integer.parseInt(nextWord());
}
private String nextWord() {
if (tok.hasMoreTokens()) {
return tok.nextToken();
} else {
while (!tok.hasMoreTokens()) {
try {
nextLine = in.readLine();
if (nextLine == null) {
return null;
} else {
tok = new StringTokenizer(nextLine);
}
} catch (IOException ex) {
Logger.getLogger(ProblemA.class.getName()).log(Level.SEVERE, null, ex);
}
}
return tok.nextToken();
}
}
private void start() {
int n = nextInt();
int k = nextInt();
T[] ts = new T[n];
for (int i = 0; i < n; i++) {
ts[i] = new T(nextInt(), nextInt());
}
Arrays.sort(ts, new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
if (o1.p > o2.p) {
return -1;
}
if (o1.p < o2.p) {
return 1;
}
if (o1.t < o2.t) {
return -1;
}
if (o1.t > o2.t) {
return 1;
}
return 0;
}
});
int t = ts[k - 1].t;
int p = ts[k - 1].p;
int res = 0;
for (int i = 0; i < n; i++) {
if (ts[i].p == p && ts[i].t == t) {
res++;
}
}
out.println(res);
}
class T {
int p;
int t;
public T(int p, int t) {
this.p = p;
this.t = t;
}
}
private void end() {
out.close();
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {
}
new Thread() {
public void run() {
try {
new Main().run();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
private void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
boolean[] pr = new boolean[1001];
for (int i = 2; i <= 1000; i++)
if (!pr[i]) {
int l = 2 * i;
while (l <= 1000) {
pr[l] = true;
l += i;
}
}
Set<Integer> set = new HashSet<Integer>();
for (int i = 2; i < 1000; i++) {
for (int j = i + 1; j <= 1000; j++) {
if (!pr[j]) {
set.add(j + i + 1);
i = j - 1;
break;
}
}
}
int n = nextInt();
int k = nextInt();
int res = 0;
for (int i = 2; i <= n; i++) {
if (set.contains(i) && !pr[i])
res++;
}
if (res >= k)
out.println("YES");
else
out.println("NO");
in.close();
out.close();
}
void chk(boolean b) {
if (b)
return;
System.out.println(new Error().getStackTrace()[1]);
exit(999);
}
void deb(String fmt, Object... args) {
System.out.printf(Locale.US, fmt + "%n", args);
}
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
@SuppressWarnings("unchecked")
public class P35C {
final static int SHIFT = 11;
final static int MASK = (1 << SHIFT) - 1;
final static int [] DX = {-1, 1, 0, 0};
final static int [] DY = { 0, 0, -1, 1};
public void run() throws Exception {
int m = nextInt();
int n = nextInt();
boolean [][] burned = new boolean [n][m];
List<Integer> burn = new ArrayList();
for (int k = nextInt(); k > 0; k--) {
int x = nextInt() - 1;
int y = nextInt() - 1;
burned[y][x] = true;
burn.add((x << SHIFT) | y);
}
int lastXY = 0;
List<Integer> newBurn = null;
do {
lastXY = burn.get(0);
newBurn = new ArrayList();
for (int xy : burn) {
int x = xy >> SHIFT;
int y = xy & MASK;
for (int i = 0; i < 4; i++) {
int nx = x + DX[i];
int ny = y + DY[i];
if ((ny >= 0) && (ny < n) && (nx >= 0) && (nx < m) && (!burned[ny][nx])) {
burned[ny][nx] = true;
newBurn.add((nx << SHIFT) | ny);
}
}
}
burn = newBurn;
} while (newBurn.size() > 0);
println(((lastXY >> SHIFT) + 1) + " " + ((lastXY & MASK) + 1));
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream("output.txt")));
new P35C().run();
br.close();
pw.close();
System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]");
}
static long startTime = System.currentTimeMillis();
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { print("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
public class D {
int[][] fast(int n, int m){
int[][] ans = new int[2][n * m];
int c = 0;
for (int left = 1, right = m; left < right; left++, right--) {
for (int l = 1, r = n; l <= n && r >= 1; l++, r--) {
ans[0][c] = l;
ans[1][c++] = left;
ans[0][c] = r;
ans[1][c++] = right;
}
}
if (m % 2 == 1) {
int x = m/2 + 1;
for(int l = 1, r = n;l < r;l++, r--){
ans[0][c] = l;
ans[1][c++] = x;
ans[0][c] = r;
ans[1][c++] = x;
if(n % 2 == 1 && l + 2 == r){
ans[0][c] = l+1;
ans[1][c++] = x;
}
}
}
if(n == 1 && m % 2 == 1){
ans[0][c] = 1;
ans[1][c] = m/2 + 1;
}
return ans;
}
void stress(){
for(int i = 3;i<=5;i++){
for(int j = 2;j<=5;j++){
int[][] ans = new int[2][];
try{
ans = fast(i, j);
}catch(Exception e){
out.println("ошибка");
out.print(i + " " + j);
return;
}
boolean[][] check = new boolean[i][j];
for(int c = 0;c<ans[0].length;c++){
int x = ans[0][c] - 1;
int y = ans[1][c] - 1;
check[x][y] = true;
}
for(int c = 0;c<i;c++){
for(int q = 0;q<j;q++){
if(!check[c][q]){
out.println(i + " " + j);
out.println("точки");
for(int w = 0;w<ans[0].length;w++){
out.println(ans[0][w] + " " + ans[1][w]);
}
return;
}
}
}
HashSet<String> set = new HashSet<>();
for(int c = 1;c<ans[0].length;c++){
int x = ans[0][c] - ans[0][c- 1];
int y = ans[1][c] - ans[1][c - 1];
set.add(x + " " + y);
}
if(set.size() < i * j - 1){
out.println(i + " " + j);
out.println("вектора");
for(int w = 0;w<ans[0].length;w++){
out.println(ans[0][w] + " " + ans[1][w]);
}
return;
}
}
}
}
void normal(){
int n =readInt();
int m = readInt();
int[][] ans = fast(n, m);
for(int i = 0;i<ans[0].length;i++){
out.println(ans[0][i] + " " + ans[1][i]);
}
}
boolean stress = false;
void solve(){
if(stress) stress();
else normal();
}
public static void main(String[] args) {
new D().run();
}
void run(){
init();
solve();
out.close();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init(){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
String readLine(){
try{
return in.readLine();
}catch(Exception ex){
throw new RuntimeException(ex);
}
}
String readString(){
while(!tok.hasMoreTokens()){
String nextLine = readLine();
if(nextLine == null) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt(){
return Integer.parseInt(readString());
}
long readLong(){
return Long.parseLong(readString());
}
double readDouble(){
return Double.parseDouble(readString());
}
}
|
quadratic
|
1179_B. Tolik and His Uncle
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long k = in.nextLong();
long t = 1;
long l = 1;
if(k <= 9) {
System.out.print(k);
System.exit(0);
}
long x = 9;
while(true) {
++l;
t *= 10;
x += 9 * l * t;
if(x >= k) {
break;
}
}
if(x == k) {
System.out.print(9);
System.exit(0);
}
x -= 9 * l * t;
long a = (k - x) / l;
if((k - x) % l == 0) {
x = t + a - 1;
System.out.print(x % 10);
} else {
k -= (x + a * l);
x = t + a;
String s = Long.toString(x);
System.out.print(s.charAt((int)k - 1));
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Map<Integer, List<Range>> rgs = new HashMap<Integer, List<Range>>();
for (int i = 0; i < n; i++) {
int s = 0;
for (int j = i; j < n; j++) {
s += a[j];
if (rgs.get(s) == null) {
rgs.put(s, new ArrayList<Range>());
}
rgs.get(s).add(new Range(i, j));
}
}
Iterator it = rgs.entrySet().iterator();
List<Range> ans = new ArrayList<Range>();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
int sum = (int) pair.getKey();
Object[] intermediate = ((List<Object[]>) pair.getValue()).toArray();
Range[] ranges = new Range[intermediate.length];
for (int i = 0; i < intermediate.length; i++) {
ranges[i] = (Range) intermediate[i];
}
Arrays.sort(ranges);
List<Range> cand = new ArrayList<Range>();
for (Range r : ranges) {
if (cand.size() == 0) {
cand.add(r);
continue;
}
if (cand.get(cand.size() - 1).j < r.i) {
cand.add(r);
} else {
if (cand.get(cand.size() - 1).j > r.j) {
cand.remove(cand.size() - 1);
cand.add(r);
}
}
}
if (cand.size() > ans.size()) {
ans = cand;
}
}
out.println(ans.size());
for (Range r : ans) {
out.println((r.i + 1) + " " + (r.j + 1));
}
}
public class Range implements Comparable {
public int i;
public int j;
public Range(int i, int j) {
this.i = i;
this.j = j;
}
public int compareTo(Object o) {
Range t = (Range) o;
if (this.i == t.i) {
if (this.j < t.j) return 1;
else return 0;
}
if (this.i < t.i) return 1;
return 0;
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
//package com.krakn.CF.B1159;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int min = 1000000000, temp;
for (int i = 0; i < n; i++) {
temp = arr[i] / Math.max(i, n - 1 - i);
if (temp < min)
min = temp;
// System.out.println(i + " " + temp);
}
System.out.println(min);
}
}
|
linear
|
1159_B. Expansion coefficient of the array
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.List;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* 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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, FastReader in, PrintWriter out) {
Debug debug = new Debug();
int n = in.nextInt();
int K = in.nextInt();
List<Integer>[] g = GraphUtils.nextU(in, n, n - 1, true);
int[] center = GraphUtils.getCenter(g);
if (center.length == 2) {
out.println("No");
return;
}
int[][] pars = GraphUtils.parents3(g, center[0]);
int[] par = pars[0], ord = pars[1], depth = pars[2];
int[] deg = new int[n];
for (int i = 0; i < n; ++i) deg[i] = g[i].size();
if (deg[center[0]] < 3) {
out.println("No");
return;
}
// all leaves depth = K
for (int i = 0; i < n; ++i) {
if (deg[i] == 1) {
if (depth[i] != K) {
out.println("No");
return;
}
} else if (i != center[0]) {
if (deg[i] < 4) {
out.println("No");
return;
}
}
}
out.println("Yes");
}
}
static class GraphUtils {
public static List<Integer>[] nextU(FastReader in, int n, int m, boolean oneIndexed) {
int diff = oneIndexed ? 1 : 0;
List<Integer>[] g = new List[n];
for (int i = 0; i < n; ++i) g[i] = new ArrayList<>();
for (int i = 0; i < m; ++i) {
int u = in.nextInt() - diff;
int v = in.nextInt() - diff;
g[u].add(v);
g[v].add(u);
}
return g;
}
public static int[][] parents3(List<Integer>[] g, int root) {
int n = g.length;
int[] par = new int[n];
ArrayUtils.fill(par, -1);
int[] depth = new int[n];
depth[0] = 0;
int[] q = new int[n];
q[0] = root;
for (int p = 0, r = 1; p < r; p++) {
int cur = q[p];
for (int nex : g[cur]) {
if (par[cur] != nex) {
q[r++] = nex;
par[nex] = cur;
depth[nex] = depth[cur] + 1;
}
}
}
return new int[][]{par, q, depth};
}
public static int[] getCenter(List<Integer>[] g) {
int n = g.length;
int[] q = new int[n];
int[] deg = new int[n];
int p = 0;
for (int i = 0; i < n; i++) {
deg[i] = g[i].size();
if (g[i].size() <= 1) { // < for n=1
q[p++] = i;
}
}
int bound = p == n ? 0 : p;
for (int z = 0; z < p; z++) {
if (bound == z && p < n) bound = p;
int cur = q[z];
deg[cur]--;
for (int e : g[cur]) {
if (--deg[e] == 1) q[p++] = e;
}
}
assert p == n;
assert bound >= n - 2 && bound < n;
if (bound == n - 2) {
return new int[]{q[n - 2], q[n - 1]};
} else {
return new int[]{q[n - 1]};
}
}
}
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;
}
}
static class ArrayUtils {
public static void fill(int[] array, int value) {
Arrays.fill(array, value);
}
}
static class Debug {
PrintWriter out;
boolean oj;
boolean system;
long timeBegin;
Runtime runtime;
public Debug(PrintWriter out) {
oj = System.getProperty("ONLINE_JUDGE") != null;
this.out = out;
this.timeBegin = System.currentTimeMillis();
this.runtime = Runtime.getRuntime();
}
public Debug() {
system = true;
oj = System.getProperty("ONLINE_JUDGE") != null;
OutputStream outputStream = System.out;
this.out = new PrintWriter(outputStream);
this.timeBegin = System.currentTimeMillis();
this.runtime = Runtime.getRuntime();
}
}
}
|
linear
|
1067_B. Multihedgehog
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long n = scanner.nextLong();
long s = scanner.nextLong();
long myLong = s;
long count =0;
while(true){
if(myLong>n){
break;
}
char[] num = (""+myLong).toCharArray();
int sum = 0;
for (int j = 0; j < num.length; j++)
sum += num[j] - '0';
if(myLong- sum>=s){
//count++;
break;
}
myLong++;
}
System.out.println(Math.max(n-myLong+1,0));
scanner.close();
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.