src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
public class B1177 {
public static void main(String[] args) throws Exception {
// BufferedReader br = new BufferedReader(new FileReader("F:/books/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Long n = Long.parseLong(br.readLine());
long[] p = new long[15];
int i;
p[0]=1;
for(i=1;i<15;p[i]=p[i-1]*10,i++);
for(i=1;i*p[i-1]*9L<n;n-=i*p[i-1]*9L,i++);
n--;
int v = (int) (n%i);
n/=i;
n+=p[i-1];
String s = n.toString();
System.out.println(s.charAt(v));
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
/**
* Created by IntelliJ IDEA.
* User: SONY
* Date: 27.05.12
* Time: 18:25
* To change this template use File | Settings | File Templates.
*/
import java.io.*;
import java.util.*;
public class TaskA extends Thread {
public TaskA(String inputFileName, String outputFileName) {
try {
if (inputFileName != null) {
this.input = new BufferedReader(new FileReader(inputFileName));
} else {
this.input = new BufferedReader(new InputStreamReader(System.in));
}
if (outputFileName != null) {
this.output = new PrintWriter(outputFileName);
} else {
this.output = new PrintWriter(System.out);
}
this.setPriority(Thread.MAX_PRIORITY);
} catch (Throwable e) {
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(666);
}
}
private void solve() throws Throwable {
long n = nextLong();
output.println("0 0 " + n);
}
public void run() {
try {
solve();
} catch (Throwable e) {
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(666);
} finally {
output.close();
}
}
public static void main(String... args) {
new TaskA(null, null).start();
}
private int nextInt() throws IOException {
return Integer.parseInt(next());
}
private double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private long nextLong() throws IOException {
return Long.parseLong(next());
}
private String next() throws IOException {
while (tokens == null || !tokens.hasMoreTokens()) {
tokens = new StringTokenizer(input.readLine());
}
return tokens.nextToken();
}
private StringTokenizer tokens;
private BufferedReader input;
private PrintWriter output;
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class a {
static long mod = 1000000007;
static boolean[][] blacks;
public static void main(String[] args) throws IOException
{
input.init(System.in);
PrintWriter out = new PrintWriter(new PrintStream(System.out));
//Scanner input = new Scanner(new File("input.txt"));
//PrintWriter out = new PrintWriter(new File("output.txt"));
int n = input.nextInt(), t = input.nextInt();
int res = 2;
Cottage[] data = new Cottage[n];
int[] xs = new int[n], as = new int[n];
for(int i = 0; i<n; i++)
{
data[i] = new Cottage(input.nextInt(), input.nextInt());
}
Arrays.sort(data);
for(int i = 0; i<n; i++)
{
xs[i] = data[i].x;
as[i] = data[i].a;
}
for(int i = 0; i<n-1; i++)
{
if(2*(xs[i+1]-xs[i]) == 2*t+as[i]+as[i+1]) res++;
else if(2*(xs[i+1]-xs[i]) > 2*t+as[i]+as[i+1]) res+=2;
}
out.println(res);
out.close();
}
static class Cottage implements Comparable<Cottage>
{
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
int x, a;
public Cottage(int xx, int aa)
{
x = xx; a = aa;
}
@Override
public int compareTo(Cottage o) {
// TODO(mkirsche): Auto-generated method stub
return this.x - o.x;
}
}
static long pow(long a, long p)
{
if(p==0) return 1;
if((p&1) == 0)
{
long sqrt = pow(a, p/2);
return (sqrt*sqrt)%mod;
}
else
return (a*pow(a,p-1))%mod;
}
static class input {
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 long nextLong() throws IOException {
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static String nextLine() throws IOException {
return reader.readLine();
}
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author \/
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
TaskC.pair[] songs = new TaskC.pair[n];
long sum = 0;
for (int i = 0; i < n; i++) {
songs[i] = new TaskC.pair(in.nextInt(), in.nextInt());
sum += songs[i].a;
}
Arrays.sort(songs);
int res = 0;
int idx = n - 1;
while (sum > m) {
if (idx < 0) {
break;
}
sum -= (songs[idx].a - songs[idx].b);
res++;
idx--;
}
if (sum > m) {
out.println(-1);
} else {
out.println(res);
}
}
static class pair implements Comparable<TaskC.pair> {
int a;
int b;
pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(TaskC.pair p) {
return (this.a - this.b) - (p.a - p.b);
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
nlogn
|
1015_C. Songs Compression
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class DD {
public static void main(String[] args)throws Throwable {
MyScanner sc=new MyScanner();
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
int [] a=new int [n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
int c=0;
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(a[i]>a[j])
c^=1;
int m=sc.nextInt();
while(m-->0){
int l=sc.nextInt()-1;
int r=sc.nextInt()-1;
int d=r-l+1;
d=d*(d-1)/2;
c^=(d%2);
pw.println(c==0? "even" : "odd");
}
pw.flush();
pw.close();
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {e.printStackTrace();}}
return st.nextToken();}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
String nextLine(){String str = "";
try {str = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return str;}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* Created by shirsh.bansal on 07/08/16.
*/
public class Main {
public static void main(String[] args) throws IOException {
FastScanner scanner = new FastScanner();
int n = scanner.nextInt();
int m = scanner.nextInt();
boolean graph[][] = new boolean[n][n];
for (int i = 0; i < m; i++) {
int a = scanner.nextInt();
int b = scanner.nextInt();
graph[a-1][b-1] = true;
graph[b-1][a-1] = true;
}
if(n <= 2) {
System.out.println(0);
return;
}
long dp[][] = new long[1<<n][n];
for (int i = 0; i < (1<<n); i++) {
Arrays.fill(dp[i], -1);
}
for (int i = 1; i < (1<<n); i++) {
for (int j = 0; j < n; j++) {
f(i, j, dp, graph, n);
}
}
long sum = 0;
// for (int i = 7; i < (1 << n); i++) {
// if(Integer.bitCount(i) < 3) continue;
// for (int j = 0; j < n; j++) {
// int startNode = Integer.numberOfTrailingZeros(Integer.highestOneBit(i));
// int endNode = j;
//
// if(graph[startNode][endNode] && dp[i][j] != -1) {
//// System.out.println(i + " " + startNode + " " + endNode + " " + dp[i][j]);
// sum += dp[i][j];
// }
// }
// }
for (int i = 0; i < n; i++) {
for (int j = 0; j < (1 << n); j++) {
if(Integer.bitCount(j) >= 3 && graph[Integer.numberOfTrailingZeros(j)][i]) {
sum += dp[j][i];
}
}
}
System.out.println(sum/2);
}
private static long f(int mask, int i, long[][] dp, boolean[][] graph, int n) {
if(dp[mask][i] != -1) return dp[mask][i];
if(Integer.bitCount(mask) == 1 && (mask&(1<<i)) != 0) {
dp[mask][i] = 1;
} else if(Integer.bitCount(mask) > 1 && (mask&(1<<i)) != 0 && i != Integer.numberOfTrailingZeros(mask)) {
dp[mask][i] = 0;
for (int j = 0; j < n; j++) {
if(graph[i][j]) dp[mask][i] = dp[mask][i] + f(mask^(1<<i), j, dp, graph, n);
}
} else {
dp[mask][i] = 0;
}
// int tmpMask = mask ^ (1<<i);
// for (int j = 0; j <= firstNode; j++) {
// if(((1<<j)&tmpMask) != 0 && graph[i][j]) {
// dp[mask][i] += f(tmpMask, j, dp, graph, n, firstNode);
// }
// }
//
return dp[mask][i];
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() {
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());
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a, b, min, max, result = 0, temp;
while(n-->0){
a = sc.nextInt();
b = sc.nextInt();
max = Math.max(a, b);
min = Math.min(a, b);
result = 0;
while(true){
result += max/min;
if(max%min == 0){
System.out.println(result);
break;
}
/* take the min and the remainder as the previous min. */
temp = max;
max = min;
min = temp%min;
}
}
sc.close();
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.lang.Math.*;
public class Main{
static long s;
static boolean check(long n){
int sum = 0;
long storen=n;
while(n>0){
int k = (int)(n%10);
n /=10;
sum+=k;
}
return storen-(long)sum >= s;
}
public static void main(String args[]){
PrintWriter pw=new PrintWriter(System.out);
InputReader ip=new InputReader(System.in);
long n;
n=ip.nextLong();
s=ip.nextLong();
if(s>n){
pw.println("0");
}
else{
long l=0,r=n;
boolean possible=false;
long mid=0;
int it=100;
while(it-->0){
mid = (l+r)/2;
if(check(mid)){
r=mid;
possible = true;
}
else{
l=mid+1;
}
// pw.println(mid);
// pw.println(l+" "+r);
}
if(possible){
pw.println(n-l+1);
}
else{
pw.println("0");
}
}
pw.close();
}
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 String nextLine() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class C {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
// Scanner scan = new Scanner(System.in);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(bf.readLine());
int counter = 0;
for(int i=0; i<2*n/3; i++) System.out.println("0 " + i);
for(int i=0; i<n-2*n/3; i++) System.out.println("3 " + (2*i+1));
}
}
|
linear
|
1067_C. Knights
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class RGBSubstring {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int Q = scanner.nextInt();
while(Q-->0) {
int N = scanner.nextInt();
int K = scanner.nextInt();
String s1 = "RGB";
String s2 = "GBR";
String s3 = "BRG";
char[] arr = scanner.next().toCharArray();
int[] cnts = new int[3];
for(int i = 0; i < K; i++) {
int ind = i % 3;
if (arr[i] != s1.charAt(ind)) cnts[0]++;
if (arr[i] != s2.charAt(ind)) cnts[1]++;
if (arr[i] != s3.charAt(ind)) cnts[2]++;
}
int ans = Math.min(Math.min(cnts[0], cnts[1]), cnts[2]);
for(int i = K; i < N; i++) {
int ind = (K-1)%3;
int[] nextCnts = new int[3];
nextCnts[1] = cnts[0];
nextCnts[2] = cnts[1];
nextCnts[0] = cnts[2];
if ('R' != arr[i-K]) nextCnts[1]--;
if ('G' != arr[i-K]) nextCnts[2]--;
if ('B' != arr[i-K]) nextCnts[0]--;
if (arr[i] != s1.charAt(ind)) nextCnts[0]++;
if (arr[i] != s2.charAt(ind)) nextCnts[1]++;
if (arr[i] != s3.charAt(ind)) nextCnts[2]++;
cnts = nextCnts;
for(int j = 0; j < 3; j++) ans = Math.min(ans, cnts[j]);
}
out.println(ans);
}
out.flush();
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
}
}
|
quadratic
|
1196_D1. RGB Substring (easy version)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Locale;
import java.util.StringTokenizer;
public class A {
private void solve() throws IOException {
int n = nextInt();
Integer[] a = new Integer[n];
Integer[] b = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = b[i] = nextInt();
}
Arrays.sort(a);
int k = 0;
for (int i = 0; i < n; i++) {
if (!a[i].equals(b[i])) {
k++;
}
}
if (k <= 2) {
println("YES");
} else {
println("NO");
}
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
private int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
private double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private void print(Object o) {
writer.print(o);
}
private void println(Object o) {
writer.println(o);
}
private void printf(String format, Object... o) {
writer.printf(format, o);
}
public static void main(String[] args) {
long time = System.currentTimeMillis();
Locale.setDefault(Locale.US);
new A().run();
System.err.printf("%.3f\n", 1e-3 * (System.currentTimeMillis() - time));
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
private void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(13);
}
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class A{
static int N, M, K;
static String s;
static StringTokenizer st;
static int[] d;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int[][] d = new int[5][3];
int[][] d2 = new int[5][3];
int N = Integer.parseInt(br.readLine());
for (int i = 0; i < N; i++) {
String r = br.readLine();
int len = r.length();
int fin = 0;
if(r.charAt(r.length()-1) == 'S')
fin = 0;
if(r.charAt(r.length()-1) == 'M')
fin = 1;
if(r.charAt(r.length()-1) == 'L')
fin = 2;
d[len][fin]++;
}
for (int i = 0; i < N; i++) {
String r = br.readLine();
int len = r.length();
int fin = 0;
if(r.charAt(r.length()-1) == 'S')
fin = 0;
if(r.charAt(r.length()-1) == 'M')
fin = 1;
if(r.charAt(r.length()-1) == 'L')
fin = 2;
d2[len][fin]++;
}
int ans = 0;
for (int i = 0; i < d.length; i++) {
int sum = 0;
int sum2 = 0;
for (int j = 0; j < d[0].length; j++) {
sum += d[i][j];
sum2 += d2[i][j];
ans += Math.max(0, d2[i][j] - d[i][j]);
}
}
System.out.println(ans);
out.close();
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class Twins {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] val = new int[n];
for (int i=0; i<n; i++)
val[i] = in.nextInt();
Arrays.sort(val);
int sum = 0, count = 0;
for (int i=n-1; i>=0; i--) {
count++;
sum += val[i];
int his = 0;
for (int j=0; j<i; j++) his += val[j];
if (his < sum) break;
}
System.out.println(count);
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
FastReader in;
PrintWriter out;
int n;
public void solve(int testNumber, FastReader in, PrintWriter out) {
this.in = in;
this.out = out;
n = in.nextInt();
if (n % 4 != 0) {
out.println("! -1");
return;
}
int low = 0;
int high = n >> 1;
if (BValue(low) == 0) {
out.println("! " + (low + 1));
return;
}
int fSign = Integer.signum(BValue(low));
while (high - low > 1) {
int mid = (high + low) >> 1;
int mSign = Integer.signum(BValue(mid));
if (mSign == 0) {
out.println("! " + (mid + 1));
return;
}
if (mSign == -fSign) {
high = mid;
} else {
low = mid;
}
}
out.println("! -1");
}
public int BValue(int index) {
out.println("? " + (index + 1));
out.flush();
int f = in.nextInt();
out.println("? " + (index + 1 + (n >> 1)));
out.flush();
int s = in.nextInt();
return f - s;
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main
{
static final long mod=(int)1e9+7;
public static void main(String[] args) throws Exception
{
FastReader in=new FastReader();
PrintWriter pw=new PrintWriter(System.out);
int n=in.nextInt();
int[] arr=new int[n+1];
for(int i=1;i<=n;i++)
arr[i]=in.nextInt();
Map<Integer,TreeMap<Integer,Integer>> map=new HashMap();
for(int i=1;i<=n;i++)
{
int sum=0;
for(int j=i;j<=n;j++)
{
sum+=arr[j];
if(map.containsKey(sum))
{
TreeMap<Integer,Integer> t=map.get(sum);
// System.out.println(t+" "+sum);
Map.Entry<Integer,Integer> e=t.lastEntry();
if(e.getKey()>j)
{
t.remove(e.getKey());
t.put(j,i);
map.put(sum,t);
}
else if(e.getKey()<i)
{
t.put(j,i);
map.put(sum,t);
}
}
else
{
TreeMap<Integer,Integer> t=new TreeMap();
t.put(j,i);
map.put(sum,t);
}
}
}
int ans=0,size=0;
for(Map.Entry<Integer,TreeMap<Integer,Integer>> e:map.entrySet())
{
if(e.getValue().size()>size)
{
ans=e.getKey();
size=e.getValue().size();
}
}
pw.println(size);
for(Map.Entry e:map.get(ans).entrySet())
pw.println(e.getValue()+" "+e.getKey());
pw.flush();
}
}
class pair
{
int f,s;
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException
{
if(st==null || !st.hasMoreElements())
{
st=new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class D implements Runnable{
public static void main (String[] args) {new Thread(null, new D(), "_cf", 1 << 28).start();}
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("Go!");
int n = fs.nextInt();
Pair[] a = new Pair[n], b = new Pair[n];
for(int i = 0; i < n; i++) {
a[i] = new Pair(fs.nextInt(), i+1);
b[i] = new Pair(a[i].val, a[i].id);
}
Arrays.sort(a);
Fenwick_Tree ft = new Fenwick_Tree(n), ftFreq = new Fenwick_Tree(n);
BigInteger res = BigInteger.ZERO;
int[] update = new int[n];
int sum = 0;
for(int i = 0; i < n; i++) {
// System.out.println(sum + " " + a[i].val);
if(i + 1 == n || (i + 1 < n && a[i+1].val != a[i].val)) {
update[i] = sum+1;
sum = 0;
}
else {
sum++;
}
}
// System.out.println(Arrays.toString(update));
for(int i = 0; i < n; i++) {
int pos = a[i].id;
long val = a[i].val;
long right = ft.sum(n) - ft.sum(pos);
long freq = ftFreq.sum(n) - ftFreq.sum(pos);
// System.out.println(a[i].val + " " + a[i].id + " " + right + " " + freq);
res = add(res, right - (val * freq));
// res += right - (val * freq);
long left = ft.sum(pos);
freq = ftFreq.sum(pos);
res = add(res, (val * freq) - left);
// res += (val * freq) - left;
// System.out.println(a[i].val + " " + a[i].id + " " + left + " " + freq);
// System.out.println();
if(update[i] > 0) {
ft.update(pos, val);
ftFreq.update(pos, 1);
int ptr = i-1;
while(ptr >= 0 && update[ptr] == 0) {
ft.update(a[ptr].id, val);
ftFreq.update(a[ptr].id, 1);
ptr--;
}
}
}
HashMap<Integer, Integer> freq = new HashMap<>();
for(int i = n-1; i >= 0; i--) {
if(!freq.containsKey(b[i].val+1)) {
if(!freq.containsKey(b[i].val)) freq.put(b[i].val, 0);
freq.put(b[i].val, freq.get(b[i].val)+1);
continue;
}
long fr = freq.get(b[i].val+1);
// System.out.println(i + " " + b[i].val + " " + fr);
res = sub(res, fr * (b[i].val+1) - (fr * (b[i].val)));
// res -= (fr*(b[i].val+1)) - (fr*b[i].val);
if(!freq.containsKey(b[i].val)) freq.put(b[i].val, 0);
freq.put(b[i].val, freq.get(b[i].val)+1);
}
// System.out.println(res);
freq.clear();
for(int i = 0; i < n; i++) {
if(!freq.containsKey(b[i].val+1)) {
if(!freq.containsKey(b[i].val)) freq.put(b[i].val, 0);
freq.put(b[i].val, freq.get(b[i].val)+1);
continue;
}
long fr = freq.get(b[i].val+1);
// System.out.println(i + " " + b[i].val + " " + fr);
res = add(res, (fr*(b[i].val+1)) - (fr*b[i].val));
// res += (fr*(b[i].val+1)) - (fr*b[i].val);
if(!freq.containsKey(b[i].val)) freq.put(b[i].val, 0);
freq.put(b[i].val, freq.get(b[i].val)+1);
}
out.println(res);
out.close();
}
BigInteger add (BigInteger a, long b) {
BigInteger res = a.add(BigInteger.valueOf(b));
return res;
}
BigInteger sub (BigInteger a, long b) {
BigInteger res = a.subtract(BigInteger.valueOf(b));
return res;
}
class Pair implements Comparable<Pair> {
int val, id;
Pair (int a, int b) {
val = a;
id = b;
}
public int compareTo (Pair o) {
if(val == o.val) return Integer.compare(id, o.id);
return Integer.compare(o.val, val);
}
}
class Fenwick_Tree {
long[] bit;
int n;
public Fenwick_Tree(int a) {
n = a + 1;
bit = new long[n];
}
//Remember that when querying a sum to query the 1-based index of the value.
void update (int index, long val) {
while(index < n) {
bit[index] += val;
index += (index & (-index));
}
}
long sum (int index) {
long sum = 0;
while(index > 0) {
sum += bit[index];
index -= (index & (-index));
}
return sum;
}
}
void sort (int[] a) {
int n = a.length;
for(int i = 0; i < 1000; i++) {
Random r = new Random();
int x = r.nextInt(n), y = r.nextInt(n);
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
Arrays.sort(a);
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new FileReader("cases.in"));
st = new StringTokenizer("");
} 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 = "";
try {line = br.readLine();}
catch (Exception e) {e.printStackTrace();}
return line;
}
public Integer[] nextIntegerArray(int n) {
Integer[] a = new Integer[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public char[] nextCharArray() {return nextLine().toCharArray();}
}
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class bhaa {
InputStream is;
PrintWriter o;
/////////////////// CODED++ BY++ ++ ++ ++ BHAVYA++ ARORA++ ++ ++ ++ FROM++ JAYPEE++ INSTITUTE++ OF++ INFORMATION++ TECHNOLOGY++ ////////////////
///////////////////////// Make it work, make it right, make it fast. Make it work, make it right, make it fast. Make it work, make it right, make it fast. Make it work, make it right, make it fast. /////////////////
boolean chpr(int n)
{
if(n==1)
{
return true;
}if(n==2)
{
return true;
}
if(n==3)
{
return true;
}
if(n%2==0)
{
return false;
}
if(n%3==0)
{
return false;
}
int w=2;
int i=5;
while(i*i<=n)
{
if(n%i==0)
{
return false;
}
i+=w;
w=6-w;
}
return true;
}
void solve() {
int n=ni();
int k=ni();
int rr=2*n;
int gr=5*n;
int br=8*n;
o.println((long)(Math.ceil(rr*1.0/k)+Math.ceil(gr*1.0/k)+Math.ceil(br*1.0/k)));
}
//---------- I/O Template ----------
public static void main(String[] args) { new bhaa().run(); }
void run() {
is = System.in;
o = new PrintWriter(System.out);
solve();
o.flush();
}
byte input[] = new byte[1024];
int len = 0, ptr = 0;
int readByte() {
if(ptr >= len) { ptr = 0;
try { len = is.read(input); }
catch(IOException e) { throw new InputMismatchException(); }
if(len <= 0) { return -1; }
} return input[ptr++];
}
boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); }
int skip() {
int b = readByte();
while(b != -1 && isSpaceChar(b)) { b = readByte(); }
return b;
}
char nc() { return (char)skip(); }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
String nLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
int ni() {
int n = 0, b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
if(b == -1) { return -1; } //no input
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
long nl() {
long n = 0L; int b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
double nd() { return Double.parseDouble(ns()); }
float nf() { return Float.parseFloat(ns()); }
int[] nia(int n) {
int a[] = new int[n];
for(int i = 0; i < n; i++) { a[i] = ni(); }
return a;
}
long[] nla(int n) {
long a[] = new long[n];
for(int i = 0; i < n; i++) { a[i] = nl(); }
return a;
}
int [][] nim(int n)
{
int mat[][]=new int[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
mat[i][j]=ni();
}
}
return mat;
}
long [][] nlm(int n)
{
long mat[][]=new long[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
mat[i][j]=nl();
}
}
return mat;
}
char[] ns(int n) {
char c[] = new char[n];
int i, b = skip();
for(i = 0; i < n; i++) {
if(isSpaceChar(b)) { break; }
c[i] = (char)b; b = readByte();
} return i == n ? c : Arrays.copyOf(c,i);
}
void piarr(int arr[])
{
for(int i=0;i<arr.length;i++)
{
o.print(arr[i]+" ");
}
o.println();
}
void plarr(long arr[])
{
for(int i=0;i<arr.length;i++)
{
o.print(arr[i]+" ");
}
o.println();
}
void pimat(int mat[][])
{
for(int i=0;i<mat.length;i++)
{
for(int j=0;j<mat[0].length;j++)
{
o.print(mat[i][j]);
}
o.println();
}
}
void plmat(long mat[][])
{
for(int i=0;i<mat.length;i++)
{
for(int j=0;j<mat[0].length;j++)
{
o.print(mat[i][j]);
}
o.println();
}
}
//////////////////////////////////// template finished //////////////////////////////////////
}
|
constant
|
1080_A. Petya and Origami
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class E1 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//optimizaciones que parece que solo son necesarias para java
ArrayList<Integer>[] reps = new ArrayList[13]; //representantes de las clases
int[][] index = new int[13][]; // mapea para cada representante un indice de 0 a |clases|-1
int[][] eqcl = new int[13][]; //mapea para cada mask, su clase
ArrayList<Integer>[][] nexts = new ArrayList[13][]; //para cada clase, los masks compatibles
for(int n = 1; n <= 12; n++) {
eqcl[n] = new int[(1 << n)];
reps[n] = new ArrayList<Integer>();
index[n] = new int[(1 << n)];
int ind = 0;
for(int mask = 0; mask < (1 << n); mask++) {
boolean add = true;
for(int k = 0; k < n; k++) {
if(rot(mask, k, n) < mask) add = false;
}
if(add) {
reps[n].add(mask);
index[n][mask] = ind; ind++;
}
}
nexts[n] = new ArrayList[reps[n].size()];
for(int i = 0; i < reps[n].size(); i++) {
int mask = reps[n].get(i);
for(int k = 0; k < n; k++) {
eqcl[n][rot(mask, k, n)] = i;
}
nexts[n][i] = new ArrayList<>();
for(int y = 0; y < (1 << n); y++) {
if((mask & y) == 0) {
nexts[n][i].add(y);
}
}
}
}
int T = Integer.parseInt(br.readLine());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
for(int test = 0; test < T; test++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[][] arrt = new int[m][n];
for(int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for(int j = 0; j < m; j++) {
arrt[j][i] = Integer.parseInt(st.nextToken());
}
}
Column[] cols = new Column[m];
for(int j = 0; j < m; j++) {
cols[j] = new Column(arrt[j]);
}
Arrays.sort(cols, Collections.reverseOrder());
m = Integer.min(n, m);
int[][] arr = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
arr[i][j] = cols[j].arr[i];
}
}
int[][] max = new int[m][reps[n].size()];
for(int c = 0; c < m; c++) {
for(int mask = 0; mask < (1 << n); mask++) {
int curr = 0;
for(int i = 0; i < n; i++) {
if((mask & (1 << i)) > 0) curr += arr[i][c];
}
int cl = eqcl[n][mask];
max[c][cl] = Integer.max(max[c][cl], curr);
}
}
int[][] dp = new int[m+1][reps[n].size()];
for(int c = 0; c < m; c++) {
for(int i = 0; i < reps[n].size(); i++) {
int mask = reps[n].get(i);
for(int next: nexts[n][i]) { //opt
int cl = eqcl[n][next];
int dl = eqcl[n][mask | next];
if(dp[c][i] + max[c][cl] > dp[c+1][dl]) { // el dp
dp[c+1][dl] = dp[c][i] + max[c][cl];
}
}
}
}
bw.write(dp[m][reps[n].size() - 1]+"\n");
}
bw.flush();
}
static int rot(int x, int k, int n) {
int a = x << k;
int b = x >> (n - k);
return (a + b) & ((1 << n) - 1);
}
static class Column implements Comparable<Column>{
int[] arr;
int max;
public Column(int[] arr) {
this.arr = arr;
max = 0;
for(int k: arr) {
max = Integer.max(max, k);
}
}
@Override
public int compareTo(Column col) {
return max - col.max;
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
EPhoenixAndComputers solver = new EPhoenixAndComputers();
solver.solve(1, in, out);
out.close();
}
static class EPhoenixAndComputers {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt();
ModInt mod = new ModInt(m);
int[] factorial = new int[n + 1];
int[][] binomial = new int[n + 1][n + 1];
int[] two = new int[n + 1];
for (int i = 0; i <= n; i++) {
binomial[i][0] = 1;
for (int j = 1; j <= i; j++)
binomial[i][j] = mod.add(binomial[i - 1][j], binomial[i - 1][j - 1]);
factorial[i] = i == 0 ? 1 : mod.multiply(factorial[i - 1], i);
two[i] = i == 0 ? 1 : mod.multiply(2, two[i - 1]);
}
int[][] dp = new int[n + 1][n + 1];
dp[0][0] = 1;
int answer = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
for (int x = 1; x <= i; x++) {
dp[i][j] = mod.add(dp[i][j],
mod.multiply(binomial[i][x], mod.multiply(two[x - 1], dp[i - x][j - 1])));
}
}
}
for (int k = 0; k < n; k++) {
answer = mod.add(answer, dp[n - k][k + 1]);
}
out.println(answer);
}
}
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 println(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
writer.print('\n');
}
public void close() {
writer.close();
}
}
static class ModInt {
int modulo;
public ModInt(int m) {
modulo = m;
}
public int add(int x, int y) {
x += y;
if (x >= modulo) x -= modulo;
return x;
}
public int multiply(int x, int y) {
return (int) ((x * 1L * y) % modulo);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Scanner;
import java.util.Vector;
public class Main {
private static final int SIM = 1;
private static final int NAO = 2;
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int n = in.nextInt();
int m = in.nextInt();
int[][] a = new int[n][m];
int[][] graphVerticial = null;
int[][] graphDiagonal = null;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
}
}
graphVerticial = createGraphVertical(n, m, a);
graphDiagonal = createGraphDiagonal(n, m, a);
// print(graphVerticial);
// System.out.println("##########################");
// print(graphDiagonal);
int result = 0;
int k = 1;
int piso = 0;
int teto = 1000000000;
while(true) {
k = (int) Math.ceil((teto - piso) / 2.0) + piso;
if(isOk(n, k, graphVerticial, graphDiagonal)) {
result = Math.max(result, k);
piso = k;
}
else{
teto = k - 1;
}
//System.out.println(piso + ", " + teto);
if(teto <= piso) break;
}
System.out.println(result);
}
public static int[][] createGraphVertical(int n, int m, int[][] a){
int[][] graph = new int[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(i == j) continue;
if(i > j) {graph[i][j] = graph[j][i]; continue;}
graph[i][j] = Integer.MAX_VALUE;
for(int k = 0; k < m; k++) {
graph[i][j] = Math.min(graph[i][j], Math.abs(a[i][k] - a[j][k]));
}
}
}
return graph;
}
public static int[][] createGraphDiagonal(int n, int m, int[][] a){
int[][] graph = new int[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
graph[i][j] = Integer.MAX_VALUE;
for(int k = 0; k < m - 1; k++) {
graph[i][j] = Math.min(graph[i][j], Math.abs(a[j][k] - a[i][k + 1]));
}
}
}
return graph;
}
public static int hasPath(int n, int k, int origem, int destino, int conjunto, int[][] graph, int[][][] pd) {
//System.out.println(origem + ", " + destino);
//print(conjunto);
if(pd[origem][destino][conjunto] != 0) return pd[origem][destino][conjunto];
if(conjunto == 0) {
return origem == destino ? SIM : NAO;
}
else if(origem == destino){
return NAO;
}
for(int i = 0; i < n; i++) {
if(i == origem) continue;
int novoConjunto = conjunto - (1 << i);
boolean pertenceConjunto = ((conjunto >> i) % 2) == 1;
if(pertenceConjunto && graph[origem][i] >= k && hasPath(n, k, i, destino, novoConjunto, graph, pd) == SIM) {
pd[origem][destino][conjunto] = SIM;
return pd[origem][destino][conjunto];
}
}
pd[origem][destino][conjunto] = NAO;
return pd[origem][destino][conjunto];
}
public static boolean isOk(int n, int k, int[][] graphVertical, int[][] graphDiagonal) {
int conjunto = (int) Math.pow(2, n) - 1;
int[][][] pd = new int[n][n][(int)Math.pow(2, n)];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(i == j && n > 1) continue;
int novoConjunto = conjunto - (1 << i);
if(graphDiagonal[i][j] >= k && hasPath(n, k, i, j, novoConjunto, graphVertical, pd) == SIM) {
return true;
}
}
}
return false;
}
public static void print(int[][] graph) {
for(int i = 0; i < graph.length; i++) {
for(int j = 0; j < graph.length; j++) {
// if(graph[i][j] >= 3 ) System.out.print("1 ");
// else System.out.print("0 ");
System.out.print(graph[i][j] + " ");
}
System.out.println();
}
}
public static void print(int n) {
List<Integer> bits = new Vector<>();
while(n > 0) {
bits.add(n % 2);
n /= 2;
}
for(int i = bits.size() - 1; i >= 0; i--) {
System.out.print(bits.get(i));
}
System.out.println();
}
}
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Template {
public static void main(String[] args) throws IOException {
st = new StringTokenizer(rd.readLine());
n = Long.parseLong(st.nextToken());
m = Long.parseLong(st.nextToken());
k = Long.parseLong(st.nextToken());
long s = n - m;
s = Math.min(s, m / (k - 1));
s = Math.min(s, n / k);
long score = 0;
score = (s * (k - 1))%P;
long n1 = n - k * s, m1 = m - (k - 1) * s;
sc = 0;
// rec(n, m);
// System.out.println(sc);
if (m1 == n1) {
score = (score + full(m1)) % P;
System.out.println(score);
return;
}
score = (score + m1) % P;
System.out.println(score);
}
static long full(long N) {
long x = N / k, r = N - x * k;
long powTwo = powMod(2, x + 1) - 2 + 2*P;
powTwo %= P;
powTwo = (powTwo * k) % P;
powTwo = (powTwo + r) % P;
return powTwo;
}
static long sc = 0;
static void rec(long N, long M){
if(N==M){ sc = (sc + full(N))%P; return; }
if(N>=k && M>=k-1){
sc = (sc + (k-1))%P;
rec(N-k, M-(k-1));
return;
}
sc = (sc + M)%P;
}
static long powMod(long a, long p) {
if (p == 0)
return 1L;
long h = powMod(a, (p >> 1));
h = (h * h) % P;
return p % 2 == 0 ? h : (a * h) % P;
}
static long n, m, k;
static long P = 1000000009;
static StringTokenizer st;
static BufferedReader rd = new BufferedReader(new InputStreamReader(
System.in));
static PrintWriter pw = new PrintWriter(System.out);
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Sunits789
*/
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();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n=in.nextInt();
int arr[]=new int[n];
in.getArray(arr);
int arrc[]=new int[n];
for(int i=0;i<n;i++){
arrc[i]=arr[i];
}
Library.sort(arrc);
int c=0;
for(int i=0;i<n;i++){
if(arrc[i]!=arr[i]){
c++;
}
}
if(c>2){
out.println("NO");
}
else{
out.println("YES");
}
}
}
class InputReader{
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{
tokenizer = new StringTokenizer(reader.readLine());
}
catch (IOException e){
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
public void getArray(int arr[]){
for(int i=0;i<arr.length;i++){
arr[i]=nextInt();
}
}
}
class Library{
public static void sort(int n[]){
int len=n.length;
int l1=len/2;
int l2=len-l1;
int n1[]=new int[l1];
int n2[]=new int[l2];
for(int i=0;i<l1;i++){
n1[i]=n[i];
}
for(int i=0;i<l2;i++){
n2[i]=n[i+l1];
}
if(l1!=0){
sort(n1);
sort(n2);
}
int ind1=0;
int ind2=0;
int ind=0;
for(int i=0;i<len&&ind1<l1&&ind2<l2;i++){
if(n1[ind1]<n2[ind2]){
n[i]=n1[ind1];
ind1++;
}
else{
n[i]=n2[ind2];
ind2++;
}
ind++;
}
if(ind1<l1){
for(int i=ind1;i<l1;i++){
n[ind]=n1[i];
ind++;
}
}
if(ind2<l2){
for(int i=ind2;i<l2;i++){
n[ind]=n2[i];
ind++;
}
}
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class C138B
{
private static StringTokenizer st;
public static void nextLine(BufferedReader br) throws IOException
{
st = new StringTokenizer(br.readLine());
}
public static int nextInt()
{
return Integer.parseInt(st.nextToken());
}
public static String next()
{
return st.nextToken();
}
public static long nextLong()
{
return Long.parseLong(st.nextToken());
}
/**
* @param args
*/
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
nextLine(br);
int n = nextInt();
int k = nextInt();
int[] a = new int[n];
nextLine(br);
for (int i = 0; i < n; i++) a[i] = nextInt();
int bp = 0, fp = 0, count = 0;
boolean good = false;
int[] mark = new int[100001];
for (fp = 0; fp < n; fp++)
{
if (mark[a[fp]] == 0)
{
count++;
}
mark[a[fp]]++;
if (count == k)
{
good = true;
break;
}
}
if (!good)
{
System.out.println("-1 -1");
return;
}
for (bp = 0; bp < fp; bp++)
{
if (mark[a[bp]] > 1)
{
mark[a[bp]]--;
}
else break;
}
System.out.println((bp+1) + " " + (fp+1));
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
import java.math.BigInteger;
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 Sagimbekov_MA
*/
public class A483 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BigInteger l = sc.nextBigInteger();
BigInteger r = sc.nextBigInteger();
if (r.subtract(l).compareTo(new BigInteger("2")) == -1) {
System.out.println("-1");
} else if (r.subtract(l).compareTo(new BigInteger("2")) == 0 && l.mod(new BigInteger("2")) != BigInteger.ZERO) {
System.out.println("-1");
} else if (l.mod(new BigInteger("2")) != BigInteger.ZERO) {
System.out.println(l.add(BigInteger.ONE) + " " + l.add(BigInteger.ONE).add(BigInteger.ONE) + " " + l.add(BigInteger.ONE).add(BigInteger.ONE).add(BigInteger.ONE));
} else {
System.out.println(l + " " + l.add(BigInteger.ONE) + " " + l.add(BigInteger.ONE).add(BigInteger.ONE));
}
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class A implements Runnable {
private void Solution() throws IOException {
int n = nextInt();
if (n % 7 == 0 || n % 4 == 0 || n % 47 == 0 || n % 74 == 0 || n % 747 == 0 || n % 474 == 0 || n % 777 == 0 || n % 444 == 0 || n % 774 == 0 || n % 447 == 0 || n % 744 == 0 || n % 477 == 0)
System.out.println("YES"); else
System.out.println("NO");
}
public static void main(String args[]) {
new A().run();
}
BufferedReader in;
StringTokenizer tokenizer;
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
Solution();
in.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(in.readLine());
return tokenizer.nextToken();
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jenish
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
APaintTheNumbers solver = new APaintTheNumbers();
solver.solve(1, in, out);
out.close();
}
static class APaintTheNumbers {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int arr[] = new int[n];
in.scanInt(arr);
CodeX.sort(arr);
int ans = 0;
boolean vissited[] = new boolean[n];
for (int i = 0; i < n; i++) {
if (!vissited[i]) {
ans++;
for (int j = 0; j < n; j++) {
if (arr[j] % arr[i] == 0) {
vissited[j] = true;
}
}
}
}
out.println(ans);
}
}
static class CodeX {
public static void sort(int arr[]) {
merge_sort(arr, 0, arr.length - 1);
}
private static void merge_sort(int A[], int start, int end) {
if (start < end) {
int mid = (start + end) / 2;
merge_sort(A, start, mid);
merge_sort(A, mid + 1, end);
merge(A, start, mid, end);
}
}
private static void merge(int A[], int start, int mid, int end) {
int p = start, q = mid + 1;
int Arr[] = new int[end - start + 1];
int k = 0;
for (int i = start; i <= end; i++) {
if (p > mid)
Arr[k++] = A[q++];
else if (q > end)
Arr[k++] = A[p++];
else if (A[p] < A[q])
Arr[k++] = A[p++];
else
Arr[k++] = A[q++];
}
for (int i = 0; i < k; i++) {
A[start++] = Arr[i];
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public void scanInt(int[] A) {
for (int i = 0; i < A.length; i++) A[i] = scanInt();
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Queue;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Solution implements Runnable {
public static void main(String[] args) {
(new Thread(new Solution())).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String sti(String s) {
int res = 0;
int q = 1;
int qq = 0;
for (int i = 0; i < s.length(); i++) {
if (i > 0) qq += q;
res = res * 26 + s.charAt(i) - 'A';
q *= 26;
}
return Integer.toString(qq + res + 1);
}
String its(String s) {
int q = Integer.parseInt(s);
String res = "";
int w = 26;
int l = 1;
while (q > w) {
q -= w;
l++;
w *= 26;
}
q--;
if (q == 0) return "A";
while (q > 0) {
res = "" + (char)('A' + q % 26) + res;
l--;
q /= 26;
}
for (; l > 0; l--) res = "A" + res;
return res;
}
void solve() throws IOException {
int n = nextInt();
for (int i = 0; i < n; i++) {
String s = nextToken();
int j = 0;
while (!Character.isDigit(s.charAt(j))) j++;
int q = j + 1;
while (q < s.length() && Character.isDigit(s.charAt(q))) q++;
if (q == s.length()) {
out.println("R" + s.substring(j) + "C" + sti(s.substring(0, j)));
} else {
String w = s.substring(j, q);
while (!Character.isDigit(s.charAt(q))) q++;
out.println(its(s.substring(q)) + w);
}
}
}
public void run() {
try {
// in = new BufferedReader(new FileReader(new File("input.txt")));
// out = new PrintWriter(new File("output.txt"));
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
} catch (IOException e) {
e.printStackTrace();
}
out.flush();
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.awt.Point;
import java.util.Scanner;
public class p105b {
static int[] b, l;
static int n;
static int A;
static boolean[] masks;
static double max;
public static double work(int index, int k, int mask) {
if (index == n) {
if (Integer.bitCount(mask) * 2 <= n) {
int sum = 0;
for (int i = 0; i < n; i++) {
if (((1 << i) & mask) == 0) {
sum += b[i];
}
}
return (A * 1.0) / (A * 1.0 + sum);
}
return 1;
}
double max = 0;
int to = Math.min(k, (100 - l[index]) / 10);
for (int i = to; i >= 0; i--) {
double loy = l[index] + i * 10;
double b = ((100.0 - loy) / 100.0) * work(index + 1, k - i, mask);
double a = (loy / 100.0)
* work(index + 1, k - i, (mask | (1 << index)));
max = Math.max(max, a + b);
}
return max;
}
public static void rec(int index, int k) {
if (k == -1)
return;
if (index == n) {
double tot = 0;
for (int i = 0; i < 1 << n; i++) {
double temp = 1.0;
int bb = 0;
for (int j = 0; j < n; j++) {
if(l[j]>100)
return;
if (((1 << j) & i) != 0) {
temp *= (l[j] * 1.0 / 100.0);
} else {
bb += b[j];
temp *= ((100.0 - l[j]) / 100.0);
}
}
if (Integer.bitCount(i) * 2 <= n) {
temp *= (A * 1.0) / (A * 1.0 + bb);
}
tot += temp;
}
max = Math.max(max, tot);
return;
}
l[index] += 10;
rec(index, k - 1);
l[index] -= 10;
rec(index + 1, k);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
int k = in.nextInt();
A = in.nextInt();
b = new int[n];
l = new int[n];
for (int i = 0; i < n; i++) {
b[i] = in.nextInt();
l[i] = in.nextInt();
}
masks = new boolean[1 << n];
max = 0;
rec(0, k);
System.out.println(max);
}
}
/*
* 5 3 100 23 70 80 30 153 70 11 80 14 90
*/
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
public class Main {
public static void main(String[] args) {
solve(System.in,System.out);
}
static void solve(InputStream inStream, PrintStream printStream) {
Scanner in = new Scanner(inStream);
int n = in.nextInt();
long[] sums = new long[n];
for (int i = 1; i < n; i++) {
sums[i]=0;
}
sums[0]=1;
long mod = 1000000007;
for (int i = 0; i < n; i++) {
if (in.next().equals("f") ) {
for (int j = n-1; j > 0 ; j--) {
sums[j]=sums[j-1];
}
sums[0]=0;
} else {
for (int j = n-2; j >= 0 ; j--) {
sums[j] += sums[j+1];
if (sums[j]>=mod) {
sums[j]-=mod;
}
}
}
}
// long finalSum = 0;
// for (int i = 0; i < n; i++) {
// finalSum+=sums[i];
// }
printStream.println(sums[0]);
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
FastScanner sc = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
long dest = sc.nextLong();
long max = (long)N * ((long)N + 1L) / 2L;
if (dest < 2 * N - 1 || dest > max) {
out.println("No");
out.close();
return;
}
int[] d = new int[N + 1];
int[] f = new int[N + 1];
int K = 1;
for (; K <= N; K++) {
long dep = 1L, cnt = 1L, c = 1L;
long t = 1L;
while (cnt < N) {
c = c * K;
dep++;
t += (dep * Math.min(c, N - cnt));
cnt += c;
}
if (t <= dest) break;
}
out.println("Yes");
int dep = 1; long cnt = 1L, c = 1L;
long t = 1L;
d[1] = 1;
while (cnt < N) {
dep++; c = c * K;
long x = (long)N - cnt;
int min;
if (c >= x) min = (int)x;
else min = (int)c;
d[dep] = min;
t += (dep * Math.min(c, (long)N - cnt)); cnt += c;
}
dest -= t;
int curDep = dep; int nextDep = dep + 1;
while (dest > 0) {
if (d[curDep] <= 1) curDep--;
d[curDep]--;
long next = Math.min(nextDep++, dest + curDep);
dest -= ((int)next - curDep);
d[(int)next]++;
}
int first = 1;
for (int i = 2; i < nextDep; i++) {
int p = 0, fn = first - d[i - 1] + 1;
for (int j = first + 1; j <= first + d[i]; j++) {
if (p == K) {
fn++; p = 0;
}
p++; f[j] = fn;
}
first += d[i];
}
for (int i = 2; i <= N; i++)
out.format("%d ", f[i]);
out.close();
}
static class FastScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
/* 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;
}*/
}
}
|
nlogn
|
1098_C. Construct a tree
|
CODEFORCES
|
//package round168;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), K = ni();
int[] a = na(n);
if(K == 1){
out.println(n);
return;
}
a = radixSort(a);
boolean[] dead = new boolean[n];
int ct = 0;
for(int i = 0;i < n;i++){
if(!dead[i]){
ct++;
if((long)a[i]*K<=1000000000){
int ind = Arrays.binarySearch(a, a[i]*K);
if(ind >= 0){
dead[ind] = true;
}
}
}
}
out.println(ct);
}
public static int[] radixSort(int[] f)
{
int[] to = new int[f.length];
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new A().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.io.IOException;
import java.util.Scanner;
/**
* TODO: describe
*
* @author keks
*/
public class A {
public static void main(String[] args) throws IOException {
final Scanner sc = new Scanner(System.in);
final int n = sc.nextInt();
if (n % 2 == 0) {
System.out.println(4 + " " + (n - 4));
} else {
System.out.println(9 + " " + (n - 9));
}
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.BigInteger;
public class Main implements Runnable {
private final String problemname = "";
private final String FILE_IN = problemname + ".in";
private final String FILE_OUT = problemname + ".out";
public void run() {
// in = new BufferedReader(new FileReader(FILE_IN));
// out = new PrintWriter(FILE_OUT);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
_st = new StringTokenizer("");
// TODO: type your code here
int n = nextInt();
int best = n + n / 2;
/*
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n - i; j++) {
best = Math.max(best, i + j + Math.min(n - i, n - j));
}
}*/
out.println(best);
try {
in.close();
out.close();
}
catch (Exception e) {
System.err.println("Epic fail");
}
}
BufferedReader in;
PrintWriter out;
StringTokenizer _st;
public static void main(String[] args) {
new Thread(new Main()).start();
}
private void seek() {
while (!_st.hasMoreTokens()) {
String s;
try {
s = in.readLine();
_st = new StringTokenizer(s);
} catch (Exception e) {
return;
}
}
}
private String next() {
seek();
return _st.nextToken();
}
private int nextInt() {
return Integer.parseInt(next());
}
private long nextLong() {
return Long.parseLong(next());
}
private double nextDouble() {
return Double.parseDouble(next());
}
private BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author beginner1010
*/
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);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
HashMap<Integer, Integer> map = new HashMap<>();
boolean[] dp;
boolean[] vis;
boxPair[] ans;
int two(int bit) {
return 1 << bit;
}
boolean contain(int mask, int bit) {
return ((two(bit) & mask) > 0);
}
int get(long val) {
if (val > Integer.MAX_VALUE || val < Integer.MIN_VALUE) return -1;
int key = (int) val;
if (map.containsKey(key) == false) return -1;
return map.get(key);
}
boolean rec(int mask, boolean[] hasCycle) {
if (hasCycle[mask]) return true;
if (vis[mask] == true) return dp[mask];
vis[mask] = true;
for (int i = mask & (mask - 1); i > 0; i = mask & (i - 1)) {
if (rec(i, hasCycle) && rec(i ^ mask, hasCycle)) {
return dp[mask] = true;
}
}
return dp[mask] = false;
}
void findPath(int mask, boolean[] hasCycle, ArrayList<boxPair>[] maskPath) {
if (hasCycle[mask]) {
for (boxPair b : maskPath[mask]) {
ans[get(b.addTo)] = b;
}
return;
}
for (int i = mask & (mask - 1); i > 0; i = mask & (i - 1)) {
if (rec(i, hasCycle) && rec(i ^ mask, hasCycle)) {
findPath(i, hasCycle, maskPath);
findPath(i ^ mask, hasCycle, maskPath);
return;
}
}
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int k = in.nextInt();
int[][] a = new int[k][];
int[] n = new int[k];
long[] sum = new long[k];
long S = 0;
for (int i = 0; i < k; i++) {
n[i] = in.nextInt();
a[i] = new int[n[i]];
for (int j = 0; j < n[i]; j++) {
a[i][j] = in.nextInt();
sum[i] += a[i][j];
map.put(a[i][j], i);
}
S += sum[i];
}
if (S % k != 0) out.println("No");
else {
ArrayList<boxPair>[] maskPath = new ArrayList[two(k)];
boolean[] hasCycle = new boolean[two(k)];
for (int i = 0; i < two(k); i++) {
maskPath[i] = new ArrayList<>();
}
long balance = S / k;
for (int i = 0; i < k; i++) {
for (int j = 0; j < n[i]; j++) {
long remove = a[i][j];
int curID = i;
int curMask = 0;
ArrayList<boxPair> curPath = new ArrayList<>();
while (true) {
curMask |= two(curID);
remove = (balance - (sum[curID] - remove));
int nxtID = get(remove);
curPath.add(new boxPair(curID, (int) remove));
if (nxtID == i && remove == a[i][j]) {
if (hasCycle[curMask] == false) {
hasCycle[curMask] = true;
maskPath[curMask] = curPath;
}
break;
}
if (nxtID == -1 || contain(curMask, nxtID)) break;
curID = nxtID;
}
}
}
vis = new boolean[two(k)];
dp = new boolean[two(k)];
if (rec(two(k) - 1, hasCycle) == false) out.println("No");
else {
ans = new boxPair[k];
findPath(two(k) - 1, hasCycle, maskPath);
out.println("Yes");
for (int i = 0; i < k; i++) {
out.println(ans[i].addTo + " " + (ans[i].boxID + 1));
}
}
}
}
class boxPair {
int boxID;
int addTo;
boxPair(int _boxID, int _addTo) {
this.boxID = _boxID;
this.addTo = _addTo;
}
}
}
static class InputReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0;
private int ptrbuf = 0;
static final int[] ints = new int[128];
public InputReader(InputStream is) {
for (int i = '0'; i <= '9'; i++) ints[i] = i - '0';
this.is = is;
}
public int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + ints[b];
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
}
|
np
|
1242_C. Sum Balance
|
CODEFORCES
|
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.regex.*;
import static java.lang.Math.*;
public class A {
public A() throws Exception {
int n = in.nextInt();
int[] arr = new int[n];
for (int i=0; i<n; i++) arr[i] = in.nextInt();
int[] arr2 = arr.clone();
Arrays.sort(arr2);
int diff = 0;
for (int i=0; i<n; i++) {
if (arr2[i]!=arr[i]) diff++;
}
if (diff<=2) System.out.println("YES");
else System.out.println("NO");
}
Scanner in = new Scanner(System.in);
StringBuilder buf = new StringBuilder();
public static void main(String[] args) throws Exception { // {{{
new A();
} // }}}
public static void debug(Object... arr) { // {{{
System.err.println(Arrays.deepToString(arr));
} // }}}
public static class Scanner { // {{{
BufferedReader br;
String line;
StringTokenizer st;
public Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public boolean hasNext() throws IOException {
while ((st==null||!st.hasMoreTokens())&&(line=br.readLine())!=null)
st = new StringTokenizer(line);
return st.hasMoreTokens();
}
public String next() throws IOException {
if (hasNext()) return st.nextToken();
throw new NoSuchElementException();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
} // }}}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class C implements Runnable {
private void Solution() throws IOException {
int n = nextInt(), max = 0, maxi = 0;
ArrayList<Integer> mas = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
int num = nextInt();
if (num > max) {
max = num;
maxi = i;
}
mas.add(num);
}
mas.remove(maxi);
mas.add(max == 1 ? 2 : 1);
Collections.shuffle(mas);
Collections.sort(mas);
for (int i = 0; i < n; i++)
System.out.print(mas.get(i) + " ");
}
public static void main(String[] args) {
new C().run();
}
BufferedReader in;
StringTokenizer tokenizer;
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
Solution();
in.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(in.readLine());
return tokenizer.nextToken();
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
System.out.println(n * 6 / 4);
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st = new StringTokenizer("");
static PrintWriter pw = new PrintWriter(System.out);
public static String next() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static void main(String[] args) throws IOException {
new Main().run();
}
void run() throws IOException {
long n = nextInt();
long k = nextInt();
long d = 9 + 8 * (n + k);
pw.print(n - (-3 + (int)Math.sqrt(d)) / 2);
pw.close();
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
final int[] dr = {-1, 0, 1, 0};
final int[] dc = {0, -1, 0, 1};
int height = in.nextInt();
int width = in.nextInt();
int k = in.nextInt();
int[][][] cost = new int[4][height][width];
for (int r = 0; r < height; r++) {
for (int c = 0; c + 1 < width; c++) {
int x = in.nextInt();
cost[3][r][c] = x;
cost[1][r][c + 1] = x;
}
}
for (int r = 0; r + 1 < height; r++) {
for (int c = 0; c < width; c++) {
int x = in.nextInt();
cost[2][r][c] = x;
cost[0][r + 1][c] = x;
}
}
boolean odd = (k % 2 != 0);
k /= 2;
int[][][] d = new int[k + 1][height][width];
for (int len = 1; len <= k; len++) {
for (int r = 0; r < height; r++) {
for (int c = 0; c < width; c++) {
d[len][r][c] = Integer.MAX_VALUE;
for (int dir = 0; dir < 4; dir++) {
int nr = r + dr[dir];
int nc = c + dc[dir];
if (nr < 0 || nr >= height || nc < 0 || nc >= width) {
continue;
}
d[len][r][c] = Math.min(d[len][r][c], d[len - 1][nr][nc] + cost[dir][r][c]);
}
}
}
}
for (int r = 0; r < height; r++) {
for (int c = 0; c < width; c++) {
if (c > 0) {
out.print(" ");
}
out.print(odd ? -1 : 2 * d[k][r][c]);
}
out.println();
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class C {
static int n, m, a[][];
static int[][] memo;
static int[] getCol(int col, int shift) {
int[] ans = new int[n];
for (int i = 0, j = shift; i < n; i++, j = (j + 1) % n) {
ans[i] = a[j][col];
}
return ans;
}
static int dp(int col, int msk) {
if (col == m)
return 0;
if (memo[msk][col] != -1)
return memo[msk][col];
int ans = 0;
for (int shift = 0; shift < n; shift++) {
int[] currCol = getCol(col, shift);
for (int nxtMsk = 0; nxtMsk < 1 << n; nxtMsk++) {
if ((nxtMsk & msk) != msk)
continue;
int curr = 0;
int diff = msk ^ nxtMsk;
for (int i = 0; i < n; i++)
if ((diff & 1 << i) != 0)
curr += currCol[i];
ans = Math.max(ans, dp(col + 1, nxtMsk) + curr);
}
}
return memo[msk][col] = ans;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int tc = sc.nextInt();
while (tc-- > 0) {
n = sc.nextInt();
m = sc.nextInt();
memo = new int[1 << n][m];
for (int[] x : memo)
Arrays.fill(x, -1);
a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = sc.nextInt();
out.println(dp(0, 0));
}
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());
}
boolean ready() throws IOException {
return br.ready();
}
}
static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
static void shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;
public class Main {
public static void main(String[] args) throws IOException {
(new Main()).solve();
}
public void Main() {
}
void solve() throws IOException {
// BufferedReader in = new BufferedReader(new
// InputStreamReader(System.in));
// Scanner in = new Scanner(System.in);
MyReader in = new MyReader();
PrintWriter out = new PrintWriter(System.out);
// Scanner in = new Scanner(new FileReader("input.txt"));
// PrintWriter out = new PrintWriter("output.txt");
int n = in.nextInt();
out.print("0 0 ");
out.print(n);
out.close();
}
};
class MyReader {
private BufferedReader in;
String[] parsed;
int index = 0;
public MyReader() {
in = new BufferedReader(new InputStreamReader(System.in));
}
public int nextInt() throws NumberFormatException, IOException {
if (parsed == null || parsed.length == index) {
read();
}
return Integer.parseInt(parsed[index++]);
}
public long nextLong() throws NumberFormatException, IOException {
if (parsed == null || parsed.length == index) {
read();
}
return Long.parseLong(parsed[index++]);
}
public String nextString() throws IOException {
if (parsed == null || parsed.length == index) {
read();
}
return parsed[index++];
}
private void read() throws IOException {
parsed = in.readLine().split(" ");
index = 0;
}
public String readLine() throws IOException {
return in.readLine();
}
};
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class CodeChef2 {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
//
// static class Line{
// Point p1;
// Point p2;
//
// Line(Point p1,Point p2){
// this.p1=p1;
// this.p2=p2;
// }
//
// static Boolean intersects(Line l1,Line l2)
// {
// Point A=l1.p1, B=l1.p2,C=l2.p1,D=l2.p2;
//
// long a1 = B.y - A.y;
// long b1 = A.x - B.x;
// long c1 = a1*(A.x) + b1*(A.y);
//
// long a2 = D.y - C.y;
// long b2 = C.x - D.x;
// long c2 = a2*(C.x)+ b2*(C.y);
//
// long determinant = a1*b2 - a2*b1;
//
// if (determinant == 0)
// {
// return false;
// }
// else
// {
// long x = (b2*c1 - b1*c2)/determinant;
// long y = (a1*c2 - a2*c1)/determinant;
//
// if(x>=0 || x<=1) {
// return true;
// }
// return false;
// }
// }
//
// static Point getSlope(Line l) {
// long num=l.p1.y - l.p2.y;
// long den=l.p1.x - l.p2.x;
//
// long gcd=gcd(num,den);
// return new Point(num/gcd,den/gcd);
// }
//
// private static long gcd(long a, long b) {
// return b==0?a:gcd(b,a%b);
// }
//
// }
static class Pair{
int x;
long y;
Pair(int x,long y, Integer integer, int i){
this.y=y;
this.x=x;
}
@Override
public String toString() {
return "(" + x +" "+ y+")";
}
}
static class Edge{
int src;
int dest;
int cost;
int val;
Edge(int src,int dest,int cost,int val){
this.src=src;
this.dest=dest;
this.cost=cost;
this.val=val;
}
public String toString() {
return "(" + src +" "+ dest+": "+ cost +" , "+val+")";
}
}
static class Pair2{
Pair node;
int dist;
Pair2(Pair p,int dist){
node=p;
this.dist=dist;
}
}
static long M=1000000007l;
static HashMap<Character,ArrayList<Character>> dirs;
public static void main(String[] args) throws Exception {
FastReader sc=new FastReader();
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
// ArrayList<Integer> prime=getPrimeSieve();
int t=sc.nextInt();
int po=0;
dirs=new HashMap<>();
dirs.put('U', new ArrayList<>());
dirs.get('U').addAll(Arrays.asList('U','R','D','L'));
dirs.put('L', new ArrayList<>());
dirs.get('L').addAll(Arrays.asList('L','U','R','D'));
dirs.put('D', new ArrayList<>());
dirs.get('D').addAll(Arrays.asList('D','L','U','R'));
dirs.put('R', new ArrayList<>());
dirs.get('R').addAll(Arrays.asList('R','D','L','U'));
//
outer:while(t-- >0) {
po++;
int n=sc.nextInt();
int x=(int) Math.sqrt(n/2);
int y=(int) Math.sqrt(n/4);
if(x*x*2 == n || y*y*4==n)
bw.append("YES\n");
else {
bw.append("NO\n");
}
// int x=sc.nextInt();
// Integer[] arr=new Integer[n];
// long sum=0;
//
// for(int i=0;i<n;i++) {
// arr[i]=sc.nextInt();
// sum+=arr[i];
// }
//
// if(sum==x) {
// bw.append("NO\n");
// continue outer;
// }
//
// Arrays.sort(arr,Collections.reverseOrder());
//
// sum=0;
// for(int i=0;i<n-1;i++) {
// sum+=arr[i];
//
// if(sum==x) {
// int temp=arr[i];
// arr[i+1]=arr[i];
// arr[i]=temp;
// sum=sum-arr[i+1]+arr[i];
// }
// }
// bw.append("YES\n");
// for(int i=0;i<n;i++) {
// bw.append(arr[i]+" ");
// }
// bw.append("\n");
// bw.append("Case #"+po+": "+0+"\n");
}
bw.close();
}
private static int abs(int i) {
if(i<0) {
return -i;
}
return i;
}
private static String getRoaring2(String s) {
String res="";
String max="";
for(int i=1;i<=s.length()/2;i++) {
long prev=Long.parseLong(s.substring(0, i));
res=Long.toString(prev);
long prev1=Long.parseLong(res);
long ans=Long.parseLong(s);
long next=prev+1;
while(prev1 <= ans) {
prev1=Long.parseLong(res+Long.toString(next));
res+=Long.toString(next);
next++;
}
if(max.length() == 0) {
max=res;
res="";
}else {
Long a=Long.parseLong(max);
long m=Math.max(a, prev1);
max=Long.toString(m);
}
}
return max;
}
private static String getRoaring(String s) {
int val=-1;
for(int i=1;i<=s.length()/2;i++) {
long prev=Long.parseLong(s.substring(0, i));
int j=i,update=i;
while(j<s.length()) {
if(numDigit(prev+1) > numDigit(prev)) {
update++;
}
if(j+update > s.length()) {
break;
}
long cur=Long.parseLong(s.substring(j, j+update));
if(cur != prev+1) {
break;
}
prev=cur;
j+=update;
}
if(j>= s.length()) {
val=i;
break;
}
}
if(val==-1) {
return "";
}else {
String res="";
long prev=Long.parseLong(s.substring(0, val));
res=Long.toString(prev+1);
System.out.println(res+ " ");
long prev1=Long.parseLong(res);
long ans=Long.parseLong(s);
long next=prev+1;
while(prev1 <= ans) {
prev1=Long.parseLong(res+Long.toString(next));
next++;
}
return Long.toString(prev1);
}
}
private static boolean isRoaring(String s) {
for(int i=1;i<=s.length()/2;i++) {
long prev=Long.parseLong(s.substring(0, i));
// System.out.println("prev= "+prev+" ");
int j=i,update=i;
while(j<s.length()) {
if(numDigit(prev+1) > numDigit(prev)) {
update++;
}
if(j+update > s.length()) {
break;
}
long cur=Long.parseLong(s.substring(j, j+update));
// System.out.println("cur= "+cur+" ");
if(cur != prev+1) {
break;
}
prev=cur;
j+=update;
}
if(j>= s.length()) {
return true;
}
}
return false;
}
private static long numDigit(long ans) {
long sum=0;
while(ans > 0) {
sum++;
ans/=10;
}
return sum;
}
private static boolean go(int i, int j, long n, long m, Integer k, HashMap<Integer, Boolean>[][] dp) {
if(i==n && j==m && k==0) {
return true;
}
if(i<1 || j<1 || i>n || j>m || k<0) {
return false;
}
if(dp[i][j].containsKey(k)) {
return dp[i][j].get(k);
}
boolean down=go(i+1,j,n,m,k-j,dp);
boolean left=go(i,j+1,n,m,k-i,dp);
dp[i][j].put(k, left||down);
return left||down;
}
private static long getDigitSum(long ans) {
long sum=0;
while(ans > 0) {
sum+=ans%10;
ans/=10;
}
return sum;
}
private static boolean getAns2(int l, long[] prefix, long x) {
for(int i=l;i<prefix.length-1;i++) {
if((x^prefix[i]) == (prefix[prefix.length-1]^prefix[i])) {
return true;
}
}
return false;
}
private static boolean getAns(long[] prefix) {
for(int i=0;i<prefix.length-1;i++) {
if(prefix[i] == (prefix[prefix.length - 1]^prefix[i])) {
return true;
}
}
return false;
}
private static void rotate(ArrayList<Integer> arr, int i) {
reverse(arr,0,i-1);
reverse(arr,i,arr.size()-1);
reverse(arr,0,arr.size()-1);
}
private static void reverse(ArrayList<Integer> arr, int l, int m) {
while(l<m) {
int temp=arr.get(l);
arr.set(l,arr.get(m));
arr.set(m, temp);
l++;
m--;
}
}
static int modInverse(int a, int m)
{
int m0 = m;
int y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1) {
int q = a / m;
int t = m;
m = a % m;
a = t;
t = y;
y = x - q * y;
x = t;
}
if (x < 0)
x += m0;
return x;
}
private static long isPerfectSquare(long num) {
long l=1,h=num;
while(l<=h) {
long mid=l+(h-l)/2;
if(mid*mid == num) {
return mid;
}else if(mid*mid < num) {
l=mid+1;
}else {
h=mid-1;
}
}
return -1;
}
private static void rightmax(long[] arr, long n,int[] res,int[] rightmax) {
Deque<Integer> stack=new ArrayDeque<>();
stack.clear();
for(int i=(int) (n-1);i>=0;i--) {
while(!stack.isEmpty() && arr[stack.peek()] <= arr[i]) {
stack.pop();
}
rightmax[i]=(stack.isEmpty()?Integer.MAX_VALUE:stack.peek());
stack.addFirst(i);
}
}
private static boolean rotatedSorted(long[] arr, int min) {
reverse(arr,0,min-1);
reverse(arr,min,arr.length-1);
reverse(arr,0,arr.length-1);
if(isSorted(arr)) {
return true;
}
return false;
}
private static boolean isSorted(long[] arr) {
for(int i=1;i<arr.length;i++) {
if(arr[i] < arr[i-1]) {
return false;
}
}
return true;
}
private static int countDigit(long x) {
int count=0;
while(x > 0) {
x/=10;
count++;
}
return count;
}
private static boolean isSub(String s, String c) {
int l=0;
for(int i=0;i<s.length();i++) {
if(l < c.length() && c.charAt(l)==s.charAt(i)) {
l++;
}
if(l==c.length()) {
break;
}
}
if(l==c.length()) {
return true;
}
return false;
}
static long power(long a, long d, long n)
{
long res = 1;
a = a % n;
if (a == 0)
return 0;
while (d > 0)
{
if ((d & 1) != 0)
res = (res * a) % n;
d = d >> 1;
a = (a * a) % n;
}
return res;
}
private static void reverse(long[] arr,int l,int m) {
while(l<m) {
long temp=arr[l];
arr[l]=arr[m];
arr[m]=temp;
l++;
m--;
}
}
static int UpperBound(ArrayList<Integer> a, int x) {// x is the key or target value
int l=-1,r=a.size();
while(l+1<r) {
int m=(l+r)>>>1;
if(a.get(m)<=x) l=m;
else r=m;
}
return l+1;
}
private static void printMat(int[][] dp) {
System.out.println("--------------------------------------------------------------------");
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
System.out.print(dp[i][j]+" ");
}
System.out.println();
}
System.out.println("--------------------------------------------------------------------");
}
private static int highestOneBit(long n) {
long x=Long.highestOneBit(n);
int c=0;
while(x >0) {
x=x/2;
c++;
}
return c-1;
}
private static int bitcount(long l) {
int count=0;
while(l>0) {
l-=(l&(-l));
count++;
}
return count;
}
private static void bfs(HashMap<Integer, HashSet<Integer>> tree, int start) {
Queue<Integer> q=new LinkedList<>();
q.offer(start);
HashSet<Integer> visited=new HashSet<>();
System.out.print(q.peek()+"\n");
while(!q.isEmpty()) {
int parent=q.poll();
if(visited.contains(parent)) {
continue;
}
visited.add(parent);
int flag=0;
for(int child:tree.get(parent)) {
if(!visited.contains(child)) {
q.offer(child);
System.out.print(child+" ");
flag=1;
}
}
if(flag==0) {
continue;
}
System.out.println();
}
}
static int par;
private static HashMap<Integer, HashSet<Integer>> getTreeInputLevel(StringTokenizer st) {
Queue<Integer> q=new LinkedList<>();
HashMap<Integer, HashSet<Integer>> tree=new HashMap<>();
q.offer(Integer.parseInt(st.nextToken()));
par=q.peek();
while(!q.isEmpty()) {
int parent=q.poll();
if(!tree.containsKey(parent)) {
tree.put(parent, new HashSet<Integer>());
}
int left=-1,right=-1;
if(st.hasMoreElements())
left=Integer.parseInt(st.nextToken());
if(st.hasMoreElements())
right=Integer.parseInt(st.nextToken());
if(left != -1) {
tree.get(parent).add(left);
if(!tree.containsKey(left)) {
tree.put(left, new HashSet<Integer>());
}
tree.get(left).add(parent);
q.offer(left);
}
if(right != -1) {
tree.get(parent).add(right);
if(!tree.containsKey(right)) {
tree.put(right, new HashSet<Integer>());
}
tree.get(right).add(parent);
q.offer(right);
}
}
tree.remove(-1);
return tree;
}
private static int containsString(String s1,String s2) {
String s=s1+"#"+s2;
int[] z=getZfunc(s);
boolean flag=false;
for(int i=0;i<s.length();i++) {
if(z[i]==s1.length()) {
flag=true;
}
}
int count=0;
for(int i=s1.length();i<z.length;i++) {
// System.out.print(z[i]+" ");
if(z[i]==s1.length()) {
count++;
}
}
// System.out.println();
return count;
}
private static int[] getZfunc(String s) {
int[] z=new int[s.length()];
int l=0,r=0;
for(int i=1;i<s.length();i++) {
if(i <= r) {
z[i]=Math.min( z[i-l] , r-i+1);
}
while(i+z[i] < s.length() && s.charAt(z[i])==s.charAt(i+z[i])) {
z[i]++;
}
if(i+z[i] -1 > r) {
l=i;
r=i+z[i]-1;
}
}
return z;
}
private static long ceil(long n,long k) {
long ans;
if(n%k==0) {
ans=n/k;
}else {
ans=n/k+1;
}
return ans;
}
static ArrayList<Integer> getDivisor(int n){
ArrayList<Integer> div=new ArrayList<>();
for (int i=1; i*i <= n; i++)
{
if (n%i==0)
{
if (n/i == i)
div.add(i);
else {
div.add(i);
div.add(n/i);
}
}
}
return div;
}
static long gcd(long x,long y) {
return (y==0?x:gcd(y,x%y));
}
static int MAXN = 1000001;
static int[] spf=new int[MAXN];
static void sieveSmallestFactor()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
spf[i] = i;
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
if (spf[i] == i)
{
for (int j=i*i; j<MAXN; j+=i)
if (spf[j]==j)
spf[j] = i;
}
}
}
private static HashMap<Integer,Integer> PrimeFactorizationmap(long n) {
int count=0;
HashMap<Integer,Integer> factors=new HashMap<>();
if(n==1) {
factors.put( 1,1);
return factors;
}else {
for(long i=2; i*i <= n ;i++) {
long z=n;
if(z%i==0) {
count=0;
while(z%i==0) {
count++;
z=z/i;
}
factors.put((int) (i+0),count);
}
}
if(n>1) {
factors.put((int) (n+0),1);
}
}
return factors;
}
static HashMap<Integer,Integer> getprimeFactors(int n)
{
HashMap<Integer,Integer> ret = new HashMap<>();
while (n > 1)
{
if(ret.containsKey(spf[n])) {
ret.put(spf[n],ret.get(spf[n])+1);
}else {
ret.put(spf[(int) n],1);
}
n = n / spf[n];
}
return ret;
}
static ArrayList<Integer> getPrimeSieve(){
int primesieve[]=new int[1000005];
Arrays.fill(primesieve,0);
for(int i=2;i*i<primesieve.length;i++) {
if(primesieve[i]==0)
for(int j=i*i;j<primesieve.length;j+=i) {
primesieve[j]=1;
}
}
ArrayList<Integer> prime=new ArrayList<>();
for(int i=2;i<primesieve.length;i++) {
if(primesieve[i]==0) {
prime.add(i);
}
}
return prime;
}
private static boolean checkPrimeRM(long n,int k) {
if(n<=4) {
return n==2||n==3;
}
int s=0;
long d=n-1;
while((d&1) != 1) {
d=d/2;
s++;
}
for(int i=0;i<k;i++) {
long a=2+(int)Math.random()*(n-4);
if(isComposite(a,s,d,n)) {
return false;
}
}
return true;
}
private static boolean isComposite(long a, int s, long d, long n) {
long x=power(a,d,n);
if(x==1 || x==n-1) {
return false;
}
for(int i=0;i<s;i++){
if(x%(n-1)==0) {
return false;
}
x=(x*x)%n;
}
return true;
}
public static HashSet<Long> getPrimeLtoR(int l,int r,List<Integer> prime) {
if(l==1) l++;
int[] arr=new int[r-l+1];
Arrays.fill(arr,0);
for(int i: prime ){
if(i*i<=r) {
int j=(l/i)*i;
if(j<l)
j+=i;
for(;j<=r;j+=i) {
if(j!=i)
arr[j-l]=1;
}
}else {
break;
}
}
HashSet<Long> primeLtoR=new HashSet<>();
for(int i=0;i<arr.length;i++) {
if(arr[i]==0) {
primeLtoR.add((i+l+0l));
}
}
return primeLtoR;
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.InputMismatchException;
/**
* @author Egor Kulikov (egor@egork.net)
* Created on 14.03.2010
*/
public class TaskD implements Runnable {
private InputReader in;
private PrintWriter out;
private int n;
private int m;
private boolean[][] e;
private long[][] qp;
private static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1000];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private 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 String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
}
public static void main(String[] args) {
// new Thread(new Template()).start();
new TaskD().run();
}
public TaskD() {
// String id = getClass().getName().toLowerCase();
// try {
// System.setIn(new FileInputStream(id + ".in"));
// System.setOut(new PrintStream(new FileOutputStream(id + ".out")));
// } catch (FileNotFoundException e) {
// throw new RuntimeException();
// }
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
public void run() {
// int numTests = in.readInt();
// for (int testNumber = 0; testNumber < numTests; testNumber++) {
// }
n = in.readInt();
m = in.readInt();
e = new boolean[n][n];
for (int i = 0; i < m; i++) {
int a = in.readInt() - 1;
int b = in.readInt() - 1;
e[a][b] = e[b][a] = true;
}
// n = 19;
// e = new boolean[n][n];
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < n; j++)
// e[i][j] = i != j;
// }
int msk = (1 << n) - 1;
qp = new long[n - 1][1 << (n - 1)];
long ans = 0;
for (int i = n - 1; i >= 0; i--) {
msk -= (1 << i);
for (int k = 0; k < i; k++)
Arrays.fill(qp[k], 0, 1 << i, -1);
for (int j = 0; j < i; j++) {
if (e[i][j]) {
e[i][j] = e[j][i] = false;
ans += go(j, msk - (1 << j), i);
e[i][j] = e[j][i] = true;
}
}
}
out.println(ans / 2);
out.close();
}
private long go(int v, int msk, int u) {
if (qp[v][msk] != -1)
return qp[v][msk];
qp[v][msk] = 0;
if (e[v][u])
qp[v][msk] = 1;
for (int i = 0; i < u; i++) {
if (e[v][i] && ((msk >> i) & 1) != 0)
qp[v][msk] += go(i, msk - (1 << i), u);
}
return qp[v][msk];
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class C{
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main (String[] args) throws IOException {
int t = Integer.parseInt(br.readLine());
while(t-- > 0) {
int n = Integer.parseInt(br.readLine());
int prev = 1;
ArrayList<Integer> nums = new ArrayList<>();
nums.add(1);
String till = "1";
for(int i=0;i<n;i++) {
int ln = Integer.parseInt(br.readLine());
if(i == 0) {
bw.write("1\n");
continue;
}
if(ln == 1) {
nums.add(1);
}else if(ln == prev + 1) {
nums.set(nums.size()-1, ln);
}else {
int idx = -1;
for(int j=nums.size()-1;j>=0;j--) {
if(nums.get(j) == ln-1) {
idx = j;
break;
}
}
ArrayList<Integer> temp = new ArrayList<>();
for(int j=0;j<idx;j++) {
temp.add(nums.get(j));
}
temp.add(ln);
nums.clear();
nums = temp;
}
for(int j=0;j<nums.size()-1;j++) {
bw.write(nums.get(j) + ".");
}
bw.write(nums.get(nums.size()-1) + "\n");
prev = ln;
}
}
bw.flush();
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class CF {
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=null;
private void solution() throws IOException{
int n=nextInt();
if((n % 4==0 && n>=4)||(n % 7==0 && n>=7) || (n % 44==0 && n>=44) || (n % 47==0 && n>=47) || (n % 77==0 && n>=77) || (n % 74==0 && n>=74)
|| (n % 444==0 && n>=444) || (n % 447==0 && n>=447) || (n % 474==0 && n>=74) || (n % 477==0 && n>=477) || (n % 744==0 && n>=744)
|| (n % 747==0 && n>=747) || (n % 777==0 && n>=777) || (n % 774==0 && n>=774)){
System.out.println("YES");
}else{
System.out.println("NO");}
}
String nextToken()throws IOException {
if(st==null || !st.hasMoreTokens()){
st = new StringTokenizer(bf.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());
}
public static void main(String args[]) throws IOException {
new CF().solution();
}
}
|
constant
|
122_A. Lucky Division
|
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.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
G1PlaylistForPolycarpEasyVersion solver = new G1PlaylistForPolycarpEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class G1PlaylistForPolycarpEasyVersion {
static ArrayList<Integer> list;
static int n;
static int req;
static int mod = (int) 1e9 + 7;
static int[] dur;
static int[] genre;
static Integer[][][] memo;
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
n = sc.nextInt();
req = sc.nextInt();
dur = new int[n];
genre = new int[n];
list = new ArrayList<>();
for (int i = 0; i < n; i++) {
dur[i] = sc.nextInt();
genre[i] = sc.nextInt();
}
int ans = 0;
memo = new Integer[1 << n][n + 1][4];
for (int i = 0; i <= n; i++)
ans += bf(0, 0, 0, i) % mod;
pw.print(ans % mod);
}
private int bf(int idx, int msk, int before, int max) {
if (idx == max) {
int sum = 0;
for (int x : list)
sum += x;
if (sum == req)
return 1;
return 0;
}
if (memo[msk][max][before] != null)
return memo[msk][max][before] % mod;
int toRet = 0;
for (int i = 0; i < n; i++) {
if (genre[i] != before && (msk & 1 << i) == 0) {
list.add(dur[i]);
toRet += bf(idx + 1, msk | 1 << i, genre[i], max);
toRet %= mod;
list.remove(list.size() - 1);
}
}
return memo[msk][max][before] = (toRet % mod);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class cf2 {
static final double EPS = 1e-9;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
//rec
int xr1=sc.nextInt(), yr1=sc.nextInt(), xr2=sc.nextInt(),yr2=sc.nextInt();
int xr3=sc.nextInt(), yr3=sc.nextInt(), xr4=sc.nextInt(),yr4=sc.nextInt();
Point pr1 = new Point(xr1, yr1);
Point pr2 = new Point(xr2, yr2);
Point pr3 = new Point(xr3, yr3);
Point pr4 = new Point(xr4, yr4);
LineSegment lr1 = new LineSegment(pr1, pr2);
LineSegment lr2 = new LineSegment(pr2, pr3);
LineSegment lr3 = new LineSegment(pr3, pr4);
LineSegment lr4 = new LineSegment(pr4, pr1);
//diamond
int xd1=sc.nextInt(), yd1=sc.nextInt(), xd2=sc.nextInt(),yd2=sc.nextInt();
int xd3=sc.nextInt(), yd3=sc.nextInt(), xd4=sc.nextInt(),yd4=sc.nextInt();
Point p1 = new Point(xd1, yd1);
Point p2 = new Point(xd2, yd2);
Point p3 = new Point(xd3, yd3);
Point p4 = new Point(xd4, yd4);
Point [] pt = new Point [5];
pt[0]=p1; pt[1]=p2; pt[2]=p3; pt[3]=p4; pt[4]=p1;
Polygon pg = new Polygon(pt);
if(pg.inside(pr1)||pg.inside(pr2)||pg.inside(pr3)||pg.inside(pr4)) {
System.out.println("YES");
return;
}
LineSegment ld1 = new LineSegment(p1, p2);
LineSegment ld2 = new LineSegment(p2, p3);
LineSegment ld3 = new LineSegment(p3, p4);
LineSegment ld4 = new LineSegment(p4, p1);
Rectangle rec = new Rectangle(new Point(Math.min(Math.min(xr3,xr4),Math.min(xr1,xr2)), Math.min(Math.min(yr3,yr4),Math.min(yr1,yr2))),
new Point(Math.max(Math.max(xr3,xr4),Math.max(xr1,xr2)), Math.max(Math.max(yr3,yr4),Math.max(yr1,yr2))) );
if(rec.contains(p1)||rec.contains(p2)||rec.contains(p3)||rec.contains(p4)) {
System.out.println("YES");
return;
}
if(ld1.intersect(lr1)||ld1.intersect(lr3)||ld1.intersect(lr3)||ld1.intersect(lr4)) {
System.out.println("YES");
return;
}
if(ld2.intersect(lr1)||ld2.intersect(lr3)||ld2.intersect(lr3)||ld2.intersect(lr4)) {
System.out.println("YES");
return;
}
if(ld3.intersect(lr1)||ld3.intersect(lr3)||ld3.intersect(lr3)||ld3.intersect(lr4)) {
System.out.println("YES");
return;
}
if(ld4.intersect(lr1)||ld4.intersect(lr3)||ld4.intersect(lr3)||ld4.intersect(lr4)) {
System.out.println("YES");
return;
}
System.out.println("NO");
}
public static class Polygon {
// Cases to handle: collinear points, polygons with n < 3
static final double EPS = 1e-9;
Point[] g; //first point = last point, counter-clockwise representation
Polygon(Point[] o) { g = o; }
double perimeter()
{
double sum = 0.0;
for(int i = 0; i < g.length - 1; ++i)
sum += g[i].dist(g[i+1]);
return sum;
}
double area() //clockwise/anti-clockwise check, for convex/concave polygons
{
double area = 0.0;
for(int i = 0; i < g.length - 1; ++i)
area += g[i].x * g[i+1].y - g[i].y * g[i+1].x;
return Math.abs(area) / 2.0; //negative value in case of clockwise
}
boolean inside(Point p) //for convex/concave polygons - winding number algorithm
{
double sum = 0.0;
for(int i = 0; i < g.length - 1; ++i)
{
double angle = Point.angle(g[i], p, g[i+1]);
if((Math.abs(angle) < EPS || Math.abs(angle - Math.PI) < EPS) && p.between(g[i], g[i+1]))
return true;
if(Point.ccw(p, g[i], g[i+1]))
sum += angle;
else
sum -= angle;
}
return Math.abs(2 * Math.PI - Math.abs(sum)) < EPS; //abs makes it work for clockwise
}
/*
* Another way if the polygon is convex
* 1. Triangulate the poylgon through p
* 2. Check if sum areas == poygon area
* 3. Handle empty polygon
*/
Point centroid() //center of mass
{
double cx = 0.0, cy = 0.0;
for(int i = 0; i < g.length - 1; i++)
{
double x1 = g[i].x, y1 = g[i].y;
double x2 = g[i+1].x, y2 = g[i+1].y;
double f = x1 * y2 - x2 * y1;
cx += (x1 + x2) * f;
cy += (y1 + y2) * f;
}
double area = area(); //remove abs
cx /= 6.0 * area;
cy /= 6.0 * area;
return new Point(cx, cy);
}
}
static class LineSegment {
Point p, q;
LineSegment(Point a, Point b) { p = a; q = b; }
boolean intersect(LineSegment ls)
{
Line l1 = new Line(p, q), l2 = new Line(ls.p, ls.q);
if(l1.parallel(l2))
{
if(l1.same(l2))
return p.between(ls.p, ls.q) || q.between(ls.p, ls.q) || ls.p.between(p, q) || ls.q.between(p, q);
return false;
}
Point c = l1.intersect(l2);
return c.between(p, q) && c.between(ls.p, ls.q);
}
}
static class Rectangle {
static final double EPS = 1e-9;
Point ll, ur;
Rectangle(Point a, Point b) { ll = a; ur = b; }
double area() { return (ur.x - ll.x) * (ur.y - ll.y); }
boolean contains(Point p)
{
return p.x <= ur.x + EPS && p.x + EPS >= ll.x && p.y <= ur.y + EPS && p.y + EPS >= ll.y;
}
Rectangle intersect(Rectangle r)
{
Point ll = new Point(Math.max(this.ll.x, r.ll.x), Math.max(this.ll.y, r.ll.y));
Point ur = new Point(Math.min(this.ur.x, r.ur.x), Math.min(this.ur.y, r.ur.y));
if(Math.abs(ur.x - ll.x) > EPS && Math.abs(ur.y - ll.y) > EPS && this.contains(ll) && this.contains(ur) && r.contains(ll) && r.contains(ur))
return new Rectangle(ll, ur);
return null;
}
}
static class Line {
static final double INF = 1e9, EPS = 1e-9;
double a, b, c;
Line(Point p, Point q)
{
if(Math.abs(p.x - q.x) < EPS) { a = 1; b = 0; c = -p.x; }
else
{
a = (p.y - q.y) / (q.x - p.x);
b = 1.0;
c = -(a * p.x + p.y);
}
}
Line(Point p, double m) { a = -m; b = 1; c = -(a * p.x + p.y); }
boolean parallel(Line l) { return Math.abs(a - l.a) < EPS && Math.abs(b - l.b) < EPS; }
boolean same(Line l) { return parallel(l) && Math.abs(c - l.c) < EPS; }
Point intersect(Line l)
{
if(parallel(l))
return null;
double x = (b * l.c - c * l.b) / (a * l.b - b * l.a);
double y;
if(Math.abs(b) < EPS)
y = -l.a * x - l.c;
else
y = -a * x - c;
return new Point(x, y);
}
Point closestPoint(Point p)
{
if(Math.abs(b) < EPS) return new Point(-c, p.y);
if(Math.abs(a) < EPS) return new Point(p.x, -c);
return intersect(new Line(p, 1 / a));
}
}
public static class Vector {
double x, y;
Vector(double a, double b) { x = a; y = b; }
Vector(Point a, Point b) { this(b.x - a.x, b.y - a.y); }
Vector scale(double s) { return new Vector(x * s, y * s); } //s is a non-negative value
double dot(Vector v) { return (x * v.x + y * v.y); }
double cross(Vector v) { return x * v.y - y * v.x; }
double norm2() { return x * x + y * y; }
Vector reverse() { return new Vector(-x, -y); }
Vector normalize()
{
double d = Math.sqrt(norm2());
return scale(1 / d);
}
}
static class Point implements Comparable<Point>{
static final double EPS = 1e-9;
double x, y;
Point(double a, double b) { x = a; y = b; }
public int compareTo(Point p)
{
if(Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1;
if(Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1;
return 0;
}
static double angle(Point a, Point o, Point b) // angle AOB
{
Vector oa = new Vector(o, a), ob = new Vector(o, b);
return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2()));
}
static boolean ccw(Point p, Point q, Point r)
{
return new Vector(p, q).cross(new Vector(p, r)) > 0;
}
public double dist(Point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); }
static double sq(double x) { return x * x; }
Point rotate(double angle)
{
double c = Math.cos(angle), s = Math.sin(angle);
return new Point(x * c - y * s, x * s + y * c);
}
// for integer points and rotation by 90 (counterclockwise) : swap x and y, negate x
boolean between(Point p, Point q)
{
return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x)
&& y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y);
}
//returns true if it is on the line defined by a and b
//returns true if it is on the ray whose start point is a and passes through b
// Another way: find closest point and calculate the distance between it and p
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public Scanner(String file) throws FileNotFoundException {
br = new BufferedReader(new FileReader(file));
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public long nextlong() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
long res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
constant
|
994_C. Two Squares
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class two {
public static void main(String[] args) throws IOException, FileNotFoundException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader in = new BufferedReader(new FileReader("two"));
HashSet<Integer> good = new HashSet<>();
int i=1;
for (; i<= (int)(1e9);) {
i <<= 1;
good.add(i);
}
for (i=3; i*i*2 <= (int)(1e9); i++) {
good.add(i*i*2);
}
int beg = 4;
for (i=3; beg + i*4 <= (int)(1e9); i+=2) {
good.add(beg + i*4);
beg += i*4;
}
int t = Integer.parseInt(in.readLine());
while (t-- > 0) {
int n = Integer.parseInt(in.readLine());
if (good.contains(n)) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter writer;
static String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static void banana() throws IOException {
int n = nextInt();
int[] a = new int[n];
int[] color = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
int c = 0;
while(true) {
int mn = 1000;
for (int i = 0; i < n; i++) {
if(color[i] == 0) {
mn = Math.min(mn, a[i]);
}
}
if (mn == 1000) {
break;
}
c++;
for (int i = 0; i < n; i++) {
if (color[i] == 0) {
if (a[i] % mn == 0) {
color[i] = c;
}
}
}
}
writer.println(c);
}
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
banana();
reader.close();
writer.close();
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class C {
int removeSq(int x) {
for (int i = 2; i * i <= x; i++) {
while (x % (i * i) == 0) {
x /= i * i;
}
}
return x;
}
void submit() {
int n = nextInt();
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
int x = removeSq(nextInt());
map.merge(x, 1, Integer::sum);
}
int[] a = new int[map.size()];
int ptr = 0;
for (Integer x : map.values()) {
a[ptr++] = x;
}
int ret = go(a);
for (int x : a) {
ret = (int)((long)ret * fact[x] % P);
}
out.println(ret);
}
int go(int[] a) {
int[] dp = new int[a[0]];
dp[a[0] - 1] = 1;
int places = a[0] + 1;
int toInsert = 0;
for (int x : a) {
toInsert += x;
}
toInsert -= a[0];
for (int i =1; i < a.length; i++) {
int here = a[i];
if (here == 0) {
continue;
}
int[] nxt = new int[dp.length + here];
for (int wasSame = 0; wasSame < dp.length; wasSame++) {
if (wasSame > toInsert) {
continue;
}
if (dp[wasSame] == 0) {
continue;
}
int wasDiff = places - wasSame;
for (int runsSame = 0; runsSame <= wasSame && runsSame <= here; runsSame++) {
for (int runsDiff = 0; runsDiff <= wasDiff && runsSame + runsDiff <= here; runsDiff++) {
if (runsSame + runsDiff == 0) {
continue;
}
int delta = (int) ((long) dp[wasSame]
* ways[wasSame][runsSame] % P * ways[wasDiff][runsDiff]
% P * ways[here - 1][runsSame + runsDiff - 1] % P);
if (delta == 0) {
continue;
}
int nxtIdx = (wasSame - runsSame) + (here - runsSame - runsDiff);
nxt[nxtIdx] += delta;
if (nxt[nxtIdx] >= P) {
nxt[nxtIdx] -= P;
}
}
}
}
dp = nxt;
places += here;
toInsert -= here;
}
// System.err.println(Arrays.toString(a) + " " + idx);
// System.err.println(Arrays.toString(dp));
return dp[0];
}
int[][] ways;
int[] fact;
static final int N = 350;
static final int P = 1_000_000_007;
void preCalc() {
ways = new int[N][];
for (int i = 0; i < N; i++) {
ways[i] = new int[i + 1];
ways[i][0] = ways[i][i] = 1;
for (int j = 1; j < i; j++) {
ways[i][j] = ways[i - 1][j] + ways[i - 1][j - 1];
if (ways[i][j] >= P) {
ways[i][j] -= P;
}
}
}
fact = new int[N];
fact[0] = 1;
for (int i = 1; i < N; i++) {
fact[i] = (int)((long)fact[i - 1] * i % P);
}
}
void stress() {
}
void test() {
}
C() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
preCalc();
submit();
//stress();
//test();
out.close();
}
static final Random rng = new Random();
static int rand(int l, int r) {
return l + rng.nextInt(r - l + 1);
}
public static void main(String[] args) throws IOException {
new C();
}
BufferedReader br;
PrintWriter out;
StringTokenizer st;
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
|
cubic
|
840_C. On the Bench
|
CODEFORCES
|
import java.util.*;
import java.math.*;
import java.io.*;
public class b2 {
public static void main(String[] args) throws IOException
{
input.init(System.in);
int n = input.nextInt(), x = input.nextInt(), y = input.nextInt(), c = input.nextInt();
long lo = 0, hi = 2*n;
while(hi > lo+1)
{
long mid = (hi+lo)/2;
long covered = go(n, x, y, mid);
if(covered < c)
lo = mid;
else hi = mid;
}
if(go(n, x, y, lo) < c) lo++;
System.out.println(lo);
}
public static long go(int n, int x, int y, long d)
{
long res = d*d + (d+1)*(d+1);
long maxLeft = d - x;
if(maxLeft >= 0) res -= (maxLeft+1)*(maxLeft+1);
long maxTop = d - y;
if(maxTop >= 0) res -= (maxTop+1)*(maxTop+1);
long maxRight = d - (n+1-x);
if(maxRight >= 0) res -= (maxRight+1)*(maxRight+1);
long maxBot = d - (n+1-y);
if(maxBot >= 0) res -= (maxBot+1)*(maxBot+1);
long maxTopLeft = d - (x+y);
if(maxTopLeft >= 0) res += (maxTopLeft+1)*(maxTopLeft+2)/2;
long maxTopRight = d - ((n+1-x)+y);
if(maxTopRight >= 0) res += (maxTopRight+1)*(maxTopRight+2)/2;
long maxBotLeft = d - (x+(n+1-y));
if(maxBotLeft >= 0) res += (maxBotLeft+1)*(maxBotLeft+2)/2;
long maxBotRight = d - ((n+1-x)+(n+1-y));
if(maxBotRight >= 0) res += (maxBotRight+1)*(maxBotRight+2)/2;
return res;
}
public static class input {
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() );
}
}
}
|
logn
|
256_B. Mr. Bender and Square
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class TaskA {
void Run() throws IOException {
int n=ReadInt();
int[] arr=new int[n];
for(int i=0;i<n;++i)
arr[i]=ReadInt();
Arrays.sort(arr);
boolean one=true;
for(int x : arr)
if(x!=1) {
one=false;
break;
}
if(one) {
for(int i=1;i<n;++i)
output.print("1 ");
output.print("2");
return;
}
int prev=1;
for(int x : arr)
if(x==prev) {
output.print(prev);
output.print(" ");
} else {
output.print(prev);
output.print(" ");
prev=x;
}
}
public static void main(String[] args) throws IOException {
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
Reader reader;
reader=oj ? new InputStreamReader(System.in) : new FileReader("input.txt");
input=new BufferedReader(reader);
Writer writer=new OutputStreamWriter(System.out);
writer=new BufferedWriter(writer);
output=new PrintWriter(writer);
new TaskA().Run();
output.close();
}
static int ReadInt() throws IOException {
return Integer.parseInt(ReadString());
}
static long ReadLong() throws IOException {
return Long.parseLong(ReadString());
}
static String ReadString() throws IOException {
while(tokenizer==null || !tokenizer.hasMoreTokens())
tokenizer=new StringTokenizer(input.readLine());
return tokenizer.nextToken();
}
static StringTokenizer tokenizer;
static BufferedReader input;
static PrintWriter output;
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader reader
= new BufferedReader(new InputStreamReader(System.in));
static StringBuilder out = new StringBuilder();
public static void main(String[] args){
solve();
return;
}
// the followings are methods to take care of inputs.
static int nextInt(){
return Integer.parseInt(nextLine());
}
static long nextLong(){
return Long.parseLong(nextLine());
}
static int[] nextIntArray(){
String[] inp = nextLine().split("\\s+");
int[] ary = new int[inp.length];
for (int i = 0; i < ary.length; i++){
ary[i] = Integer.parseInt(inp[i]);
}
return ary;
}
static int[] nextIntArrayFrom1(){
String[] inp = nextLine().split("\\s+");
int[] ary = new int[inp.length + 1];
for (int i = 0; i < inp.length; i++){
ary[i+1] = Integer.parseInt(inp[i]);
}
return ary;
}
static long[] nextLongArray(){
String[] inp = nextLine().split("\\s+");
long[] ary = new long[inp.length];
for (int i = 0; i < inp.length; i++){
ary[i] = Long.parseLong(inp[i]);
}
return ary;
}
static long[] nextLongArrayFrom1(){
String[] inp = nextLine().split("\\s+");
long[] ary = new long[inp.length + 1];
for (int i = 0; i < inp.length; i++){
ary[i+1] = Long.parseLong(inp[i]);
}
return ary;
}
static String nextLine(){
try {
return reader.readLine().trim();
} catch (Exception e){}
return null;
}
static void solve(){
String str = nextLine();
int max=0;
int index=0;
for(int i=0;i<str.length();i++){
for(int j=i+1;j<str.length();j++){
if(str.charAt(i)==str.charAt(j)){
int count=1;
while(true){
if(str.length()<=i+count || str.length()<=j+count || str.charAt(i+count)!=str.charAt(j+count) )
break;
count++;
}
if(max<count){
max=count;
index=i;
}
}
}
}
System.out.println(max);
return;
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
new Main().go();
}
PrintWriter out;
Reader in;
BufferedReader br;
Main() throws IOException {
try {
//br = new BufferedReader( new FileReader("input.txt") );
//in = new Reader("input.txt");
in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
}
catch (Exception e) {
//br = new BufferedReader( new InputStreamReader( System.in ) );
in = new Reader();
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
}
}
void go() throws Exception {
//int t = in.nextInt();
int t = 1;
while (t > 0) {
solve();
t--;
}
out.flush();
out.close();
}
int inf = 2000000000;
int mod = 1000000007;
double eps = 0.000000001;
int n;
int m;
ArrayList<Pair>[] g;
String s;
int[][] a;
void solve() throws IOException {
int n = in.nextInt();
int m = in.nextInt();
a = new int[n][m];
for (int i = 0; i < n; i++) {
String s = in.nextLine();
for (int j = 0; j < m; j++) {
a[i][j] = s.charAt(j);
}
}
int[][] f = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
f[i][j] = inf;
for (int i = 0; i < n; i++) {
int cnt = 0;
for (int j = 0; j < m; j++) {
if (a[i][j] == '*') {
f[i][j] = Math.min(f[i][j], cnt);
cnt++;
} else {
cnt = 0;
}
}
}
for (int i = 0; i < n; i++) {
int cnt = 0;
for (int j = m - 1; j >= 0; j--) {
if (a[i][j] == '*') {
f[i][j] = Math.min(f[i][j], cnt);
cnt++;
} else {
cnt = 0;
}
}
}
for (int j = 0; j < m; j++) {
int cnt = 0;
for (int i = 0; i < n; i++) {
if (a[i][j] == '*') {
f[i][j] = Math.min(f[i][j], cnt);
cnt++;
} else {
cnt = 0;
}
}
}
for (int j = 0; j < m; j++) {
int cnt = 0;
for (int i = n - 1; i >= 0; i--) {
if (a[i][j] == '*') {
f[i][j] = Math.min(f[i][j], cnt);
cnt++;
} else {
cnt = 0;
}
}
}
ArrayList<Item> ans = new ArrayList<>();
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if (a[i][j] == '*' && f[i][j] > 0)
ans.add(new Item(i + 1, j + 1, f[i][j]));
}
boolean[][] used = new boolean[n][m];
for (int i = 0; i < n; i++) {
int cnt = 0;
for (int j = 0; j < m; j++) {
if (a[i][j] == '*' && f[i][j] > 0) {
cnt = Math.max(cnt, f[i][j] + 1);
}
if (cnt > 0) used[i][j] = true;
cnt--;
}
cnt = 0;
for (int j = m - 1; j >= 0; j--) {
if (a[i][j] == '*' && f[i][j] > 0) {
cnt = Math.max(cnt, f[i][j] + 1);
}
if (cnt > 0) used[i][j] = true;
cnt--;
}
}
for (int j = 0; j < m; j++) {
int cnt = 0;
for (int i = 0; i < n; i++) {
if (a[i][j] == '*' && f[i][j] > 0) {
cnt = Math.max(cnt, f[i][j] + 1);
}
if (cnt > 0) used[i][j] = true;
cnt--;
}
cnt = 0;
for (int i = n - 1; i >= 0; i--) {
if (a[i][j] == '*' && f[i][j] > 0) {
cnt = Math.max(cnt, f[i][j] + 1);
}
if (cnt > 0) used[i][j] = true;
cnt--;
}
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (a[i][j] == '*' && !used[i][j]) {
out.println(-1);
return;
}
out.println(ans.size());
for (Item i : ans)
out.println(i.a + " " + i.b + " " + i.c);
}
class Pair implements Comparable<Pair>{
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair p) {
if (a != p.a)
return Integer.compare(a, p.a);
else
return Integer.compare(b, p.b);
}
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
static class InputReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public InputReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public InputReader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
}
|
quadratic
|
1015_E2. Stars Drawing (Hard Edition)
|
CODEFORCES
|
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public Main() {
super();
}
public static void main(String... args) {
Main main = new Main();
main.start();
}
public void start() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
double a[][] = new double[n][n];
for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i][j] = Double.parseDouble(in.next());
int nn = 1 << n;
double p[] = new double[nn];
Arrays.fill(p, -1.0);
p[nn - 1] = 1.0;
DecimalFormat f = new DecimalFormat();
f.applyPattern("0.000000");
for (int i = 0; i < n; i++) {
if (i != 0) System.out.print(" ");
System.out.print(f.format(this.probability(a, p, 1 << i)));
}
}
private double probability(double a[][], double p[], int i) {
if (p[i] >= 0.0) return p[i];
double ans = 0;
int count = Integer.bitCount(i);
int n = a.length;
for (int j = 0; j < n; j++) {
int jj = 1 << j;
if ((jj & i) == 0) {
double d = this.probability(a, p, jj | i);
double dPair = 2.0 / (double)((count + 1) * count);
double s = 0;
for (int l = 0; l < n; l++) {
int ll = 1 << l;
if ((ll & i) != 0) s += a[l][j];
}
ans += d * dPair * s;
}
}
p[i] = ans;
return p[i];
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
long a,b;
a = scn.nextLong();
b = scn.nextLong();
long diff = b -a , tot = 0;
int ind = 0;
while(true) {
long res = (long)Math.pow(2.0, ind);
if (res > b) break;
if (((a>>ind) != (b>>ind)) || diff >= res)
tot += res;
ind++;
}
System.out.println(tot);
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner(new InputStreamReader(System.in));
int n = sc.nextInt(),even = 0,odd = 0,evI = 0,OdI = 0;
for (int i = 0; i < n; i++) {
if(sc.nextInt()%2 == 1){
odd++;
OdI = i+1;
}else{
even++;
evI = i+1;
}
}
if(even < odd)
System.out.println(evI);
else
System.out.println(OdI);
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class TaskA {
BufferedReader br;
PrintWriter out;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return "-1";
}
stok = new StringTokenizer(s);
}
return stok.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());
}
char nextChar() throws IOException {
return (char) (br.read());
}
String nextLine() throws IOException {
return br.readLine();
}
void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
Arrays.sort(a);
a[n - 1] = a[n - 1] == 1 ? 2 : 1;
Arrays.sort(a);
for (int i = 0; i < n; i++) {
out.print(a[i]);
out.print(' ');
}
}
void run() throws IOException {
// br = new BufferedReader(new FileReader("taska.in"));
// out = new PrintWriter("taska.out");
// br = new BufferedReader(new FileReader("input.txt"));
// out = new PrintWriter("output.txt");
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
br.close();
out.close();
}
public static void main(String[] args) throws IOException {
// Locale.setDefault(Locale.US);
new TaskA().run();
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
int n=in.nextInt();
Vector<Integer> mas=new Vector<Integer>();
Vector<Integer> mas2=new Vector<Integer>();
int index=-1;
boolean res=false;
for(int i=0; i<n; i++){
mas.add(in.nextInt());
if(i!=0 && mas.get(i)<mas.get(i-1)){
index=i-1;
break;
}
}
if(index==-1) res=true;
else{
int min=mas.get(index+1);
int minIndex=index+1;
for(int i=index+2; i<n; i++){
mas.add(in.nextInt());
if(mas.get(i)<=min){
min=mas.get(i);
minIndex=i;
}
}
mas2.addAll(mas);
mas.set(minIndex, mas.get(index));
mas.set(index, min);
int o=mas.hashCode();
Collections.sort(mas);
int nw=mas.hashCode();
res=nw==o;
}
if(!res){
mas=mas2;
for(int i=n-1; i>=0; i--){
if(i!=n-1 && mas.get(i)>mas.get(i+1)){
index=i+1;
break;
}
}
if(index==-1) res=true;
else{
int max=mas.get(index-1);
int maxIndex=index-1;
for(int i=index-1; i>=0; i--){
if(mas.get(i)>=max){
max=mas.get(i);
maxIndex=i;
}
}
mas.set(maxIndex, mas.get(index));
mas.set(index, max);
int o=mas.hashCode();
Collections.sort(mas);
int nw=mas.hashCode();
res=res||nw==o;
}
}
if(res) out.println("YES");
else out.println("NO");
out.close();
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.BigInteger;
public class Main{
static InputReader sc;
static PrintWriter pw;
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
sc = new InputReader(inputStream);
pw = new PrintWriter(outputStream);
solve();
pw.close();
}
// static int L,R,top,bottom;
// static int cnt,edge;
// static long ans;
static int time;
// static boolean isIsland;
static BigInteger min(BigInteger a, BigInteger b){
if(a.compareTo(b)<0)
return a;
return b;
}
public static void solve(){
int t=1;
t=s(0);
u:while(t-->0){
int n=s(0);
int []arr=new int [n];
feedArr(arr);
Stack<Pair> stk=new Stack<>();
stk.push(new Pair("",1));
pln(1);
Pair pr;
for(int i=1;i<n;i++){
if(arr[i]==1){
pr=stk.peek();
stk.push(new Pair(pr.s+(pr.s.length()==0?"":".")+pr.i,1));
pln(stk.peek().s+"."+stk.peek().i);
}
else if(stk.peek().i==arr[i]-1){
pr=stk.pop();
pln(pr.s+(pr.s.length()==0?"":".")+arr[i]);
pr.i++;
stk.push(pr);
}
else{
stk.pop();
i--;
}
}
}
}
static long fact(long p){
long ans=1l;
for(long i=2;i<=p;i++)
ans*=i;
return ans;
}
static int find(int j, List<Integer> B, List<Integer> A, int i){
// System.out.println("Hi");
int l=j,r=B.size()-1,m;
while(l<=r){
m=(r-l)/2+l;
if(A.size()-i-1<=B.size()-m-1)
l=m+1;
else
r=m-1;
}
// System.out.println("Bye");
return r;
}
static int find2(List<Integer> B, int x){
int l=0,r=B.size()-1,m;
// System.out.println("Hi2");
// System.out.println(j);
while(l<=r){
m=(r-l)/2+l;
// System.out.println(m);
if(B.get(m)-x<=0)
l=m+1;
else
r=m-1;
}
// System.out.println("Bye2");
return r;
}
static long nPr(long n, long r){
long ans=1;
for(long i=1;i<=r;i++)
ans*=(n-i+1);
return ans;
}
static long nCr(long n, long r){
long ans=1;
for(long i=1;i<=r;i++){
ans*=(n-i+1);
ans/=i;
}
return ans;
}
static void update_DAG(int cur,int val, int []graph, int n)
{
if(val>maxx[cur])
{
int x=graph[cur];
if(x!=-1)
update_DAG(x,val+1,graph,n);
maxx[cur]=val;
update(cur,val,n);
}
}
static int []bit, maxx;
static void update(int i,int val, int n)
{
while(i<=n)
{
bit[i]=Math.max(bit[i],val);
i=i+(i&(-i));
}
}
static int query(int i)
{
int ret=0;
while(i>0)
{
ret=Math.max(ret,bit[i]);
i=i-(i&(-i));
}
return ret;
}
public static int [][]dir=new int [][]{{1,0},{0,1},{-1,0},{0,-1}};
public static int find(List<Integer> list, int x){
int l=0,r=list.size()-1,m;
while(l<=r){
m=(r-l)/2+l;
if(list.get(m)<=x)
l=m+1;
else
r=m-1;
}
return r;
}
static class Node{
int val;
long cost;
Node next;
Node(int v,long c){
val=v;
next=null;
cost=c;
}
}
public static long sum(long n){
long val=0l;
while(n>0){
val+=n%10;
n/=10;
}
return val;
}
// static class Node{
// int left,right;
// Node prev,next;
// Node(int i, int v){
// left=i;
// right=v;
// prev=next=null;
// }
// void remove(){
// this.prev.next=this.next;
// this.next.prev=this.prev;
// }
// void insert(Node node){
// node.next=this;
// node.prev=this.prev;
// node.prev.next=node;
// this.prev=node;
// }
// }
public static int findDiameter(int r, List<List<Integer>>list){
return findFarthest(findFarthest(r,list)[0],list)[1];
}
public static int[] findFarthest(int u, List<List<Integer>>list){
int n=list.size();
boolean []vis=new boolean[n+1];
Queue<Integer>q=new LinkedList<>();
q.offer(u);
vis[u]=true;
int s,pr,cnt=0;
int []ar=new int[]{u,0};
while(q.size()>0){
s=q.size();
while(s-->0){
pr=q.poll();
if(ar[1]<cnt){
ar[1]=cnt;
ar[0]=pr;
}
for(int i:list.get(pr)){
if(!vis[i]){
vis[i]=true;
q.offer(i);
}
}
}
cnt++;
}
return ar;
}
public static long atMostK(char []chrr, int k){
if(k<0)
return 0;
int l=0,cnt=0;
long ans=0l;
for(int i=0;i<chrr.length;i++){
if(chrr[i]=='1')
cnt++;
while(cnt>k){
if(chrr[l++]=='1')
cnt--;
}
ans+=(long)(i-l)+1l;
}
return ans;
}
public static int ask(int l, int r){
System.out.println("? "+l+" "+r);
System.out.flush();
return sc.nextInt();
}
public static void sort(int []arr){
ArrayList<Integer> list=new ArrayList<>();
for(int i=0;i<arr.length;i++)
list.add(arr[i]);
Collections.sort(list);
for(int i=0;i<arr.length;i++)
arr[i]=list.get(i);
}
public static void sort(long []arr){
ArrayList<Long> list=new ArrayList<>();
for(int i=0;i<arr.length;i++)
list.add(arr[i]);
Collections.sort(list);
for(int i=0;i<arr.length;i++)
arr[i]=list.get(i);
}
public static void swap(char []chrr, int i, int j){
char temp=chrr[i];
chrr[i]=chrr[j];
chrr[j]=temp;
}
public static int countSetBits(long n){
int a=0;
while(n>0){
a+=(n&1);
n>>=1;
}
return a;
}
static class Pair{
String s;
int i;
Pair(String S, int I){
s=S;
i=I;
}
//*
}
/*/
public int compareTo(Pair p){
return (b-p.b);
}
public int hashCode(){
int hashcode = (a+" "+b).hashCode();
return hashcode;
}
public boolean equals(Object obj){
if (obj instanceof Pair) {
Pair p = (Pair) obj;
return (p.a==this.a && p.b == this.b);
}
return false;
}
}
//*/
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return a>b?gcd(b, a % b):gcd(a, b % a);
}
static long fast_pow(long base,long n,long M){
if(n==0)
return 1;
if(n==1)
return base;
long halfn=fast_pow(base,n/2,M);
if(n%2==0)
return ( halfn * halfn ) % M;
else
return ( ( ( halfn * halfn ) % M ) * base ) % M;
}
static long modInverse(long n,long M){
return fast_pow(n,M-2,M);
}
public static int s(int n){
return sc.nextInt();
}
public static long s(long n){
return sc.nextLong();
}
public static String s(String n){
return sc.next();
}
public static double s(double n){
return sc.nextDouble();
}
public static void p(int n){
pw.print(n);
}
public static void p(long n){
pw.print(n);
}
public static void p(String n){
pw.print(n);
}
public static void p(double n){
pw.print(n);
}
public static void pln(int n){
pw.println(n);
}
public static void pln(long n){
pw.println(n);
}
public static void pln(String n){
pw.println(n);
}
public static void pln(double n){
pw.println(n);
}
public static void feedArr(long []arr){
for(int i=0;i<arr.length;i++)
arr[i]=sc.nextLong();
}
public static void feedArr(double []arr){
for(int i=0;i<arr.length;i++)
arr[i]=sc.nextDouble();
}
public static void feedArr(int []arr){
for(int i=0;i<arr.length;i++)
arr[i]=sc.nextInt();
}
public static void feedArr(String []arr){
for(int i=0;i<arr.length;i++)
arr[i]=sc.next();
}
public static String printArr(int []arr){
StringBuilder sbr=new StringBuilder();
for(int i:arr)
sbr.append(i+" ");
return sbr.toString();
}
public static String printArr(long []arr){
StringBuilder sbr=new StringBuilder();
for(long i:arr)
sbr.append(i+" ");
return sbr.toString();
}
public static String printArr(String []arr){
StringBuilder sbr=new StringBuilder();
for(String i:arr)
sbr.append(i+" ");
return sbr.toString();
}
public static String printArr(double []arr){
StringBuilder sbr=new StringBuilder();
for(double i:arr)
sbr.append(i+" ");
return sbr.toString();
}
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());
}
}
}
class AncestorQuerier {
int [][]dp;
int N=200001;
int M=22;
int max;
public void preCompute(int []par){
for(int i=0;i<N;i++){
if(i>=2&&i<par.length)
dp[i][0]=par[i];
else
dp[i][0]=-1;
}
for(int j=1;j<M;j++){
for(int i=0;i<N;i++){
if(dp[i][j-1]!=-1)
dp[i][j]=dp[dp[i][j-1]][j-1];
}
}
}
public int getAncestor(int val, int k) {
if(k<0||val>max)
return -1;
if(k==0)
return val;
int t=(1<<(M-1));
for(int i=M-1;i>=0&&val!=-1;i--,t>>=1){
if(t<=k){
val=dp[val][i];
k-=t;
}
}
return val;
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class a {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
int len = s.length();
for(int i=len-1; i>=1; --i) {
for(int j=0; j<=len - i; ++j) {
String ss = s.substring(j, j+i);
if(s.substring(j+1).indexOf(ss)!=-1) {
System.out.println(ss.length());
return;
}
}
}
System.out.println(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
//package codeforces.cf156;
import java.io.*;
import java.util.Arrays;
public class ProblemB {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));
long[] readInts() throws IOException {
String[] strings = reader.readLine().split(" ");
long[] ints = new long[strings.length];
for(int i = 0; i < ints.length; i++) {
ints[i] = Long.parseLong(strings[i]);
}
return ints;
}
long foo(long a) {
return a > 0 ? a * a : 0;
}
long boo(long a) {
return a <= 0 ? 0 : a * (a + 1) / 2;
}
void solve() throws IOException {
long[] tt = readInts();
long n = tt[0];
long x = tt[1];
long y = tt[2];
long c = tt[3];
long lo = -1, hi = 2 * 1000 * 1000 * 1000 + 2;
// hi = 5;
while(hi - lo > 1) {
long m = (lo + hi) / 2;
long s = 2 * m * m + 2 * m + 1;
s -= foo(m - x + 1) + foo(m - y + 1) + foo(x + m - n) + foo(y + m - n);
s += boo(m + 1 - (n + 1 + n + 1 - x - y)) + boo(m + 1 - (n + 1 - x + y)) + boo(m + 1 - (n + 1 - y + x))
+ boo(m + 1 - (x + y));
if(s < c) lo = m;
else hi = m;
}
writer.println(hi);
writer.flush();
}
public static void main(String[] args) throws IOException{
new ProblemB().solve();
}
}
|
logn
|
256_B. Mr. Bender and Square
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class NewYearAndCurling {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer t = new StringTokenizer(in.readLine());
int N = Integer.parseInt(t.nextToken());
int R = Integer.parseInt(t.nextToken());
int[] x = new int[N];
t = new StringTokenizer(in.readLine());
for(int i = 0; i < N; ++i)
x[i] = Integer.parseInt(t.nextToken());
double[] y = new double[N];
for(int i = 0; i < N; ++i) {
double max = R;
for(int j = 0; j < i; ++j ) {
int xDiff = Math.abs(x[i] - x[j]);
if(xDiff <= 2 * R)
max = Math.max(max, y[j] + Math.sqrt(4*R*R - xDiff*xDiff));
}
y[i] = max;
}
out.print(y[0]);
for(int i = 1; i < N; ++i)
out.print(" " + y[i]);
out.println();
in.close();
out.close();
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
static StringBuilder data = new StringBuilder();
final static FastReader in = new FastReader();
public static void main(String[] args) {
int n = in.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Arrays.sort(a);
int answ = 0;
for (int i = 0; i < n; i++) {
if (a[i] != 0) {
for (int j = i + 1; j < n; j++) {
if (a[j] % a[i] == 0) {
a[j] = 0;
}
}
answ++;
a[i]=0;
}
}
System.out.println(answ);
}
static void fileOut(String s) {
File out = new File("output.txt");
try {
FileWriter fw = new FileWriter(out);
fw.write(s);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
public FastReader(String path) {
try {
br = new BufferedReader(new
InputStreamReader(new FileInputStream(path)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
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());
}
float nextFloat() {
return Float.parseFloat(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class ElevatorOrStairs {
private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private static final OutputStreamWriter writer = new OutputStreamWriter(System.out);
public static void main(String...strings) throws Exception {
String[] specs = reader.readLine().split(" ");
int x = Integer.parseInt(specs[0]);
int y = Integer.parseInt(specs[1]);
int z = Integer.parseInt(specs[2]);
int t1 = Integer.parseInt(specs[3]);
int t2 = Integer.parseInt(specs[4]);
int t3 = Integer.parseInt(specs[5]);
reader.close();
String ans = solve(x, y, z, t1, t2, t3);
writer.append(ans);
writer.flush();
writer.close();
}
private static String solve(int x, int y, int z, int t1, int t2, int t3) {
int time_using_stairs = Math.abs(x - y) * t1;
int elevator_time_between_floor = Math.abs(x - z) * t2;
int elevator_from_z_to_x = elevator_time_between_floor + 2*t3;
int time_using_elevator = elevator_from_z_to_x + (Math.abs(x - y) * t2) + t3;
if(time_using_elevator <= time_using_stairs) {
return "YES";
}
return "NO";
}
}
|
constant
|
1054_A. Elevator or Stairs?
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class ayyyyyy
{
public static void main(String[] args) { new ayyyyyy(); }
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int t, n;
int[] a;
ayyyyyy()
{
t = in.nextInt();
while (t --> 0)
{
a = new int[n = in.nextInt()];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
shuffle(a);
Arrays.sort(a);
out.println(Math.min(n-2, a[n-2]-1));
}
out.close();
}
void shuffle(int[] x)
{
for (int i = 0; i < n; i++)
{
int swp = (int)(n*Math.random());
int tmp = x[swp];
x[swp] = x[i];
x[i] = tmp;
}
}
}
|
nlogn
|
1197_A. DIY Wooden Ladder
|
CODEFORCES
|
import java.util.*;
public class r220a {
public static void main(String args[]) {
Scanner in =new Scanner(System.in);
int N = in.nextInt();
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> sort = new ArrayList<Integer>();
for(int i = 0; i < N; i++) {
int k = in.nextInt();
list.add(k);
sort.add(k);
}
Collections.sort(sort);
int count = 0;
for(int i = 0; i < N; i++) {
if(sort.get(i).intValue() != list.get(i).intValue())
count++;
}
if(count != 2 && count != 0)
System.out.println("NO");
else
System.out.println("YES");
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
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.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Map;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prakharjain
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
String[] a = new String[n];
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
a[i] = in.next();
map.merge(a[i], 1, Integer::sum);
}
String[] b = new String[n];
for (int i = 0; i < n; i++) {
b[i] = in.next();
if (map.containsKey(b[i])) {
map.put(b[i], map.get(b[i]) - 1);
if (map.get(b[i]) <= 0)
map.remove(b[i]);
}
}
int ans = 0;
for (String s : map.keySet()) {
ans += map.get(s);
}
out.println(ans);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public String next() {
return nextString();
}
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 println(int i) {
writer.println(i);
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class BetaRound15_A implements Runnable {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws IOException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
@Override
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
public static void main(String[] args) {
new Thread(new BetaRound15_A()).start();
}
class House implements Comparable<House> {
int left, right;
House(int left, int right) {
this.left = left;
this.right = right;
}
@Override
public int compareTo(House h) {
return this.left - h.left;
}
}
int getAns(House h1, House h2, int t) {
int d = h2.left - h1.right;
if (d < t) return 0;
if (d == t) return 1;
return 2;
}
void solve() throws IOException {
int n = readInt();
int t = readInt() * 2;
House[] h = new House[n];
for (int i = 0; i < n; i++) {
int c = readInt() * 2;
int b = readInt();
h[i] = new House(c - b, c + b);
}
Arrays.sort(h);
int ans = 2;
for (int i = 1; i < n; i++) {
ans += getAns(h[i - 1], h[i], t);
}
out.print(ans);
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.util.Scanner;
public class FUck {
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int k=scan.nextInt();
String t=scan.next();
int mx=0;
for(int i=1;i<n;i++)
{
int gd=1;
for(int j=0;j<i;j++)
{
if(t.charAt(j)!=t.charAt((n-i)+j))
{
gd=0;
// i think i can break here
}
}
if(gd==1){
mx=i;
}
}
System.out.print(t);
for(int i=2;i<=k;i++)
{
for(int j=mx;j<n;j++)
{
System.out.print(t.charAt(j));
}
}
}
}
|
quadratic
|
1029_A. Many Equal Substrings
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class A {
static Scanner scan = new Scanner (System.in);
static PrintStream out = System.out;
static void go (int n) {
if (n == 0) {
System.out.println (0 + " " + 0 + " " + 0);
return;
}
int a = 0, b = 1;
int c = a + b;
while (n > c) {
a = b;
b = c;
c = a + b;
}
System.out.println (0 + " " + a + " " + b);
}
public static void main (String[] args) {
int n = scan.nextInt();
go (n);
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class c {
static boolean used[][];
static int n;
static int m;
static int a[][];
public static void main(String args[])throws Exception{
Scanner in =new Scanner(new File("input.txt"));//System.in);//
PrintWriter out=new PrintWriter(new File("output.txt"));//System.out);//
n = in.nextInt();
m = in.nextInt();
int k = in.nextInt();
//a=new int[n+1][m+1];
/*for (int i = 1; i<=n; i++)
for (int j = 1; j<=m; j++)
a[i][j] = 40001;
*/
int x[]=new int[k];
int y[]=new int[k];
for (int i = 0; i<k; i++){
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int max = 0;
int xx = 1; int yy= 1;
for (int i = 1; i<=n; i++)
for (int j = 1; j<=m; j++){
int count = Integer.MAX_VALUE;
for (int l =0; l<k; l++)
count = Math.min(Math.abs(i - x[l]) + Math.abs(j - y[l]), count);
if (max < count){
max = count;
xx = i; yy = j;
}
}
out.println(xx + " " + yy);
out.close();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class A25 {
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine().trim());
String[] toks = in.readLine().trim().split("[ ]+");
int counter = 0;
boolean even = true;
int e = -1, o = -1;
int ec = 0, oc = 0;
for (int i = 0; i < toks.length; i++) {
int x = Integer.parseInt(toks[i]);
if (x % 2 == 0) {
ec ++;
if (e == -1) {
e = i+1;
}
}
else {
oc ++;
if (o == -1) {
o = i+1;
}
}
}
if (ec == 1) {
System.out.println(e);
}
else if (oc == 1) {
System.out.println(o);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new A25().run();
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
/**
* author: derrick20
* created: 11/11/20 1:45 PM
*/
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class OnTheBenchAlt {
public static void main(String[] args) {
setupCombo(301);
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
long[] a = new long[N];
HashMap<Long, Integer> clusters = new HashMap<>();
for (int i = 0; i < N; i++) {
a[i] = removeSquares(sc.nextLong());
clusters.merge(a[i], 1, Integer::sum);
}
int G = clusters.size();
int[] groups = new int[G + 1];
int ptr = 1;
for (int amt : clusters.values()) {
groups[ptr++] = amt;
}
long[][] dp = new long[G + 1][N + 1];
// dp[g][bad] = ways to interleave first g groups for a given # of bad pairs
dp[0][0] = 1;
// dp[0][k] = 0, k != 0
int total = 0;
/*
intuition for runtime analysis:
Say there were k groups, each size n / k
The outer loop is k, 2nd loop is n worst case,
and the inner 2 are bounded by n / k (amt per group)
k * n * (n / k) * (n / k) = n^3 / k, which works despite 4 loops!!
Seems hard to convert into pull-dp since prevBad has a more direct
meaning in the arrangements, so using that as our variable makes more sense
*/
for (int prefix = 1; prefix <= G; prefix++) {
int amt = groups[prefix];
// key bugs here and there: USE THE CORRECT BOUNDS
for (int prevBad = 0; prevBad <= max(0, total - 1); prevBad++) {
for (int fixed = 0; fixed <= min(prevBad, amt); fixed++) {
for (int slots = max(1, fixed); slots <= min(amt, total + 1); slots++) {
int introduced = amt - slots;
long ways = mult(
choose[prevBad][fixed],
choose[total + 1 - prevBad][slots - fixed],
choose[amt - 1][slots - 1],
fact[amt],
dp[prefix - 1][prevBad] // key bug: NEED TO RELATE PREVIOUS DP
);
int currBad = prevBad + introduced - fixed;
dp[prefix][currBad] = (dp[prefix][currBad] + ways) % mod;
}
}
}
total += amt;
// System.out.println(Arrays.toString(dp[prefix]));
}
out.println(dp[G][0]);
out.close();
}
static long mod = (long) 1e9 + 7;
static long[][] choose;
static long[] fact;
static long removeSquares(long x) {
long curr = x;
for (long v = 2; v * v <= x && curr > 1; v++) {
int cnt = 0;
while (curr % v == 0) {
curr /= v;
cnt ^= 1;
}
if (cnt == 1)
curr *= v;
}
return curr;
}
static long choose(int n, int k) {
return k < 0 || k > n ? 0 : choose[n][k];
}
static long mult(long... multiplicands) {
long ans = 1;
for (long v : multiplicands) {
ans = (ans * v) % mod;
}
return ans;
}
static void setupCombo(int MAX) {
choose = new long[MAX + 1][MAX + 1];
fact = new long[MAX + 1];
choose[0][0] = 1;
fact[0] = 1;
for (int i = 1; i <= MAX; i++) {
fact[i] = (long) i * fact[i - 1] % mod;
choose[i][0] = 1;
for (int j = 1; j < i; j++) {
choose[i][j] = (choose[i - 1][j - 1] + choose[i - 1][j]) % mod;
}
choose[i][i] = 1;
}
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static void ASSERT(boolean assertion, String message) {
if (!assertion) throw new AssertionError(message);
}
static void ASSERT(boolean assertion) {
if (!assertion) throw new AssertionError();
}
}
|
cubic
|
840_C. On the Bench
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Task15a {
public static class House implements Comparable<House>{
int x, s;
public House(int x, int s) {
super();
this.x = x;
this.s = s;
}
public int compareTo(House o) {
return x - o.x;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int t = sc.nextInt() * 2;
House[] hs = new House[n];
for (int i = 0; i < n; i++){
hs[i] = new House(sc.nextInt()*2, sc.nextInt());
}
Arrays.sort(hs);
int res = 2;
for (int i = 0; i < n - 1; i++) {
int curr = hs[i+1].x - hs[i].x - hs[i+1].s - hs[i].s;
if (curr > t) res += 2;
if (curr == t) res += 1;
}
System.out.println(res);
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
public class Main implements Runnable {
void randomShuffle(int[] arr) {
Random rnd = new Random();
for (int i = arr.length - 1; i >= 0; i--) {
int pos = rnd.nextInt(i + 1);
int temp = arr[pos];
arr[pos] = arr[i];
arr[i] = temp;
}
}
void solve() throws Exception {
int n = sc.nextInt();
int[] a = new int[n];
int[] ac = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ac[i] = sc.nextInt();
}
randomShuffle(ac);
Arrays.sort(ac);
int diff = 0;
for (int i = 0; i < n; i++) {
if (a[i] != ac[i]) {
diff++;
}
}
if (diff <= 2) {
out.println("YES");
} else {
out.println("NO");
}
}
BufferedReader in;
PrintWriter out;
FastScanner sc;
static Throwable uncaught;
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
solve();
} catch (Throwable t) {
Main.uncaught = t;
} finally {
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread t = new Thread(null, new Main(), "", 128 * 1024 * 1024);
t.start();
t.join();
if (uncaught != null) {
throw uncaught;
}
}
}
class FastScanner {
BufferedReader reader;
StringTokenizer strTok;
public FastScanner(BufferedReader reader) {
this.reader = reader;
}
public String nextToken() throws IOException {
while (strTok == null || !strTok.hasMoreTokens()) {
strTok = new StringTokenizer(reader.readLine());
}
return strTok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.StringTokenizer;
import java.util.Scanner;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Wolfgang Beyer
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
int found = 0;
int queryCount = 0;
int[] result = new int[8];
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
//int n = 100;
//int n = 65536;
int left = 1;
int right = n + 1;
while (left + 1 < right) {
int middle = (left + right) / 2;
int res = query(middle, 1, n, n);
if (res == 2) left = middle;
else if (res == 1) {
//System.out.println("Searching single: ");
findSingle(middle, 1, n, n);
found++;
break;
} else {
right = middle;
}
}
int top = 1;
int bottom = n + 1;
while (top + 1 < bottom) {
int middle = (top + bottom) / 2;
int res = query(1, middle, n, n);
if (res == 2) top = middle;
else if (res == 1) {
if ((found == 0) || (!containsRect(1, middle, n, n, result[0], result[1], result[2], result[3]))) {
//System.out.println("Searching single: ");
findSingle(1, middle, n, n);
found++;
}
break;
} else {
bottom = middle;
}
}
if (found < 2) {
//System.out.println("Dia 3: ");
left = 0;
right = n;
while (left + 1 < right) {
int middle = (left + right) / 2;
int res = query(1, 1, middle, n);
if (res == 2) right = middle;
else if (res == 1) {
if ((found == 0) || (!containsRect(1, 1, middle, n, result[0], result[1], result[2], result[3]))) {
//System.out.println("Searching single: ");
findSingle(1, 1, middle, n);
found++;
}
break;
} else {
left = middle;
}
}
}
if (found < 2) {
//System.out.println("Dia 4:");
top = 0;
bottom = n;
while (top + 1 < bottom) {
int middle = (top + bottom) / 2;
int res = query(1, 1, n, middle);
if (res == 2) bottom = middle;
else if (res == 1) {
if ((found == 0) || (!containsRect(1, 1, n, middle, result[0], result[1], result[2], result[3]))) {
//System.out.println("Searching single: ");
findSingle(1, 1, n, middle);
found++;
}
break;
} else {
top = middle;
}
}
}
System.out.print("! ");
for (int i = 0; i < 8; i++) System.out.print(result[i] + " ");
//System.out.println("\n" + queryCount + " queries used");
}
public boolean containsRect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
if ((x1 <= x3) && (y1 <= y3) && (x2 >= x4) && (y2 >= y4)) return true;
return false;
}
public void findSingle(int x1, int y1, int x2, int y2) {
x1 = findTopX(x1, y1, x2, y2);
y1 = findTopY(x1, y1, x2, y2);
x2 = findBottomX(x1, y1, x2, y2);
y2 = findBottomY(x1, y1, x2, y2);
//System.out.println("x1: " + x1 + ", y1: " + y1 + ", x2: " + x2 + ", y2: " + y2);
result[0 + 4 * found] = x1;
result[1 + 4 * found] = y1;
result[2 + 4 * found] = x2;
result[3 + 4 * found] = y2;
}
public int findTopX(int x1, int y1, int x2, int y2) {
int left = x1;
int right = x2;
while (left + 1 < right) {
int mid = (left + right) / 2;
if (query(mid, y1, x2, y2) == 1) {
left = mid;
} else {
right = mid;
}
}
while (query(right, y1, x2, y2) == 0) right--;
return right;
}
public int findTopY(int x1, int y1, int x2, int y2) {
int left = y1;
int right = y2;
while (left + 1 < right) {
int mid = (left + right) / 2;
if (query(x1, mid, x2, y2) == 1) {
left = mid;
} else {
right = mid;
}
}
while (query(x1, right, x2, y2) == 0) right--;
return right;
}
public int findBottomX(int x1, int y1, int x2, int y2) {
int left = x1;
int right = x2;
while (left + 1 < right) {
int mid = (left + right) / 2;
if (query(x1, y1, mid, y2) == 1) {
right = mid;
} else {
left = mid;
}
}
while (query(x1, y1, left, y2) == 0) left++;
return left;
}
public int findBottomY(int x1, int y1, int x2, int y2) {
int left = y1;
int right = y2;
while (left + 1 < right) {
int mid = (left + right) / 2;
if (query(x1, y1, x2, mid) == 1) {
right = mid;
} else {
left = mid;
}
}
while (query(x1, y1, x2, left) == 0) left++;
return left;
}
public int query(int x1, int y1, int x2, int y2) {
queryCount++;
System.out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
System.out.flush();
Scanner sc = new Scanner(System.in);
return sc.nextInt();
/*int ret = 0;
//if(x1 <= 17 && 57 <= x2 && y1 <= 80 && 80 <= y2) ++ret;
//if(x1 <= 25 && 88 <= x2 && y1 <= 51 && 61 <= y2) ++ret;
if(x1 <= 10 && 10 <= x2 && y1 <= 11 && 11 <= y2) ++ret;
//if(x1 <= 11 && 11 <= x2 && y1 <= 10 && 10 <= y2) ++ret;
if(x1 <= 10 && 10 <= x2 && y1 <= 15 && 15 <= y2) ++ret;
//System.out.println(x1 + ", " + y1 + ", " + x2 + ", " + y2 + ": " + ret);
return ret;*/
}
}
static class InputReader {
private static BufferedReader in;
private static StringTokenizer tok;
public InputReader(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
try {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
} catch (IOException ex) {
System.err.println("An IOException was caught :" + ex.getMessage());
}
return tok.nextToken();
}
}
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String args[] ) {
FastReader sc = new FastReader();
int n = sc.nextInt();
int m = sc.nextInt();
int[] arr = new int[105];
for(int i=0;i<m;i++){
int a = sc.nextInt();
arr[a]++;
}
for(int i=1;i<=1000;i++){
int sum=0;
for(int a:arr){
if(a!=0){
sum+=(a/i);
}
}
if(sum<n){
System.out.println(i-1);
return;
}
}
}
}
|
quadratic
|
1011_B. Planning The Expedition
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Es1
{
static IO io = new IO();
public static void main(String[] args)
{
int n = io.getInt();
int[] a = new int[n];
for(int i=0; i<n; i++)
a[i] = io.getInt();
Arrays.sort(a);
int[] color = new int[n];
int num = 1;
for(int i=0; i<n; i++){
if(color[i]==0){
for(int j=i+1; j<n; j++){
if(a[j]%a[i]==0)
color[j] = num;
}
num++;
}
}
io.println(num-1);
io.close();
}
}
class IO extends PrintWriter {
public IO() {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(System.in));
}
public IO(String fileName) {
super(new BufferedOutputStream(System.out));
try{
r = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
this.println("File Not Found");
}
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int getInt() {
return Integer.parseInt(nextToken());
}
public double getDouble() {
return Double.parseDouble(nextToken());
}
public long getLong() {
return Long.parseLong(nextToken());
}
public String getWord() {
return nextToken();
}
public String getLine(){
try{
st = null;
return r.readLine();
}
catch(IOException ex){}
return null;
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) { }
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.*;
public class B
{
static long sumN(long n)
{
return n * (n + 1) / 2;
}
static int binSearchPuts(int n, int k)
{
int L = 1;
int U = n;
int M = (L + U) / 2;
while(L <= U)
{
long left = sumN(M) - (n - M);
if(left < k)
{
L = M + 1;
}
else if(left > k)
{
U = M;
}
else
{
break;
}
M = (L + U) / 2;
}
return M;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int k = input.nextInt();
long ate = n - binSearchPuts(n, k);
System.out.println(ate);
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Main implements Runnable
{
boolean multiiple = false;
void solve() throws Exception
{
int n = sc.nextInt();
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(sc.nextInt());
Collections.sort(list);
int ans = 0;
while (!list.isEmpty())
{
ans++;
int next = list.get(0);
for (int i = list.size() - 1; i >= 1; i--)
{
if (list.get(i) % next == 0)
list.remove(i);
}
list.remove(0);
}
System.out.println(ans);
}
@Override
public void run()
{
try
{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
if (multiiple)
{
int q = sc.nextInt();
for (int i = 0; i < q; i++)
solve();
}
else
solve();
}
catch (Throwable uncaught)
{
Main.uncaught = uncaught;
}
finally
{
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread thread = new Thread(null, new Main(), "", (1 << 26));
thread.start();
thread.join();
if (Main.uncaught != null) {
throw Main.uncaught;
}
}
static Throwable uncaught;
BufferedReader in;
FastScanner sc;
PrintWriter out;
}
class FastScanner
{
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in)
{
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class ayyyyyy
{
public static void main(String[] args) { new ayyyyyy(); }
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int t, n;
int[] a;
ayyyyyy()
{
t = in.nextInt();
while (t --> 0)
{
a = new int[n = in.nextInt()];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
shuffle(a);
Arrays.sort(a);
out.println(Math.min(n-2, a[n-2]-1));
}
out.close();
}
void shuffle(int[] x)
{
for (int i = 0; i < n; i++)
{
int swp = (int)(n*Math.random());
int tmp = x[swp];
x[swp] = x[i];
x[i] = tmp;
}
}
}
|
nlogn
|
1197_A. DIY Wooden Ladder
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class E implements Runnable {
public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();}
HashMap<Integer, Integer> valToNode, nodeToVal, whichBox;
int N, ptsTo[], cycleMask[], dfsStack[], tempList[];
ArrayDeque<Integer> stack = new ArrayDeque<>();
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
valToNode = new HashMap<>();
nodeToVal = new HashMap<>();
whichBox = new HashMap<>();
int K = fs.nextInt();
int[][] vals = new int[K][], valToNode2 = new int[K][];
long[] sums = new long[K];
long total = 0;
for(int i = 0; i < K; i++) {
int size = fs.nextInt();
vals[i] = new int[size];
valToNode2[i] = new int[size];
for(int j = 0; j < size; j++) {
vals[i][j] = fs.nextInt();
sums[i] += vals[i][j];
valToNode2[i][j] = valToNode.size();
valToNode.put(vals[i][j], valToNode.size());
nodeToVal.put(valToNode.size()-1, vals[i][j]);
whichBox.put(vals[i][j], i);
}
total += sums[i];
}
if(total % K != 0) {
System.out.println("No");
return;
}
long perGroup = total/K;
N = valToNode.size();
ptsTo = new int[N];
for(int i = 0; i < K; i++) {
for(int j = 0; j < vals[i].length; j++) {
long newSum = perGroup - (sums[i]-vals[i][j]);
if(newSum > (int)1e9 || newSum < (int)-1e9) continue;
if(valToNode.containsKey((int)newSum)) {
ptsTo[valToNode.get(vals[i][j])] = valToNode.get((int)newSum);
}
else ptsTo[valToNode.get(vals[i][j])] = -1;
}
}
tempList = new int[N];
dfsStack = new int[N];
cycleMask = new int[N];
for(int i = 0; i < K; i++) {
for(int j = 0; j < vals[i].length; j++) {
int node = valToNode.get(vals[i][j]);
if(dfsStack[node] == 0) dfs(node);
}
}
int[] goodMask = new int[1<<K];
Arrays.fill(goodMask, -1); goodMask[0] = 0;
for(int mask = 1; mask < goodMask.length; mask++) {
int idx = Integer.numberOfTrailingZeros(Integer.lowestOneBit(mask));
for(int i = 0; i < vals[idx].length; i++) {
int node = valToNode2[idx][i];
if(cycleMask[node] == mask) {
goodMask[mask] = node;
break;
}
}
}
int[] dp = new int[1<<K];
Arrays.fill(dp, -1); dp[0] = 0;
for(int mask = 1; mask < dp.length; mask++) {
if(goodMask[mask] != -1) {
dp[mask] = mask;
continue;
}
for(int sub = mask; sub != 0; sub = (sub-1)&mask) {
if(goodMask[sub] == -1) continue;
int newMask = mask-sub;
if(dp[newMask] == -1) continue;
dp[mask] = sub;
break;
}
}
if(dp[dp.length-1] == -1) out.println("No");
else {
int[][] res = new int[K][2];
for(int[] x : res) Arrays.fill(x, -1);
int curMask = dp.length-1;
while(curMask > 0) {
int temp = dp[curMask];
int curNode = goodMask[temp];
while(temp > 0) {
int curVal = nodeToVal.get(curNode), curBox = whichBox.get(curVal);
res[curBox][0] = curVal;
int goingTo = ptsTo[curNode], goingVal = nodeToVal.get(goingTo), goingBox = whichBox.get(goingVal);
res[goingBox][1] = curBox;
curNode = ptsTo[curNode];
temp -= 1<<curBox;
}
curMask -= dp[curMask];
}
out.println("Yes");
for(int i = 0; i < K; i++) {
if(res[i][1] == -1) throw null;
out.printf("%d %d\n", res[i][0], res[i][1]+1);
}
}
out.close();
}
void dfs(int node) {
dfsStack[node] = 1;
stack.addLast(node);
int goTo = ptsTo[node];
if(goTo == -1) {
while(!stack.isEmpty()) {
cycleMask[stack.pollLast()] = -1;
}
}
else {
if(dfsStack[goTo] == 1) {
int ptr = 0, mask = 0, conflict = 0;
while(!stack.isEmpty()) {
int now = stack.pollLast(), val = nodeToVal.get(now), box = whichBox.get(val);
tempList[ptr++] = now;
if((mask & (1<<box)) > 0) conflict = 1;
mask |= 1<<box;
if(now == goTo) break;
}
while(!stack.isEmpty()) {
cycleMask[stack.pollLast()] = -1;
}
for(int i = 0; i < ptr; i++) {
int now = tempList[i];
if(conflict > 0) cycleMask[now] = -1;
else cycleMask[now] = mask;
}
}
else if(dfsStack[goTo] == 2) {
while(!stack.isEmpty()) {
cycleMask[stack.pollLast()] = -1;
}
}
else {
dfs(goTo);
}
}
dfsStack[node] = 2;
}
class FastScanner {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
}
|
np
|
1242_C. Sum Balance
|
CODEFORCES
|
import jdk.nashorn.internal.objects.NativeArray;
import javax.swing.JOptionPane ;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import java.sql.SQLSyntaxErrorException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Vector;
import static jdk.nashorn.internal.objects.NativeArray.sort;
import static jdk.nashorn.internal.runtime.ScriptObject.toPropertyDescriptor;
public class Dialog1 {
private static int n ;
private static String s ;
private static char[] a;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
n = input.nextInt() ;
s = input.next() ;
a = s.toCharArray();
for(int i = 0 ; i < 200 ; ++i) {
int cur = i ;
boolean fl = true ;
for(int j = 0 ; j < n ; ++j) {
if(a[j] == '+')
++cur ;
else
--cur ;
if(cur < 0)
fl = false ;
}
if(fl) {
System.out.print(cur);
return ;
}
}
}
}
|
linear
|
1159_A. A pile of stones
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStream input = System.in;
OutputStream output = System.out;
InputReader in = new InputReader(new FileReader(new File("input.txt")));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
Solution s = new Solution();
s.solve(1, in, out);
out.close();
}
static class Solution {
static int[][] grid;
static int[] dx = {0, 0, 1, -1};
static int[] dy = {1, -1, 0, 0};
static int n, m;
public void solve(int cs, InputReader in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
int k = in.nextInt();
grid = new int[n][m];
for (int[] d : grid)
Arrays.fill(d, -1);
for (int i = 0; i < k; i++) {
Pair tree = new Pair(in.nextInt()-1, in.nextInt()-1);
bfs(tree);
}
int max = 0, idx1 = 0, idx2 = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] > max) {
max = grid[i][j];
idx1 = i;
idx2 = j;
}
}
}
out.printf("%d %d%n", idx1+1, idx2+1);
}
public boolean isValid(int i, int j) {
return i >= 0 && i < n && j >= 0 && j < m;
}
static class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public void bfs(Pair src) {
Queue<Pair> q = new LinkedList<>();
grid[src.x][src.y] = 0;
q.add(src);
while (!q.isEmpty()) {
Pair p = q.poll();
for (int k = 0; k < 4; k++) {
int nx = p.x+dx[k];
int ny = p.y+dy[k];
if (isValid(nx, ny)) {
if (grid[nx][ny] > grid[p.x][p.y]+1 || grid[nx][ny] == -1) {
grid[nx][ny] = grid[p.x][p.y] + 1;
q.add(new Pair(nx, ny));
}
}
}
}
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream i) {
br = new BufferedReader(new InputStreamReader(i), 32768);
st = null;
}
public InputReader(FileReader s) {
br = new BufferedReader(s);
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
What do you think? What do you think?
1st on Billboard, what do you think of it
Next is a Grammy, what do you think of it
However you think, I’m sorry, but shit, I have no fcking interest
*******************************
I'm standing on top of my Monopoly board
That means I'm on top of my game and it don't stop
til my hip don't hop anymore
https://www.a2oj.com/Ladder16.html
*******************************
300iq as writer = Sad!
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x1080D
{
public static void main(String hi[]) throws Exception
{
long[] dp = new long[32];
for(int i=1; i <= 31; i++)
dp[i] = 1+4*dp[i-1];
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
matcha:while(T-->0)
{
st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
long K = Long.parseLong(st.nextToken());
if(N >= 32 || K == 1)
sb.append("YES "+(N-1)+"\n");
else if(dp[N] == K)
sb.append("YES 0\n");
else if(dp[N] < K)
sb.append("NO\n");
else
{
long total = 3L;
long length = 2;
for(int res=N-1; res >= 0; res--)
{
long min = 1+3*dp[N-1-res];
long max = min+dp[N-1];
long cansplit = total-2*length+1;
max += dp[res]*cansplit;
if(min <= K && K <= max)
{
sb.append("YES "+res+"\n");
continue matcha;
}
length <<= 1;
total *= 4;
}
sb.append("NO\n");
}
}
System.out.print(sb);
}
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
import java.util.Scanner;
public class Main3 implements Runnable {
public static void main(String[] args) {
new Thread(null, new Main3(), "", 128 * 1024 * 1024).start();
}
private static Scanner in = new Scanner(System.in);
public void run() {
int n = in.nextInt();
int m = 1_000_000_007;
boolean[] state = new boolean[n];
for (int i = 0; i < n; i++) {
state[i] = in.next().equals("f");
}
// 使うのは[n][n]だけど、j+1==nのときif分岐せずに済むようにn+1にしてる
long[][] dp = new long[n][n + 1];
dp[0][0] = 1;
// iは既に埋まっていてi+1に書き込んでいくから、i<n-1まででいい
for (int i = 0; i < n - 1; i++) {
if (state[i]) {
// 右下にコピーしていくから溢れないようにj<n-1
for (int j = 0; j < n - 1; j++) {
dp[i + 1][j + 1] = dp[i][j];
}
} else {
// 何通りかというのを右から埋めていくからj--で進める
for (int j = n - 1; j >= 0; j--) {
// 足していくと大きくなるからこの時点でもう%mしておく
dp[i + 1][j] = (dp[i][j] + dp[i + 1][j + 1]) % m;
}
}
}
long sum = 0;
for (int i = 0; i < n; i++) {
sum += dp[n - 1][i] % m;
}
System.out.println(sum % m);
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class codeforces2 {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
// Scanner scan = new Scanner(System.in);
//for (int i = 1; i <= 10; i++) {
// System.out.println(i + " " + divisors(i).toString());
//}
int tc = sc.ni();
for (int rep = 0; rep < tc; rep++) {
long n = sc.nl();
if (n % 2 == 1) {
pw.println("NO");
}
else {
n/= 2;
if (perfectSquare(n)) {
pw.println("YES");
}
else if (n % 2 == 0 && perfectSquare(n/2)) {
pw.println("YES");
}
else {
pw.println("NO");
}
}
}
pw.close();
}
//precondition: n <= m
public static boolean solve(int n,int m, int k) {
return false;
}
public static boolean perfectSquare(long n) {
long lo = 0;
long hi = n;
while (lo < hi) {
long k = (lo + hi) / 2;
if (k * k < n)
lo = k + 1;
else
hi = k;
}
return (lo * lo == n);
}
static Set<Integer> divisors(int n) {
Set<Integer> set = new HashSet();
for (int i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
// If divisors are equal, print only one
if (n/i == i)
set.add(i);
else {// Otherwise print both
set.add(i);
set.add(n / i);
}
}
}
return set;
}
static Map<Integer, Integer> primeFactorization(int x) {
//first divide by 2
Map<Integer, Integer> map = new HashMap();
if (x == 0) return map;
int count = 0;
while (x % 2 == 0) {
x /=2;
count++;
}
//insert 2
if (count > 0) map.put(2, count);
for (int divisor = 3; divisor * divisor <= x; divisor += 2) {
int cnt = 0;
while (x % divisor == 0) {
x /= divisor;
cnt++;
}
if (cnt > 0) map.put(divisor, cnt);
}
if (x > 1) {
map.put(x, 1);
}
return map;
}
static boolean isPrime(int n)
{
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// method to return LCM of two numbers
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
public static void sort(int[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
public static void sort(long[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
/* */
//printing methods
/* */
//WOW!
/* */
public static void printArr(PrintWriter pw, int[] arr) {
StringBuilder sb = new StringBuilder();
for (int x : arr) {
sb.append(x + "");
}
sb.setLength(sb.length() - 1);
pw.println(sb.toString());
}
public static void printArr2d(PrintWriter pw, int[][] arr) {
StringBuilder sb = new StringBuilder();
for (int[] row : arr) {
for (int x : row) {
sb.append(x + " ");
}
sb.setLength(sb.length() - 1);
sb.append("\n");
}
sb.setLength(sb.length() - 1);
pw.println(sb.toString());
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[] 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;
}
}
class UnionFind {
int size;
private int[] id;
public UnionFind(int size) {
this.size = size;
id = new int[size];
for (int i = 0; i < id.length; i++) {
id[i] = i;
}
}
public int find(int a) {
if (id[a] != a) {
id[a] = find(id[a]);
}
return id[a];
}
public void union(int a, int b) {
int r1 = find(a);
int r2 = find(b);
if (r1 == r2) return;
size--;
id[r1] = r2;
}
@Override
public String toString() {
return Arrays.toString(id);
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.lang.*;
import static java.lang.Math.*;
// _ h _ r _ t r _
// _ t _ t _ s t _
public class TaskA implements Runnable {
long m = (int)1e9+7;
PrintWriter w;
InputReader c;
final int MAXN = (int)1e6 + 100;
public void run() {
c = new InputReader(System.in);
w = new PrintWriter(System.out);
int n = c.nextInt(), hamming_distance = 0;
char[] s = c.next().toCharArray(), t = c.next().toCharArray();
HashMap<Character, HashSet<Character>> replace = new HashMap<>();
HashMap<Character, Integer> map = new HashMap<>();
for(int i=0;i<n;++i) if(s[i] != t[i]) {
HashSet<Character> temp;
if(replace.containsKey(s[i])){
temp = replace.get(s[i]);
temp.add(t[i]);
} else {
temp = new HashSet<>();
temp.add(t[i]);
}
map.put(s[i],i);
replace.put(s[i], temp);
hamming_distance++;
}
int l = -1, r = -1;
boolean global_check = false;
for(int i=0;i<n;i++) if(s[i] != t[i]) {
if(replace.containsKey(t[i])) {
HashSet<Character> indices = replace.get(t[i]);
int ind = map.get(t[i]);
l = i + 1;
r = ind + 1;
if (indices.contains(s[i])) {
hamming_distance -= 2;
global_check = true;
break;
}
}
if(global_check) break;
}
if(!global_check && l!=-1) hamming_distance--;
else if(global_check){
for(int i=0;i<n;i++) {
if(t[i] == s[l-1] && s[i] == t[l-1]){
r = i + 1;
break;
}
}
}
w.println(hamming_distance);
w.println(l+" "+r);
w.close();
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void sortbyColumn(int arr[][], int col){
Arrays.sort(arr, new Comparator<int[]>()
{
public int compare(int[] o1, int[] o2){
return(Integer.valueOf(o1[col]).compareTo(o2[col]));
}
});
}
public static class DJSet {
public int[] upper;
public DJSet(int n) {
upper = new int[n];
Arrays.fill(upper, -1);
}
public int root(int x) {
return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
}
public boolean equiv(int x, int y) {
return root(x) == root(y);
}
public boolean union(int x, int y) {
x = root(x);
y = root(y);
if (x != y) {
if (upper[y] < upper[x]) {
int d = x;
x = y;
y = d;
}
upper[x] += upper[y];
upper[y] = x;
}
return x == y;
}
}
public static int[] radixSort(int[] f) {
int[] to = new int[f.length];
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
public void printArray(int[] a){
for(int i=0;i<a.length;i++)
w.print(a[i]+" ");
w.println();
}
public int[] scanArrayI(int n){
int a[] = new int[n];
for(int i=0;i<n;i++)
a[i] = c.nextInt();
return a;
}
public long[] scanArrayL(int n){
long a[] = new long[n];
for(int i=0;i<n;i++)
a[i] = c.nextLong();
return a;
}
public void printArray(long[] a){
for(int i=0;i<a.length;i++)
w.print(a[i]+" ");
w.println();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new TaskA(),"TaskA",1<<26).start();
}
}
|
linear
|
527_B. Error Correct System
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class a {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int t = sc.nextInt();
int[][] xa = new int[n][2];
for(int i=0; i<n; ++i) {
xa[i][0] = sc.nextInt();
xa[i][1] = sc.nextInt();
}
Arrays.sort(xa, new Comparator<int[]>(){
@Override
public int compare(int[] a0, int[] a1){
return a0[0]-a1[0];
}
});
int ans=2;
for(int i=0; i<n-1; i++){
int s=(xa[i+1][0]*2-xa[i+1][1])-(xa[i][0]*2+xa[i][1]);
if(s>t*2){
ans+=2;
}else if(s==t*2){
ans++;
}
}
System.out.println(ans+"");
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
// Petya and Spiders
// 2011/9/3
public class P111C{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
int n, m;
void run(){
n=sc.nextInt();
m=sc.nextInt();
solve();
}
void solve(){
if(n<m){
int t=n;
n=m;
m=t;
}
int full=(1<<m)-1;
int[][] dp=new int[1<<m][1<<m];
int[][] tmp=new int[1<<m][1<<m];
for(int i=0; i<1<<m; i++){
fill(dp[i], INF);
}
for(int i=0; i<1<<m; i++){
int b1=(i|(i>>1)|(i<<1))&full;
int b2=i;
dp[b1][b2]=Integer.bitCount(i);
}
for(int j=0; j<n-1; j++){
for(int i=0; i<1<<m; i++){
System.arraycopy(dp[i], 0, tmp[i], 0, 1<<m);
fill(dp[i], INF);
}
for(int b1=0; b1<1<<m; b1++){
for(int b2=0; b2<1<<m; b2++){
for(int i=0; i<1<<m; i++){
if((b1|i)!=full){
continue;
}
int b=(i|(i>>1)|(i<<1))&full;
dp[b2|b][i]=min(dp[b2|b][i],
tmp[b1][b2]+Integer.bitCount(i));
}
}
}
}
int min=INF;
for(int i=0; i<1<<m; i++){
min=min(min, dp[full][i]);
}
int ans=m*n-min;
println(ans+"");
}
void println(String s){
System.out.println(s);
}
public static void main(String[] args){
new P111C().run();
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class My {
public static void main(String[] args) {
new My().go();
}
void go() {
Scanner in = new Scanner(System.in);
long n = in.nextLong();
int k = in.nextInt();
int mn = 0, mx = k + 1;
while (mn < mx) {
int mid = (mn + mx) / 2;
if (works(n, k, mid)) {
mx = mid;
} else {
mn = mid + 1;
}
}
if (mn > k) {
pl("-1");
} else {
pl((mn - 1) + "");
}
}
boolean works(long n, int k, int use) {
return 1 + T(k - 1) - T(k - use) >= n;
}
long T(int n) {
return n * (long)(n + 1) / 2;
}
void p(String s) {
System.out.print(s);
}
void pl(String s) {
System.out.println(s);
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class B176 {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
long n = in.nextLong() - 1;
long k = in.nextLong() - 1;
if (k * (k + 1) / 2 < n) out.println(-1);
else if (n == 0) out.println(0);
else if (n < k) out.println(1);
else {
long t = binSearch(n, k, 1, k);
long ans = k - t + 1;
if (k * (k + 1) / 2 - t * (t - 1) / 2 != n) ans++;
out.println(ans);
}
out.close();
}
private static long binSearch(long n, long k, long from, long to) {
if (from == to) return from;
long mid = (from + to) / 2;
if (k * (k + 1) / 2 - mid * (mid - 1) / 2 > n) return binSearch(n, k, mid + 1, to);
else return binSearch(n, k, from, mid);
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
int n = nextInt();
String nn = Integer.toString(n);
if(n >= 0){
println(n);
} else {
println(Math.max(Integer.parseInt(nn.substring(0,nn.length() - 1)), Integer.parseInt(nn.substring(0, nn.length() - 2) + nn.charAt(nn.length() - 1))));
}
}
private static PrintWriter out = new PrintWriter(System.out);
private static BufferedReader inB = new BufferedReader(new InputStreamReader(System.in));
private static StreamTokenizer in = new StreamTokenizer(inB);
private static void exit(Object o) throws Exception {
out.println(o);
out.flush();
System.exit(0);
}
private static void println(Object o) throws Exception{
out.println(o);
out.flush();
}
private static void print(Object o) throws Exception{
out.print(o);
out.flush();
}
private static long nextLong() throws Exception {
in.nextToken();
return (long)in.nval;
}
private static int nextInt() throws Exception {
in.nextToken();
return (int)in.nval;
}
private static String nextString() throws Exception {
in.nextToken();
return in.sval;
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Template implements Runnable {
private void solve() throws IOException {
int n = nextInt();
int m = nextInt();
boolean[][] g = new boolean[n][n];
for (int i = 0; i < m; ++i) {
int a = nextInt() - 1;
int b = nextInt() - 1;
g[a][b] = true;
g[b][a] = true;
}
/*for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
g[i][j] = true;*/
long[] am = new long[n + 1];
long[][] ways = new long[1 << n][n];
for (int start = 0; start < n; ++start) {
for (int mask = 0; mask < (1 << (n - start)); ++mask)
for (int last = start; last < n; ++last) {
ways[mask][last - start] = 0;
}
ways[1][0] = 1;
for (int mask = 0; mask < (1 << (n - start)); ++mask) {
int cnt = 0;
int tmp = mask;
while (tmp > 0) {
++cnt;
tmp = tmp & (tmp - 1);
}
for (int last = start; last < n; ++last)
if (ways[mask][last - start] > 0) {
long amm = ways[mask][last - start];
for (int i = start; i < n; ++i)
if ((mask & (1 << (i - start))) == 0 && g[last][i]) {
ways[mask | (1 << (i - start))][i - start] += amm;
}
if (g[last][start])
am[cnt] += ways[mask][last - start];
}
}
}
long res = 0;
for (int cnt = 3; cnt <= n; ++cnt) {
if (am[cnt] % (2) != 0)
throw new RuntimeException();
res += am[cnt] / (2);
}
writer.println(res);
}
public static void main(String[] args) {
new Template().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.io.IOException;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
private static final int MOD = (int) 1e9 + 7;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] primes = getPrimes(40_000);
int[][] a = new int[n][];
for (int i = 0; i < n; ++i) {
int x = in.nextInt();
IntList divs = new IntList();
for (int j : primes) {
if (j * j > x) {
break;
}
int cnt = 0;
while (x % j == 0) {
cnt++;
x /= j;
}
if (cnt % 2 == 1) {
divs.add(j);
}
}
if (x > 1) {
divs.add(x);
}
a[i] = divs.toArray();
}
Comparator<int[]> cmp = ((o1, o2) -> {
for (int i = 0; i < o1.length && i < o2.length; ++i) {
if (o1[i] < o2[i]) {
return -1;
} else if (o2[i] < o1[i]) {
return 1;
}
}
return Integer.compare(o1.length, o2.length);
});
Arrays.sort(a, cmp);
IntList freqsList = new IntList();
int cnt = 1;
for (int i = 1; i < n; ++i) {
if (cmp.compare(a[i], a[i - 1]) == 0) {
cnt++;
} else {
freqsList.add(cnt);
cnt = 1;
}
}
freqsList.add(cnt);
int[][] comb = new int[2 * n + 1][2 * n + 1];
for (int i = 0; i < comb.length; ++i) {
comb[i][0] = 1;
for (int j = 1; j <= i; ++j) {
comb[i][j] = (comb[i - 1][j] + comb[i - 1][j - 1]) % MOD;
}
}
int[] dp = new int[n];
int[] ndp = new int[n];
dp[0] = 1;
int total = 0;
int ans = 1;
for (int x : freqsList.toArray()) {
Arrays.fill(ndp, 0);
for (int bad = 0; bad < n; ++bad) {
if (dp[bad] == 0) {
continue;
}
for (int putSeparately = 1; putSeparately <= x; ++putSeparately) {
for (int breakEq = 0; breakEq <= putSeparately; ++breakEq) {
int nState = bad + x - putSeparately - breakEq;
if (nState < 0 || nState >= n) {
continue;
}
int rem = total + 1 - bad;
int notBreak = putSeparately - breakEq;
if (breakEq > bad || notBreak > rem) {
continue;
}
int add = (int) ((long) comb[bad][breakEq] * comb[rem][notBreak] % MOD *
comb[x - 1][putSeparately - 1] % MOD * dp[bad] % MOD);
ndp[nState] += add;
ndp[nState] %= MOD;
}
}
}
total += x;
int[] aux = dp;
dp = ndp;
ndp = aux;
ans = (int) ((long) ans * fact(x) % MOD);
}
ans = (int) ((long) ans * dp[0] % MOD);
out.println(ans);
}
private int fact(int n) {
int res = 1;
for (int i = 2; i <= n; ++i) {
res = (int) ((long) res * i % MOD);
}
return res;
}
private int[] getPrimes(int n) {
boolean[] isPrime = new boolean[n + 1];
Arrays.fill(isPrime, 2, isPrime.length, true);
for (int i = 2; i * i <= n; ++i) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
IntList primes = new IntList();
for (int i = 2; i <= n; ++i) {
if (isPrime[i]) {
primes.add(i);
}
}
return primes.toArray();
}
}
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 UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static interface IntIterator extends Iterator<Integer> {
}
static class IntList implements Iterable<Integer> {
int[] elem;
int size;
public IntList() {
this(0, 0, 1);
}
public IntList(int size) {
this(size, 0, Math.max(1, size));
}
public IntList(int size, int value) {
this(size, value, Math.max(1, size));
}
public IntList(int size, int value, int capacity) {
elem = new int[capacity];
Arrays.fill(elem, 0, size, value);
this.size = size;
}
private IntList(int... e) {
elem = e.clone();
size = e.length;
}
public void add(int e) {
if (size + 1 > elem.length) {
increaseCapacity();
}
elem[size++] = e;
}
private void increaseCapacity() {
changeCapacity(3 * elem.length / 2 + 1);
}
private void changeCapacity(int newCapacity) {
int[] nElem = new int[newCapacity];
System.arraycopy(elem, 0, nElem, 0, Math.min(elem.length, newCapacity));
elem = nElem;
}
public IntIterator iterator() {
return new IntIterator() {
int pos = 0;
public Integer next() {
return IntList.this.elem[pos++];
}
public boolean hasNext() {
return pos < IntList.this.size;
}
public int nextInt() {
return IntList.this.elem[pos++];
}
};
}
public int[] toArray() {
return Arrays.copyOf(elem, size);
}
public int hashCode() {
int hashCode = 0;
for (int i = 0; i < size; ++i) {
hashCode = 31 * hashCode + elem[i];
}
return hashCode;
}
}
}
|
cubic
|
840_C. On the Bench
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class D {
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
BigInteger nextBigInteger() {
try {
return new BigInteger(nextLine());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
}
public static void main(String[] args) throws IOException {
FastReader fr = new FastReader();
FastWriter fw = new FastWriter();
int n = fr.nextInt();
int m = fr.nextInt();
for (int r = 0; r < n / 2; r++) {
for (int c = 0; c < m; c++) {
fw.println((r + 1) + " " + (c + 1));
fw.println((n - r) + " " + (m - c));
}
}
if (n % 2 != 0) {
int r = n / 2;
for (int c = 0; c < m / 2; c++) {
fw.println((r + 1) + " " + (c + 1));
fw.println((r + 1) + " " + (m - c));
}
if (m % 2 != 0) fw.println((r + 1) + " " + (m / 2 + 1));
}
fw.close();
}
}
|
quadratic
|
1179_B. Tolik and His Uncle
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class FirstClass {
public static void main(String[] args)throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
int arr[] = new int [n];
StringTokenizer st1 = new StringTokenizer(br.readLine());
for(int i = 0 ; i < n ; i++)
{
arr[i] = Integer.parseInt(st1.nextToken());
}
int max = -1;
boolean flag = true;
for(int i = 0 ; i < n ; i++)
{
if(arr[i] > max+1)
{
flag = false;
out.println(i+1);
break;
}
else
{
max = Math.max(max, arr[i]);
}
}
if(flag)
out.println(-1);
out.flush();
out.close();
}
}
|
linear
|
1054_B. Appending Mex
|
CODEFORCES
|
import java.util.*;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long l = sc.nextLong();
long h = sc.nextLong();
sc.close();
if(h-l<2) {
System.out.println(-1);
return ;
}
if(h-l==2 && l%2==1) {
System.out.println(-1);
return ;
}
if(l%2==1) {
++l;
}
System.out.printf("%d %d %d\n",l,l+1L,l+2L);
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.