src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.io.*;
import java.util.*;
import static java.util.Arrays.*;
public class E implements Runnable
{
public static void main(String[] args) throws IOException
{
new Thread(null, new E(), "", 1 << 20).start();
}
BufferedReader input;
PrintWriter out;
String file = "input";
public void run()
{
try
{
//input = new BufferedReader(new FileReader(file + ".in"));
input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
solve();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
void solve() throws IOException
{
int n = Integer.parseInt(input.readLine());
double[][] p = new double[n][n];
for(int i = 0; i < n; i++)
{
StringTokenizer st = new StringTokenizer(input.readLine());
for(int j = 0; j < n; j++)
{
p[i][j] = Double.parseDouble(st.nextToken());
}
}
double[] dp = new double[1 << n];
int mask = (1 << n) - 1;
dp[mask] = 1;
for(int w = mask; w > 0; w--)
{
int count = 0;
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
if((w >> i & 1) != 0 && (w >> j & 1) != 0) count++;
if(count == 0) continue;
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
if((w >> i & 1) != 0 && (w >> j & 1) != 0)
{
dp[w ^ (1 << i)] += 1.0 / count * p[j][i] * dp[w];
dp[w ^ (1 << j)] += 1.0 / count * p[i][j] * dp[w];
}
}
for(int i = 0; i < n; i++)
System.out.print(dp[1 << i] + " ");
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.Scanner;
/**
* Created by Gantushig on 2/18/2016.
*/
public class A {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long n = input.nextLong();
System.out.println("25");
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import javax.crypto.AEADBadTagException;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author AlexFetisov
*/
public class TaskB_AF {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB_cf371 solver = new TaskB_cf371();
solver.solve(1, in, out);
out.close();
}
static class TaskB_cf371 {
List<Rectangle> rects;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int xLeft = 1, xRight = n;
int xSeparate = -1;
while (xLeft <= xRight) {
int e = (xLeft + xRight) / 2;
int t = makeRequest(in, out, 1, 1, e, n);
if (t == 1) {
xSeparate = e;
xRight = e - 1;
} else if (t == 0) {
xLeft = e + 1;
} else {
xRight = e - 1;
}
}
rects = new ArrayList<Rectangle>();
if (xSeparate != -1 && makeRequest(in, out, xSeparate + 1, 1, n, n) == 1) {
detectRectangle(in, out, 1, 1, xSeparate, n);
detectRectangle(in, out, xSeparate + 1, 1, n, n);
out.print("! ");
for (Rectangle r : rects) {
out.print(r.toString() + " ");
}
out.println();
out.flush();
return;
}
int yLeft = 1, yRight = n;
int ySeparate = -1;
while (yLeft <= yRight) {
int e = (yLeft + yRight) / 2;
int t = makeRequest(in, out, 1, 1, n, e);
if (t == 1) {
ySeparate = e;
yRight = e - 1;
} else if (t == 0) {
yLeft = e + 1;
} else {
yRight = e - 1;
}
}
if (ySeparate != -1) {
detectRectangle(in, out, 1, 1, n, ySeparate);
detectRectangle(in, out, 1, ySeparate + 1, n, n);
out.print("! ");
for (Rectangle r : rects) {
out.print(r.toString() + " ");
}
out.println();
out.flush();
return;
}
throw new AssertionError("!");
}
private void detectRectangle(InputReader in, PrintWriter out, int xMin, int yMin, int xMax, int yMax) {
int xLeft = -1, xRight = -1, yLeft = -1, yRight = -1;
int left = xMin, right = xMax;
while (left <= right) {
int e = (left + right) / 2;
if (makeRequest(in, out, xMin, yMin, e, yMax) == 1) {
xRight = e;
right = e - 1;
} else {
left = e + 1;
}
}
left = xMin;
right = xRight;
while (left <= right) {
int e = (left + right) / 2;
if (makeRequest(in, out, e, yMin, xRight, yMax) == 1) {
xLeft = e;
left = e + 1;
} else {
right = e - 1;
}
}
left = yMin;
right = yMax;
while (left <= right) {
int e = (left + right) / 2;
if (makeRequest(in, out, xLeft, yMin, xRight, e) == 1) {
yRight = e;
right = e - 1;
} else {
left = e + 1;
}
}
left = yMin;
right = yRight;
while (left <= right) {
int e = (left + right) / 2;
if (makeRequest(in, out, xLeft, e, xRight, yRight) == 1) {
yLeft = e;
left = e + 1;
} else {
right = e - 1;
}
}
rects.add(new Rectangle(xLeft, yLeft, xRight, yRight));
}
private int makeRequest(InputReader in, PrintWriter out, int x1, int y1, int x2, int y2) {
out.print("? " + x1 + " " + y1 + " " + x2 + " " + y2);
out.println();
out.flush();
return in.nextInt();
}
class Rectangle {
int x1;
int x2;
int y1;
int y2;
public Rectangle(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
public String toString() {
StringBuilder b = new StringBuilder("");
b.append(x1).append(' ');
b.append(y1).append(' ');
b.append(x2).append(' ');
b.append(y2);
return b.toString();
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
import java.io.*;
import java.awt.geom.Point2D;
import java.text.*;
import java.math.*;
import java.util.*;
public class Main implements Runnable {
final String filename="";
public void solve() throws Exception {
int n = iread(), k = iread();
boolean[] f = new boolean[10000];
int prev = -1;
cycle:for (int i=2; i<=n; i++)
{
for (int j=2; j*j<=i; j++)
if (i%j==0)
continue cycle;
if (prev!=-1)
f[i+prev+1] = true;
if (f[i])
k--;
prev = i;
}
if (k<=0)
out.write("YES\n");
else out.write("NO\n");
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter(System.out));
// in = new BufferedReader(new FileReader(filename+".in"));
// out = new BufferedWriter(new FileWriter(filename+".out"));
solve();
out.flush();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public int iread() throws Exception {
return Integer.parseInt(readword());
}
public double dread() throws Exception {
return Double.parseDouble(readword());
}
public long lread() throws Exception {
return Long.parseLong(readword());
}
BufferedReader in;
BufferedWriter out;
public String readword() throws IOException {
StringBuilder b = new StringBuilder();
int c;
c = in.read();
while (c >= 0 && c <= ' ')
c = in.read();
if (c < 0)
return "";
while (c > ' ') {
b.append((char) c);
c = in.read();
}
return b.toString();
}
public static void main(String[] args) {
try{
Locale.setDefault(Locale.US);
} catch (Exception e)
{
}
new Thread(new Main()).start();
//new Thread(null, new Main(), "1", 1<<25).start();
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.util.Scanner;
public class composite {
public static void main(String[] args) {
int b;
Scanner s3=new Scanner(System.in);
b=s3.nextInt();
if(b%2==0)
{
b=b-4;
System.out.println(4+" "+b);
}
else
{
b=b-9;
System.out.println(9+" "+b);
}
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.util.*;
public class test
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int t=in.nextInt();
House[] houses=new House[n];
for(int i=0;i<n;i++)
{
houses[i]=new House(in.nextInt(),in.nextInt());
}
Arrays.sort(houses);
int count=2;
for(int i=0;i<n-1;i++)
{
double start=houses[i].x+(double)houses[i].a/2;
double end=houses[i+1].x-(double)houses[i+1].a/2;
if(end-start==t)
count++;
if(end-start>t)
count+=2;
}
System.out.println(count);
}
}
class House implements Comparable<House>
{
int x;
int a;
public House(int _x, int _a)
{
x=_x;
a=_a;
}
@Override
public int compareTo(House o) {
return x-o.x;
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
public class _v14 {
public static void main(String args[]){
PrintWriter out = new PrintWriter(System.out);
Reader in = new Reader();
long k = in.nextLong();
if(k<10){
System.out.println(k);
return;
}
long sum = 0;
long cur = 9;
long prev = 0;
int count = 1;
while(k>cur){
k= k - cur;
sum = sum + cur/count;
prev = cur;
cur = 9*(count+1)*(long)Math.pow(10,count);
count++;
}
long num = k/(count);
sum = sum + num;
if(k%count == 0){
System.out.println(sum%10);
}
else{
sum++;
k = k%(count);
String str = String.valueOf(sum);
System.out.println(str.charAt((int)k-1));
}
out.flush();
out.close();
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main implements Runnable {
public void solution() throws IOException {
int n = in.nextInt();
int[] a = new int[n];
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
if (a[i] < min) {
min = a[i];
}
}
int res = Integer.MAX_VALUE;
for (int i = 0; i < n; ++i) {
if (a[i] != min && a[i] < res) {
res = a[i];
}
}
if (res == Integer.MAX_VALUE) {
out.println("NO");
} else {
out.println(res);
}
}
public void run() {
try {
solution();
in.reader.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
}
private class Scanner {
private BufferedReader reader;
private StringTokenizer tokenizer;
public Scanner(Reader reader) {
this.reader = new BufferedReader(reader);
this.tokenizer = new StringTokenizer("");
}
public boolean hasNext() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String next = reader.readLine();
if (next == null) {
return false;
}
tokenizer = new StringTokenizer(next);
}
return true;
}
public String next() throws IOException {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public String nextLine() throws IOException {
tokenizer = new StringTokenizer("");
return reader.readLine();
}
}
public static void main(String[] args) throws IOException {
new Thread(null, new Main(), "", 1 << 28).start();
}
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
Scanner in = new Scanner(new InputStreamReader(System.in));
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class A {
private 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);
int sum = 0;
for (int i = a.length - 1; i >= 0; i--) {
sum += a[i];
int k = 0;
for (int j = 0; j < i; j++)
k += a[j];
if (sum > k) {
pl(a.length - i);
return;
}
}
}
public static void main(String[] args) {
new A().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());
}
BigInteger nextBigInteger() throws IOException {
return new BigInteger(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
void p(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.flush();
writer.print(objects[i]);
writer.flush();
}
}
void pl(Object... objects) {
p(objects);
writer.flush();
writer.println();
writer.flush();
}
int cc;
void pf() {
writer.printf("Case #%d: ", ++cc);
writer.flush();
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int len = s.nextInt();
s.nextLine();
String l = s.nextLine();
char[] ca = l.toCharArray();
int h = 0;
for (char c : ca)
h += A(c);
int cur = h;
int i;
for (i = 0; i < h; i++)
cur -= A(ca[i]);
int best = cur;
while (i != h + len) {
cur -= A(ca[i % len]);
cur += A(ca[(i - h) % len]);
best = best > cur ? cur : best;
i++;
}
System.out.println(best);
}
public static int A(char x) {
return x == 'H' ? 1 : 0;
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
long n = sc.nextLong();
Long S = sc.nextLong();
long l = 0;
long h = n;
long ans = n;
while(l <= h) {
long mid = (l + h) / 2;
long t = mid;
long sum = 0;
while(t > 0) {
sum += t % 10;
t /= 10;
}
if(mid - sum < S) {
ans = mid;
l = mid + 1;
}else
h = mid - 1;
}
out.println(n - ans);
out.flush();
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream System){br = new BufferedReader(new InputStreamReader(System));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine()throws IOException{return br.readLine();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public char nextChar()throws IOException{return next().charAt(0);}
public Long nextLong()throws IOException{return Long.parseLong(next());}
public boolean ready() throws IOException{return br.ready();}
public void waitForInput(){for(long i = 0; i < 3e9; i++);}
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int distinct = sc.nextInt();
HashMap<Integer, Integer> set = new HashMap<Integer, Integer>();
int[] ar = new int[n];
for (int i = 0; i < n; i++) {
ar[i] = sc.nextInt();
if (set.containsKey(ar[i])) {
set.put(ar[i], set.get(ar[i])+1);
} else {
set.put(ar[i], 1);
}
if (set.size() == distinct) {
int st = 0;
for (int j = 0; j < i; j++) {
st=j;
if (set.get(ar[j]) > 1) {
set.put(ar[j], set.get(ar[j]) - 1);
} else {
break;
}
}
System.out.println((st + 1) + " " + (i + 1));
return;
}
}
System.out.println("-1 -1");
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
//Edwin Lunando template for online algorithm contest
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Main {
// class node implements Comparable<node> {
//
// public int a;
// public int b;
//
// public int compareTo(node a) {
// if (a.b == this.b) {
// return a.a - this.a;
// } else {
// return a.b - this.b;
// }
// }
//
// public node(int a, int b) {
// this.a = a;
// this.b = b;
// }
// }
private void solve() throws IOException {
int n = nextInt();
int[] arr = new int[n];
int count = 0;
for (int x = 0; x < n; x++) {
arr[x] = nextInt();
count+= arr[x];
}
Arrays.sort(arr);
count /=2;
int result = 0, sum = 0;
for (int x = arr.length - 1; x >= 0; x--) {
sum += arr[x];
result++;
if (sum > count) {
break;
}
}
System.out.println(result);
}
public static void main(String[] args) {
try {
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(System.out);
//out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
new Main().solve();
out.close();
} catch (Throwable e) {
System.out.println(e);
System.exit(239);
}
}
static BufferedReader br;
static StringTokenizer st;
static PrintWriter out;
static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
static int[] nextIntArray(int n) throws IOException {
int[] temp = new int[n];
for (int x = 0; x < n; x++) {
temp[x] = nextInt();
}
return temp;
}
static long[] nextLongArray(int n) throws IOException {
long[] temp = new long[n];
for (int x = 0; x < n; x++) {
temp[x] = nextLong();
}
return temp;
}
static String[] nextArray(int n) throws IOException {
String[] temp = new String[n];
for (int x = 0; x < n; x++) {
temp[x] = nextToken();
}
return temp;
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.util.*;
import java.math.*;
/**
*
* @author Izhari Ishak Aksa
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Hashtable<Integer, Integer> hi = new Hashtable<Integer, Integer>();
for (int i = 0; i < n; i++) {
int m = sc.nextInt();
hi.put(m, 1);
}
Set<Integer> set = hi.keySet();
Integer[] key = set.toArray(new Integer[set.size()]);
Arrays.sort(key);
try {
System.out.println(key[1]);
} catch (Exception e) {
System.out.println("NO");
}
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
public static boolean ok(int []x,int d,int X)
{
for(int i=0;i<x.length;i++)
if(Math.abs(x[i]-X)<d)
return false;
return true;
}
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int ans=0;
int n=sc.nextInt(),d=sc.nextInt();
TreeSet<Integer> set=new TreeSet();
int []x=new int [n];
for(int i=0;i<n;i++)
x[i]=sc.nextInt();
for(int i=0;i<n;i++)
{
int x1=x[i]+d;
if (ok(x,d,x1))
set.add(x1);
x1=x[i]-d;
if (ok(x,d,x1))
set.add(x1);
}
pw.println(set.size());
pw.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public Scanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(s));
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
C909 solver = new C909();
solver.solve(1, in, out);
out.close();
}
static class C909 {
int N;
long MOD = 1_000_000_007;
boolean[] type;
long[][] memo;
long dp(int cmd, int dep) {
// safe if we came out of a statement, we can traverse
if (dep < 0) return 0;
if (cmd == N) return 1;
if (memo[cmd][dep] != -1) return memo[cmd][dep];
boolean safe = cmd == 0 ? true : !type[cmd - 1];
int d = type[cmd] ? 1 : 0;
long ways = 0;
if (!safe) {
// we must use this indentation
ways += dp(cmd + 1, dep + d);
ways %= MOD;
} else {
ways += dp(cmd + 1, dep + d);
ways %= MOD;
ways += dp(cmd, dep - 1);
ways %= MOD;
}
return memo[cmd][dep] = ways;
}
public void solve(int testNumber, FastScanner s, PrintWriter out) {
N = s.nextInt();
type = new boolean[N];
for (int i = 0; i < N; i++) {
type[i] = s.next().charAt(0) == 'f';
}
memo = new long[N][N + 1];
for (long[] a : memo)
Arrays.fill(a, -1);
out.println(dp(0, 0));
}
}
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class LookingForOrder {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int bx = in.nextInt();
int by = in.nextInt();
in.nextLine();
int n = in.nextInt();
int[][] objects = new int[n][2];
for (int i = 0; i < n; i++) {
objects[i][0] = in.nextInt();
objects[i][1] = in.nextInt();
}
int[] cs = new int[n];
for (int i = 0; i < n; i++) {
cs[i] = 2 * time(objects[i], new int[] { bx, by });
}
int[][] cd = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
cd[j][i] = cd[i][j] = time(objects[i], new int[] { bx, by }) + time(objects[j], new int[] { bx, by }) + time(objects[i], objects[j]);
}
}
int maxMask = 1 << n;
int[] dp = new int[maxMask];
int[] path = new int[maxMask];
Arrays.fill(dp, -1);
dp[0] = 0;
for (int g = 1; g < maxMask; g++) {
int min = Integer.MAX_VALUE;
int minPath = 0;
int h = 31;
while ((g & (1 << h)) == 0)
h--;
h++;
int l = 0;
while ((g & (1 << l)) == 0)
l++;
if ((g & 1 << l) > 0) {
int oneleft = g ^ (1 << l);
int t = cs[l] + dp[oneleft];
if (t < min) {
min = t;
minPath = oneleft;
}
for (int j = l + 1; j < h; j++) {
if ((oneleft & 1 << j) > 0) {
int twoleft = oneleft ^ (1 << j);
t = cd[l][j] + dp[twoleft];
if (t < min) {
min = t;
minPath = twoleft;
}
}
}
}
dp[g] = min;
path[g] = minPath;
}
System.out.println(dp[maxMask - 1]);
int previous = maxMask - 1;
int pathElt = path[previous];
System.out.print("0 ");
while (previous > 0) {
int bits = previous - pathElt;
int h = 31;
while ((bits & (1 << h)) == 0)
h--;
int l = 0;
while ((bits & (1 << l)) == 0)
l++;
String el = h == l ? "" + (h + 1) : (h + 1) + " " + (l + 1);
System.out.print(el + " " + 0 + " ");
previous = pathElt;
pathElt = path[pathElt];
}
System.out.println();
}
static int time(int[] a, int[] b) {
int x = b[0] - a[0];
int y = b[1] - a[1];
return x * x + y * y;
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.awt.Point;
import static java.lang.Math.*;
public class CF220A {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
StringTokenizer st = new StringTokenizer(in.readLine());
int[] A = new int[n];
Integer[] B = new Integer[n];
for(int i=0; i<n; i++) {
A[i] = Integer.parseInt(st.nextToken());
B[i] = A[i];
}
Collections.sort(Arrays.asList(B));
int cnt = 0;
for(int i=0; i<n; i++)
if(A[i] != B[i])
cnt++;
System.out.println(cnt <= 2 ? "YES" : "NO");
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
public class A {
/**
* @param args
*/
public static void main(String[] args) {
Scanner s = new Scanner(new InputStreamReader(System.in));
int n = s.nextInt();
int [] ar = new int[n];
for (int i = 0; i < n ; i++) {
ar[i] = s.nextInt();
}
if(ar.length == 1){
System.out.println("NO");
}else{
Arrays.sort(ar);
int num = ar[0];
boolean flag = false;
for (int i = 1; i < ar.length; i++) {
if(ar[i]!= num){
System.out.println(ar[i]);
flag = true;
break;
}
}
if(!flag)
System.out.println("NO");
}
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class C {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
String[] S = in.readLine().split(" ");
int[] A = new int[n];
boolean allOnes = true;
for (int i = 0; i < n; i++) {
A[i] = Integer.parseInt(S[i]);
allOnes &= A[i] == 1;
}
Arrays.sort(A);
if (A[A.length - 1] > 1)
A[A.length - 1] = 1;
else
A[A.length - 1] = 2;
Arrays.sort(A);
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + " ");
System.out.println();
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int numSupply = sc.nextInt();
int dev = sc.nextInt();
int socket = sc.nextInt();
int[] sockInSu = new int[numSupply];
for (int i = 0; i< sockInSu.length; i++) {
sockInSu[i] = sc.nextInt();
}
Arrays.sort(sockInSu);
if (socket >= dev) {
System.out.println(0);
}else {
int count = 0;
for (int i = sockInSu.length-1; i >= 0; i--) {
socket+= sockInSu[i]-1;
count++;
if (socket >= dev) {
System.out.println(count);
break;
}
}
if (socket < dev)
System.out.println(-1);
}
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main implements Runnable {
public void solve() throws IOException {
int N = nextInt();
int M = nextInt();
int B = nextInt();
int[][] burn = new int[B][2];
for(int i = 0; i < B; i++){
burn[i][0] = nextInt();
burn[i][1] = nextInt();
}
int ansx = -1;
int ansy = -1;
int ans = -1;
for(int i = 1; i <= N; i++){
for(int j = 1; j <= M; j++){
int burnAt = Integer.MAX_VALUE;
for(int k = 0; k < B; k++){
int now = distance(i, j, burn[k][0], burn[k][1]);
burnAt = Math.min(burnAt, now);
}
//System.out.println(burnAt + " " + i + " " + j);
if(burnAt >= ans){
ans = burnAt;
ansx = i;
ansy = j;
}
}
}
out.println(ansx + " " + ansy);
}
private int distance(int x, int y, int xx, int yy){
//withour sqrt
return Math.abs(xx - x) + Math.abs(yy - y);
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
//in = new BufferedReader(new InputStreamReader(System.in));
in = new BufferedReader(new FileReader(new File("input.txt")));
out = new PrintWriter(new FileWriter(new File("output.txt")));
tok = null;
solve();
in.close();
out.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.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());
}
PrintWriter out;
BufferedReader in;
StringTokenizer tok;
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.Scanner;
//import java.util.Scanner;
public class SingleWildcard {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input =new Scanner(System.in);
int a = input.nextInt();
int b = input.nextInt();
char[] s1 =new char[a];
s1 = input.next().toCharArray();
char[] s2 = new char[b];
s2 = input.next().toCharArray();
boolean condition = false;
for(int i=0; i<a;i++){
if(s1[i]=='*'){
condition= true;
break;
}
}
if(!condition){
if(match(s1,s2)){
System.out.println("YES");
}
else
System.out.println("NO");
return;
}
else{
int i=0;
if(s1.length-1>s2.length){
System.out.println("NO");
return;
}
while(i<s1.length && i<s2.length && s1[i]==s2[i]){
i++;
}
int j=s2.length-1;
int k = s1.length-1;
while(j>=0 && k>=0 && s1[k]==s2[j] && i<=j){
j--;
k--;
}
//System.out.println(i);
if(i==k && i>=0 && i<s1.length && s1[i]=='*' ){
System.out.println("YES");
return;
}
System.out.println("NO");
}
}
static boolean match(char[] s1,char[] s2){
if(s1.length!=s2.length)return false;
for(int i=0; i<s1.length;i++){
if(s1[i]!=s2[i])return false;
}
return true;
}
}
|
linear
|
1023_A. Single Wildcard Pattern Matching
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.String.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//(new FileReader("input.in"));
StringBuilder out = new StringBuilder();
StringTokenizer tk;
//PrintWriter pw = new PrintWriter("output.out", "UTF-8");
long n = parseLong(in.readLine());
if(n <= 2) System.out.println(n);
else if(n%2 == 1)System.out.println(n*(n-1)*(n-2));
else {
long ans = (n-1)*(n-2)*(n-3);
if(gcd(n*(n-1),n-3)==1) ans = max(ans, n*(n-1)*(n-3));
System.out.println(ans);
}
}
static long gcd(long a,long b) {
return b==0 ? a : gcd(b, a%b);
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
Arrays.sort(a);
int count = 0;
boolean[] used = new boolean[n];
for (int i = 0; i < n; i++) {
if (!used[i]) {
count++;
for (int j = i; j < n; j++) {
if (a[j] % a[i] == 0) {
used[j] = true;
}
}
}
}
out.println(count);
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public FastScanner(String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (st == null || !st.hasMoreElements()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int[] nextIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Amine L
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastInput in, FastOutput out) {
long n = in.nextLong();
long s = in.nextLong();
long cnt = 0;
long res = 0;
for (long i = s; i <= Math.min(s + 200, n); i++) {
long d = i;
int sum = 0;
while (d > 0) {
long l = d % 10;
sum += l;
d /= 10;
}
if ((i - sum) >= s) {
cnt++;
}
}
long tmp = n - Math.min(n, s + 200);
if (tmp < 0) tmp = 0;
cnt += tmp;
out.println(cnt);
}
}
static class FastInput {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastInput.SpaceCharFilter filter;
public FastInput(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class FastOutput {
private final PrintWriter writer;
public FastOutput(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public FastOutput(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
public class Solution {
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws Exception{
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int)in.nval;
in.nextToken();
String st = in.sval;
char[] a = new char[n];
for (int i = 0; i<n; i++)
a[i] = st.charAt(i);
int kH = 0;
int kT = 0;
for (int i =0; i<n; i++)
if (a[i] == 'T') kT++;
else kH++;
int kol = 0;
int min = Integer.MAX_VALUE;
int poz;
for (int i=0; i<n; i++)
{
kol = 0;
if (a[i] == 'T') {
for (int j = 0; j<kT; j++){
poz = (i+j)%n;
if (a[poz] == 'H') kol++;
}
if (kol < min) min = kol;
}
else {
for (int j = 0; j<kH; j++){
poz = (i+j)%n;
if (a[poz] == 'T') kol++;
}
if (kol < min) min = kol;
}
}
out.print(min);
out.flush();
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import org.omg.PortableServer.AdapterActivator;
import java.io.*;
import java.lang.reflect.Array;
import java.net.CookieHandler;
import java.util.*;
import java.math.*;
import java.lang.*;
import java.util.concurrent.LinkedBlockingDeque;
import static java.lang.Math.*;
public class TaskA implements Runnable {
long m = (int)1e9+7;
PrintWriter w;
InputReader c;
public void run() {
c = new InputReader(System.in);
w = new PrintWriter(System.out);
int n = c.nextInt();
int a[] = scanArrayI(n);
int maxtime = Integer.MAX_VALUE,ind = -1;
for(int i=0;i<n;i++){
int time = Integer.MAX_VALUE;
if(a[i]<i+1)
time = i;
else{
time = (int)ceil((a[i] - i)/(double)n) * n + i;
}
if(time<maxtime){
maxtime = time;
ind = i;
}
}
w.println(ind+1);
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();
}
}
|
nlogn
|
996_B. World Cup
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class ProblemD
{
static int mod = (int) (1e9+7);
static InputReader in;
static PrintWriter out;
static void solve()
{
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int n = in.nextInt();
int r = in.nextInt();
double[] x = new double[n];
double[] y = new double[n];
for(int i = 0; i < n; i++){
int xx = in.nextInt();
x[i] = xx;
y[i] = r;
for(int j = 0; j < i; j++){
double delx = Math.abs(x[i] - x[j]);
//debug(delx);
if(delx <= 2 * r){
double tmp = 4 * r * r - delx * delx;
tmp = Math.sqrt(tmp);
tmp = y[j] + tmp;
y[i] = Math.max(y[i], tmp);
}
}
out.print(y[i] + " ");
}
out.close();
}
public static void main(String[] args)
{
new Thread(null ,new Runnable(){
public void run(){
try{
solve();
} catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<26).start();
}
static class Pair implements Comparable<Pair>
{
long x,y;
Pair (long x,long y)
{
this.x = x;
this.y = y;
}
public int compareTo(Pair o)
{
return Long.compare(this.x,o.x);
//return 0;
}
public boolean equals(Object o)
{
if (o instanceof Pair)
{
Pair p = (Pair)o;
return p.x == x && p.y==y;
}
return false;
}
@Override
public String toString()
{
return x + " "+ y ;
}
/*public int hashCode()
{
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}*/
}
static long add(long a,long b){
long x=(a+b);
while(x>=mod) x-=mod;
return x;
}
static long sub(long a,long b){
long x=(a-b);
while(x<0) x+=mod;
return x;
}
static long mul(long a,long b){
long x=(a*b);
while(x>=mod) x-=mod;
return x;
}
static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long gcd(long x,long y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static int gcd(int x,int y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static long pow(long n,long p,long m)
{
long result = 1;
if(p==0){
return 1;
}
while(p!=0)
{
if(p%2==1)
result *= n;
if(result >= m)
result %= m;
p >>=1;
n*=n;
if(n >= m)
n%=m;
}
return result;
}
static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static void debug(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.Scanner;
public class D {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double a = in.nextDouble();
double v = in.nextDouble();
double l = in.nextDouble();
double d = in.nextDouble();
double w = in.nextDouble();
double ans = 0;
double maxSpeedBySign = Math.sqrt(2 * a * d);
double speedAtSign = -1;
if (v <= w) {
if (maxSpeedBySign <= v) {
ans += Math.sqrt(2 * d / a);
speedAtSign = maxSpeedBySign;
} else {
ans += v / a;
double distanceLeftTillSign = d - v * v / a / 2;
ans += distanceLeftTillSign / v;
speedAtSign = v;
}
} else {
if (maxSpeedBySign <= w) {
ans += Math.sqrt(2 * d / a);
speedAtSign = maxSpeedBySign;
} else {
double S = d / 2 - w * w / 4 / a;
double X = d - S;
double speed = Math.sqrt(2 * a * X);
if (speed <= v) {
ans += Math.sqrt(2 * X / a);
ans += (speed - w) / a;
speedAtSign = w;
} else {
double distanceToAc = v * v / a / 2;
double distanceToDe = (v * v - w * w) / a / 2;
ans += Math.sqrt(2 * distanceToAc / a);
ans += (d - distanceToAc - distanceToDe) / v;
ans += (v - w) / a;
}
speedAtSign = w;
}
}
l -= d;
double timeToGetMaxSpeed = (v - speedAtSign) / a;
double timeToReachEnd = (-2 * speedAtSign + Math.sqrt(4 * speedAtSign
* speedAtSign + 8 * a * l))
/ 2 / a;
if (timeToGetMaxSpeed < timeToReachEnd) {
ans += timeToGetMaxSpeed;
double distanceCoveredToMaxSpeed = speedAtSign * timeToGetMaxSpeed
+ 0.5 * a * timeToGetMaxSpeed * timeToGetMaxSpeed;
l -= distanceCoveredToMaxSpeed;
ans += l / v;
} else {
ans += timeToReachEnd;
}
System.out.println(ans);
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Main iq = new Main();
Scanner sc = new Scanner(System.in);
int n;
n = sc.nextInt();
int[] naturalNumbers = new int[n];
for (int i = 0; i < naturalNumbers.length; i++) {
naturalNumbers[i] = sc.nextInt();
}
System.out.println(iq.diffInEvenness(n, naturalNumbers));
}
public int diffInEvenness(int n, int[] naturalNumbers) {
int even, odd, lastEvenIndex, lastOddIndex;
even = odd = lastEvenIndex = lastOddIndex = 0;
for (int i = 0; i < naturalNumbers.length; i++) {
if((naturalNumbers[i] % 2) == 0) {
even++;
lastEvenIndex = i + 1;
}
else {
odd++;
lastOddIndex = i + 1;
}
}
return (even > odd ? lastOddIndex : lastEvenIndex);
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class B {
static Set<Integer> A;
static Set<Integer> B;
static TreeSet<Integer> ts;
static int a;
static int b;
static boolean noAns;
public static void main(String[] args) throws Exception{
int n = readInt();
a = readInt();
b = readInt();
ts = new TreeSet<Integer>();
int[] table = new int[n];
for(int i = 0; i<n; i++){
table[i] = readInt();
ts.add(table[i]);
}
A = new HashSet<Integer>();
B = new HashSet<Integer>();
noAns = false;
for(Integer cur:ts){
boolean fitsA = false;
boolean fitsB = false;
if(A.contains(cur) || B.contains(cur)){
continue;
}
if(ts.contains(a-cur)){
fitsA = true;
}
if(ts.contains(b-cur)){
fitsB = true;
}
if(fitsA && fitsB){
continue;
}
else if(!(fitsA || fitsB)){
noAns = true;
}
else if(fitsA){
tour(cur, false);
}
else if(fitsB){
tour(cur, true);
}
}
for(Integer cur:ts){
if(A.contains(cur) || B.contains(cur)){
continue;
}
else{
A.add(cur);
}
}
if(!noAns){
System.out.println("YES");
StringBuilder sb = new StringBuilder();
for(int i = 0; i< n; i++){
if(A.contains(table[i])){
sb.append("0");
}
else{
sb.append("1");
}
sb.append(" ");
}
System.out.println(sb);
}
else{
System.out.println("NO");
}
}
static void tour(Integer cur, boolean bb){
if(A.contains(cur) || B.contains(cur)){
return;
}
if(bb){
B.add(cur);
B.add(b-cur);
if(ts.contains(a-cur)){
B.add(a-cur);
if(ts.contains(b-(a-cur))){
tour(b-(a-cur), true);
}
else{
noAns = true;
}
}
if(ts.contains(a-(b-cur))){
B.add(a-(b-cur));
if(ts.contains(b-(a-(b-cur)))){
tour(b-(a-(b-cur)), true);
}
else{
noAns = true;
}
}
}
else{
A.add(cur);
A.add(a-cur);
if(ts.contains(b-cur)){
A.add(b-cur);
if(ts.contains(a-(b-cur))){
tour(a-(b-cur), false);
}
else{
noAns = true;
}
}
if(ts.contains(b-(a-cur))){
A.add(b-(a-cur));
if(ts.contains(a-(b-(a-cur)))){
tour(a-(b-(a-cur)), false);
}
else{
noAns = true;
}
}
}
}
static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st = new StringTokenizer(" ");
static String readString() throws Exception{
while(!st.hasMoreTokens()){
st = new StringTokenizer(stdin.readLine());
}
return st.nextToken();
}
static int readInt() throws Exception {
return Integer.parseInt(readString());
}
static long readLong() throws Exception {
return Long.parseLong(readString());
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.StringJoiner;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] line = reader.readLine().split(" ");
int w = Integer.valueOf(line[0]);
int h = Integer.valueOf(line[1]);
int n = Integer.valueOf(line[2]);
Request[] requests = new Request[n];
for (int i = 0; i < n; i++) {
line = reader.readLine().split(" ");
requests[i] = new Request(line[0], Integer.valueOf(line[1]));
}
for (long e : solve(h, w, requests))
System.out.println(e);
// int w = 200000, h = 200000, n = 400000;
// Request[] requests = generate(w, h, n);
//
// long start = System.currentTimeMillis();
// solve(h, w, requests);
// long end = System.currentTimeMillis();
//
// System.out.println("Time: " + (end - start) + " ms");
}
private static Request[] generate(int w, int h, int n) {
Request[] requests = new Request[n];
Random rnd = new Random();
for (int i = 0; i < n; i++) {
requests[i] = rnd.nextBoolean() ? new Request("V", rnd.nextInt(w)) : new Request("H", rnd.nextInt(h));
}
return requests;
}
private static long[] solve(int h, int w, Request[] requests) {
TreeSet<Integer> hTree = new TreeSet<>();
TreeSet<Integer> wTree = new TreeSet<>();
Queue<CoordinateWithSize> hHeap = new PriorityQueue<>();
Queue<CoordinateWithSize> wHeap = new PriorityQueue<>();
hTree.add(0);
hTree.add(h);
wTree.add(0);
wTree.add(w);
hHeap.add(new CoordinateWithSize(0, h));
wHeap.add(new CoordinateWithSize(0, w));
long[] res = new long[requests.length];
for (int i = 0; i < requests.length; i++) {
Request request = requests[i];
switch (request.type) {
case "H": {
if (!hTree.contains(request.coordinate)) {
int higher = hTree.higher(request.coordinate);
int lower = hTree.lower(request.coordinate);
hHeap.add(new CoordinateWithSize(lower, request.coordinate - lower));
hHeap.add(new CoordinateWithSize(request.coordinate, higher - request.coordinate));
hTree.add(request.coordinate);
}
break;
}
case "V": {
if (!wTree.contains(request.coordinate)) {
int higher = wTree.higher(request.coordinate);
int lower = wTree.lower(request.coordinate);
wHeap.add(new CoordinateWithSize(lower, request.coordinate - lower));
wHeap.add(new CoordinateWithSize(request.coordinate, higher - request.coordinate));
wTree.add(request.coordinate);
}
break;
}
default:
throw new IllegalStateException("Unknown type [type=" + request.type + "]");
}
while (true) {
CoordinateWithSize c = hHeap.peek();
if (hTree.higher(c.coordinate) - c.coordinate == c.size)
break;
hHeap.remove();
}
while (true) {
CoordinateWithSize c = wHeap.peek();
if (wTree.higher(c.coordinate) - c.coordinate == c.size)
break;
wHeap.remove();
}
res[i] = 1L * hHeap.peek().size * wHeap.peek().size;
}
return res;
}
private static class CoordinateWithSize implements Comparable<CoordinateWithSize> {
private final int coordinate;
private final int size;
public CoordinateWithSize(int coordinate, int size) {
this.coordinate = coordinate;
this.size = size;
}
@Override public int compareTo(CoordinateWithSize o) {
return Integer.compare(o.size, size);
}
}
private static class Request {
private final String type;
private final int coordinate;
public Request(String type, int coordinate) {
this.type = type;
this.coordinate = coordinate;
}
}
}
|
nlogn
|
527_C. Glass Carving
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
public void solve() {
int n = ni();
int a = ni();
int b = ni();
long ans = 0;
HashMap<Long, Long> m = new HashMap<>();
HashMap<String, Long> s = new HashMap<>();
for (int i = 0; i < n; i++) {
ni();
long vx = ni();
long vy = ni();
long v = (long) a * vx - vy;
String k = vx + "|" + vy;
long cs = s.getOrDefault(k, 0L);
long c = m.getOrDefault(v, 0L);
ans += c - cs;
m.put(v, c + 1);
s.put(k, cs + 1);
}
write (ans * 2 + "\n");
}
public static void main(String[] args) {
Main m = new Main();
m.solve();
try {
m.out.close();
} catch (IOException e) {}
}
BufferedReader in;
BufferedWriter out;
StringTokenizer tokenizer;
public Main() {
in = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter(System.out));
}
public String n() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(in.readLine());
} catch (IOException e) {}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(n());
}
public long nl() {
return Long.parseLong(n());
}
public void write(String s) {
try {
out.write(s);
} catch (IOException e) {}
}
}
|
linear
|
975_D. Ghosts
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {new Main().run();}
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
void run(){
out.println(work());
out.flush();
}
long mod=1000000007;
long gcd(long a,long b) {
return b==0?a:gcd(b,a%b);
}
long work() {
int n=in.nextInt();
int m=in.nextInt();
String str=in.next();
long[] dp=new long[1<<m];
long[][] cnt=new long[m][m];
long[] rec=new long[1<<m];//记录每次移动的一位怎加的值,减少重复计算
for(int i=1;i<n;i++) {
int n1=str.charAt(i-1)-'a';
int n2=str.charAt(i)-'a';
cnt[n1][n2]++;
cnt[n2][n1]++;
}
for(int i=1;i<1<<m;i++) {
dp[i]=9999999999L;
long v=0;
int b=0;//最低位的1
for(int j=0;j<m;j++) {
if((i&(1<<j))>0) {
b=j;
break;
}
}
for(int j=0;j<m;j++) {
if((i&(1<<j))==0) {
v+=cnt[b][j];
}else {
if(b!=j)v-=cnt[b][j];
}
}
v+=rec[i-(1<<b)];
for(int j=0;j<m;j++) {
if((i&(1<<j))>0) {
dp[i]=Math.min(dp[i], dp[i-(1<<j)]+v);
}
}
rec[i]=v;
}
return dp[(1<<m)-1];
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
if(st==null || !st.hasMoreElements())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main{
BufferedReader in;
StringTokenizer str = null;
PrintWriter out;
private String next() throws Exception{
if (str == null || !str.hasMoreElements())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
private int nextInt() throws Exception{
return Integer.parseInt(next());
}
int []x,y;
int n;
int []dp, prev;
public void run() throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int xs = nextInt();
int ys = nextInt();
n = nextInt();
x = new int[n];
y = new int[n];
for(int i=0;i<n;i++){
x[i] = nextInt();
y[i] = nextInt();
}
int one[] = new int[n];
for(int i=0;i<n;i++){
one[i] = dist(xs, ys, x[i], y[i]);
}
int two[][] = new int[n][n];
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
two[i][j] = two[j][i] = dist(xs, ys, x[i], y[i]) + dist(x[i], y[i], x[j], y[j]) + dist(xs, ys, x[j], y[j]);
}
}
dp = new int[1<<n];
Arrays.fill(dp, Integer.MAX_VALUE/2);
dp[0] = 0;
prev = new int[1<<n];
Arrays.fill(prev, -1);
for(int mask=1;mask<(1<<n);mask++){
int i = 0;
while((mask & (1<<i)) == 0) i++;
dp[mask] = dp[mask ^ (1<<i)] + 2*one[i];
prev[mask] = i+1;
for(int j=i+1;j<n;j++){
if ((mask & (1<<j)) > 0) {
if (dp[mask] > dp[mask ^ (1<<i) ^ (1<<j)] + two[i][j]) {
dp[mask] = dp[mask ^ (1<<i) ^ (1<<j)] + two[i][j];
prev[mask] = 100 * (i+1) + (j+1);
}
}
}
}
out.println(dp[(1<<n)-1]);
out.print(0 + " ");
int cur = (1<<n)-1;
int i = 0, j = 0;
while(cur > 0) {
i = prev[cur]/100;
j = prev[cur]%100;
if (i > 0) {
cur^=1<<(i-1);
out.print(i + " ");
}
if (j > 0) {
cur^=1<<(j-1);
out.print(j + " ");
}
out.print(0 + " ");
}
// if (i == 0 || j == 0) {
// out.println(0);
// }
out.close();
}
private String bit2str(int mask, int n) {
String s = "";
for(int i=0;i<n;i++){
if ((mask & (1<<i)) > 0){
s+="1";
}else{
s+="0";
}
}
while(s.length() < n)
s+="0";
return new StringBuilder(s).reverse().toString();
}
private int dist(int x1, int y1, int x2, int y2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}
public static void main(String args[]) throws Exception{
new Main().run();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int xs = sc.nextInt();
int ys = sc.nextInt();
int n = sc.nextInt();
int[]x = new int[n], y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
int[]single = new int[n];
int[][]pair = new int[n][n];
for (int i = 0; i < n; i++) {
single[i] = 2*((x[i]-xs)*(x[i]-xs)+(y[i]-ys)*(y[i]-ys));
}
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
pair[i][j] = (x[i]-xs)*(x[i]-xs)+(y[i]-ys)*(y[i]-ys)+(x[j]-xs)*(x[j]-xs)+(y[j]-ys)*(y[j]-ys)+(x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]);
}
}
int[]best = new int[1 << n], prev = new int[1 << n];
for (int mask = 1; mask < (1 << n); mask++) {
int i = 0;
while ((mask & (1 << i))==0)
i++;
best[mask] = best[mask ^ (1 << i)]+single[i];
prev[mask] = i+1;
for (int j = i+1; j < n; j++) {
if ((mask & (1 << j)) != 0) {
int temp = best[mask ^ (1 << i) ^ (1 << j)]+pair[i][j];
if (temp < best[mask]) {
best[mask] = temp;
prev[mask] = (i+1)*100+(j+1);
}
}
}
}
System.out.println(best[(1 << n) - 1]);
System.out.print("0 ");
int cur = (1 << n) - 1;
while (cur > 0) {
int a = prev[cur] % 100;
int b = prev[cur] / 100;
if (a > 0) {
System.out.print(a+" ");
cur ^= 1 << (a-1);
}
if (b > 0) {
System.out.print(b+" ");
cur ^= 1 << (b-1);
}
System.out.print(0+" ");
}
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
long MAX = 100000L, MOD = 1000000007L, INF = (long) 1e18;
boolean isValid(int x, int y, int n, int m){
return x>=0 && y>=0 && x<n && y<m;
}
void solve(int TC) throws Exception {
helper hp = new helper(MOD, (int)MAX);
hp.initIO("input.txt", "output.txt");
int n = hp.nextInt(), m = hp.nextInt();
boolean[][] a = new boolean[n][m];
int k = hp.nextInt();
ArrayDeque<int[]> q = new ArrayDeque<>();
for(int i=0;i<k;i++){
int x = hp.nextInt() - 1;
int y = hp.nextInt() - 1;
a[x][y] = true;
q.add(new int[]{x,y});
}
int lastX = 0,lastY = 0;
int[] dx = new int[]{1,-1,0,0};
int[] dy = new int[]{0,0,1,-1};
while(!q.isEmpty()){
int[] X = q.pollFirst();
for(int i=0;i<4;i++){
int x = X[0] + dx[i];
int y = X[1] + dy[i];
if(isValid(x,y,n,m) && !a[x][y]){
a[x][y] = true;
lastX = x;
lastY = y;
q.add(new int[]{x,y});
}
}
}
hp.println((lastX+1) + " " + (lastY+1)); hp.flush();
}
boolean TestCases = false;
public static void main(String[] args) throws Exception { new Main().run(); }
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
static void dbg(Object... o){System.err.println(Arrays.deepToString(o));}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
int T = TestCases ? ni() : 1;
for(int t=1;t<=T;t++) solve(t);
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
void p(Object o) { out.print(o); }
void pn(Object o) { out.println(o); }
void pni(Object o) { out.println(o);out.flush(); }
double PI = 3.141592653589793238462643383279502884197169399;
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();
}
}
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();
}
}
double nd() { return Double.parseDouble(ns()); }
char nc() { return (char)skip(); }
int BUF_SIZE = 1024 * 8;
byte[] inbuf = new byte[BUF_SIZE];
int lenbuf = 0, ptrbuf = 0;
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++];
}
boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))) {
sb.appendCodePoint(b); b = readByte();
} return sb.toString();
}
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);
}
void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}
class helper {
final long MOD;
final int MAXN;
final Random rnd;
public helper(long mod, int maxn) {
MOD = mod;
MAXN = maxn;
rnd = new Random();
}
static final int BUFSIZE = 1 << 20;
static byte[] buf;
static int index, total;
static InputStream in;
static BufferedWriter bw;
public void initIO(InputStream is, OutputStream os) {
try {
in = is;
bw = new BufferedWriter(new OutputStreamWriter(os));
buf = new byte[BUFSIZE];
} catch (Exception e) {
}
}
public void initIO(String inputFile, String outputFile) {
try {
in = new FileInputStream(inputFile);
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFile)));
buf = new byte[BUFSIZE];
} catch (Exception e) {
e.printStackTrace();
}
}
private int scan() throws Exception {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public String next() throws Exception {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan())
sb.append((char) c);
return sb.toString();
}
public int nextInt() throws Exception {
int c, val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public long nextLong() throws Exception {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public long pow(long base, long exp, long MOD) {
base %= MOD;
long ret = 1;
while (exp > 0) {
if ((exp & 1) == 1) ret = ret * base % MOD;
base = base * base % MOD;
exp >>= 1;
}
return ret;
}
public void println(Object a) throws Exception {
bw.write(a.toString()+"\n");
}
public void print(Object a) throws Exception {
bw.write(a.toString());
}
public void flush() throws Exception {
bw.flush();
}
public static int[] sieve;
public static ArrayList<Integer> primes;
public void setSieve() {
primes = new ArrayList<>();
sieve = new int[MAXN];
int i, j;
for (i = 2; i < MAXN; ++i)
if (sieve[i] == 0) {
primes.add(i);
for (j = i; j < MAXN; j += i) {
sieve[j] = i;
}
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.TreeMap;
import java.util.Map;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Ribhav
*/
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);
CGlassCarving solver = new CGlassCarving();
solver.solve(1, in, out);
out.close();
}
static class CGlassCarving {
public void solve(int testNumber, FastReader s, PrintWriter out) {
TreeMap<Long, Integer> mapH = new TreeMap<>();
TreeMap<Long, Integer> mapV = new TreeMap<>();
TreeMap<Long, Integer> hDiff = new TreeMap<>();
TreeMap<Long, Integer> vDiff = new TreeMap<>();
long width = s.nextInt();
long height = s.nextInt();
mapH.put(0L, 1);
mapV.put(0L, 1);
mapV.put(width, 1);
mapH.put(height, 1);
vDiff.put(width, 1);
hDiff.put(height, 1);
long maxV = height;
long maxH = width;
int n = s.nextInt();
for (int i = 0; i < n; i++) {
char ch = s.nextCharacter();
long cut = s.nextInt();
if (ch == 'H') {
Long next = mapH.higherKey(cut);
Long prev = mapH.lowerKey(cut);
Long diff = next - prev;
int freq = hDiff.get(diff);
if (freq == 1) {
hDiff.remove(diff);
} else {
hDiff.put(diff, freq - 1);
}
hDiff.put(next - cut, hDiff.getOrDefault(next - cut, 0) + 1);
hDiff.put(cut - prev, hDiff.getOrDefault(cut - prev, 0) + 1);
mapH.put(cut, mapH.getOrDefault(cut, 0) + 1);
} else {
Long next = mapV.higherKey(cut);
Long prev = mapV.lowerKey(cut);
Long diff = next - prev;
int freq = vDiff.get(diff);
if (freq == 1) {
vDiff.remove(diff);
} else {
vDiff.put(diff, freq - 1);
}
vDiff.put(next - cut, vDiff.getOrDefault(next - cut, 0) + 1);
vDiff.put(cut - prev, vDiff.getOrDefault(cut - prev, 0) + 1);
mapV.put(cut, mapV.getOrDefault(cut, 0) + 1);
}
out.println(hDiff.lastKey() * vDiff.lastKey());
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(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 char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
nlogn
|
527_C. Glass Carving
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A992{
long mod = 1000000007L;
private void solve() throws Exception {
long x = nextLong();
long k = nextLong();
if(x == 0) {
out.println(0);
return;
}
x = x%mod;
long res = (((x*pow(2,k+1))%mod + (mod-pow(2,k))%mod)%mod+1)%mod;
out.println(res);
}
long pow(long m, long n){
long res = 1;
while(n > 0){
if(n % 2 == 1)res = (res*m)%mod;
m = (m*m)%mod;
n = n/2;
}
return res;
}
public static void main(String[] args) {
(new A992()).run();
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer tokenizer;
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private float nextFloat() throws IOException {
return Float.parseFloat(nextToken());
}
private String nextLine() throws IOException {
return new String(in.readLine());
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class E {
static int n;
static int m;
static int[][][] DP;
static int[] dx = { 0, 0, 1, -1 };
static int[] dy = { 1, -1, 0, 0 };
static int inf = 1000000;
public static int get(int x, int current, int last) {
if (x == n) {
if (last == 0)
return 0;
else
return -inf;
}
if (DP[x][current][last] != -1)
return DP[x][current][last];
int max = 0;
for (int mask = 0; mask < (1 << m); mask++) {
int tempLast = last;
int tempCurrent = current;
int tempNext = (1 << m) - 1;
for (int i = 0; i < m; i++)
if ((mask & (1 << i)) != 0) {
if (i > 0)
tempCurrent &= ~(1 << (i - 1));
if (i < m - 1)
tempCurrent &= ~(1 << (i + 1));
tempNext &= ~(1 << (i));
tempLast &= ~(1 << (i));
}
if (tempLast != 0)
continue;
max = Math.max(
max,
m - Integer.bitCount(mask)
+ get(x + 1, tempNext, tempCurrent & ~mask));
}
return DP[x][current][last] = max;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int y = in.nextInt();
n = Math.max(x, y);
m = Math.min(x, y);
DP = new int[n][1 << m][1 << m];
for (int i = 0; i < n; i++)
for (int j = 0; j < (1 << m); j++)
Arrays.fill(DP[i][j], -1);
System.out.println(get(0, (1 << m) - 1, 0));
}
}
|
np
|
112_E. Petya and Spiders
|
CODEFORCES
|
//never leave a uncompleted question in this file, always remove the code after submitting it.
import java.io.*;
import java.util.*;
public class run{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
long n = in.nextInt();
long k = in.nextInt();
long ans = (-3 + (long)Math.sqrt(9+8*(n+k)))/2;
System.out.println(n-ans);
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Solution1{
static class Node{
int start,end;
Node(int start, int end){
this.start=start;
this.end=end;
}
public String toString(){
return start+" "+end;
}
}
public static void sameSumBlock(int a[],int n){
HashMap<Long,ArrayList<Node>> map=new HashMap<>();
long sum;
for(int i=0;i<n;i++){
sum=0;
for(int j=i;j<n;j++){
sum+=a[j];
if(!map.containsKey(sum))
map.put(sum,new ArrayList<>());
map.get(sum).add( new Node(i+1, j+1) );
}
}
//for(Map.Entry<Long,ArrayList<Node>> pair: map.entrySet())
//System.out.println(pair.getKey()+" "+pair.getValue());
int max=0; LinkedList<Node> list=new LinkedList<>();
for(Map.Entry<Long,ArrayList<Node>> pair: map.entrySet()){
ArrayList<Node> arr=pair.getValue();
Collections.sort(arr, (Node x, Node y)->{ return x.end-y.end; });
int count=0,end=0;
LinkedList<Node> temp=new LinkedList<>();
for(Node item: arr){
if(end<item.start){
end=item.end;
count+=1;
temp.add(new Node(item.start, item.end));
}
}
if(count>max){
max=count;
list=temp;
}
}
System.out.println(max);
for(Node item: list)
System.out.println(item.start+" "+item.end);
}
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=in.nextInt();
sameSumBlock(a,n);
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
static class Scanner {
StreamTokenizer in;
boolean forceMode = false;
Scanner(InputStream is, String codePage, boolean forceMode) {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(is)));
if (!forceMode) {
in.resetSyntax();
in.wordChars(33, 255);
in.whitespaceChars(0, 32);
}
}
Scanner(InputStream is, String codePage) {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(is)));
if (!forceMode) {
in.resetSyntax();
in.wordChars(33, 255);
in.whitespaceChars(0, 32);
}
}
String next() {
try {
in.nextToken();
return in.sval;
} catch (Exception e) {
throw new Error();
}
}
int nextInt() {
if (forceMode) {
try {
in.nextToken();
return (int) in.nval;
} catch (Exception e) {
throw new Error();
}
} else {
return Integer.parseInt(next());
}
}
long nextLong() {
if (forceMode) {
throw new Error("No long at force mod!");
} else {
return Long.parseLong(next());
}
}
double nextDouble() {
if (forceMode) {
try {
in.nextToken();
return in.nval;
} catch (Exception e) {
throw new Error();
}
} else {
return Double.parseDouble(next());
}
}
}
static class Assertion {
static void checkRE(boolean e) {
if (!e) {
throw new Error();
}
}
static void checkTL(boolean e) {
if (!e) {
int idx = 1;
while (idx > 0) {
idx++;
}
}
}
}
Scanner in;
PrintWriter out;
class Int implements Comparable<Int> {
int value;
int pos;
public Int(int value, int pos) {
this.value = value;
this.pos = pos;
}
@Override
public int compareTo(Int second) {
if (this.value == second.value) {
return this.pos - second.pos;
} else {
return this.value - second.value;
}
}
}
void solve() {
int n = in.nextInt();
Int ar[] = new Int[n];
for (int i = 0; i < ar.length; i++) {
ar[i] = new Int(in.nextInt(), i);
}
Arrays.sort(ar);
int cnt = 0;
for (int i = 0; i < ar.length; i++) {
if (ar[i].value!=ar[ar[i].pos].value) {
cnt++;
}
}
if (cnt == 2 || cnt == 0) {
out.println("YES");
} else {
out.println("NO");
}
}
final static String fileName = "";
void run() {
// try {
// in = new Scanner(new FileInputStream(fileName + ".in"), "ISO-8859-1");
// out = new PrintWriter(fileName + ".out", "ISO-8859-1");
// } catch (FileNotFoundException e) {
// throw new Error(e);
//
// } catch (UnsupportedEncodingException e) {
// throw new Error(e);
// }
in = new Scanner(System.in, "");
out = new PrintWriter(System.out);
try {
solve();
} catch (Exception e) {
throw new Error(e);
} finally {
out.close();
}
}
public static void main(String[] args) {
new Main().run();
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
/**
* Created by Alyssa Herbst on 9/14/19 9:05 AM.
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class B {
static StringBuilder sb;
static int N;
static int[] A;
static boolean[] B;
public static void main(String[] args) {
FastScanner sc = new FastScanner();
//Scanner sc = new Scanner(System.in);
sb = new StringBuilder();
N = sc.nextInt();
A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = sc.nextInt();
}
Arrays.sort(A);
B = new boolean[N];
int count = 0;
for (int i = 0; i < A.length; i++) {
if(B[i]) {
continue;
}
else {
count++;
B[i] = true;
}
for (int j = i + 1; j < A.length; j++) {
if(A[j] % A[i] == 0) {
B[j] = true;
}
}
}
sb.append(count);
System.out.println(sb);
}
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[] readIntBrray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
long[] readLongBrray(int n) {
long[] a = new long[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextLong();
}
return a;
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Scanner;
public class Problem2 implements Runnable {
public void run() {
Scanner scanner = new Scanner(System.in);
PrintWriter writer = new PrintWriter(System.out);
long n = scanner.nextLong();
long k = scanner.nextLong();
long count = 1;
if (n == 1) {
writer.println(0);
writer.close();
return;
}
if (k >= n) {
writer.println(1);
writer.close();
return;
}
long answer = 0;
while (k > 1) {
if (k > 2000) {
if (count + k <= n) {
if (count + (k - 1 + k - 1000) * 500 <= n) {
count += (k - 1 + k - 1000) * 500;
k -= 1000;
answer += 1000;
}
}
}
if ((count + k - 1) <= n) {
count += (k - 1);
answer++;
}
if (count + k - 100000000000000000l > n) {
k -= 99999999999999999l;
}
if (count + k - 10000000000000000l > n) {
k -= 9999999999999999l;
}
if (count + k - 1000000000000000l > n) {
k -= 999999999999999l;
}
if (count + k - 100000000000000l > n) {
k -= 99999999999999l;
}
if (count + k - 10000000000000l > n) {
k -= 9999999999999l;
}
if (count + k - 1000000000000l > n) {
k -= 999999999999l;
}
if (count + k - 100000000000l > n) {
k -= 99999999999l;
}
if (count + k - 10000000000l > n) {
k -= 9999999999l;
}
if (count + k - 1000000000l > n) {
k -= 999999999l;
}
if (count + k - 100000000l > n) {
k -= 99999999l;
}
if (count + k - 10000000l > n) {
k -= 9999999l;
}
if (count + k - 1000000l > n) {
k -= 999999l;
}
if (count + k - 100000l > n) {
k -= 99999l;
}
if (count + k - 10000l > n) {
k -= 9999l;
}
if (count + k - 1000l > n) {
k -= 999l;
}
if (count + k - 100l > n) {
k -= 99l;
}
if (n - count + 1 < k) {
k = n - count + 1;
} else {
k--;
}
}
if (count == n) {
writer.println(answer);
} else {
writer.println(-1);
}
writer.close();
}
public static void main(String[] args) {
new Problem2().run();
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Vector;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Stack;
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);
TaskF2 solver = new TaskF2();
solver.solve(1, in, out);
out.close();
}
static class TaskF2 {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
HashMap<Integer, Stack<Interval>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += a[j];
if (map.containsKey(sum) == false) {
map.put(sum, new Stack<>());
}
Stack<Interval> stack = map.get(sum);
if (stack.isEmpty() || stack.get(stack.size() - 1).r < i) {
stack.push(new Interval(i, j));
} else if (stack.get(stack.size() - 1).r >= j) {
stack.pop();
stack.push(new Interval(i, j));
}
}
}
Stack<Interval> best = new Stack<>();
for (Stack<Interval> stack : map.values()) {
if (best.size() < stack.size()) {
best = stack;
}
}
out.println(best.size());
for (Interval i : best) {
out.println((i.l + 1) + " " + (i.r + 1));
}
}
class Interval {
int l;
int r;
Interval(int l, int r) {
this.l = l;
this.r = r;
}
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
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 nextInt() {
int c = read();
while (isWhitespace(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 (!isWhitespace(c));
return res * sgn;
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.*;
public class Main {
static class Node implements Comparable<Node>{
public int l,r;
public long s;
Node(int l,int r,long s){
this.l=l;
this.r=r;
this.s=s;
}
public int compareTo(Node o) {
if(o.s==s){
if(r>o.r) return 1;
else if(r==o.r) {
return 0;
}
else return -1;
} else if(s>o.s){
return 1;
} else {
return -1;
}
}
}
static long[] sum=new long[1550];
public static void main(String[] args) {
TreeMap<Long, ArrayList<Node> > mp = new TreeMap<>();
Scanner cin = new Scanner(System.in);
int N=cin.nextInt();
for(int i=1;i<=N;i++){
int x=cin.nextInt();
sum[i]=sum[i-1]+x;
}
//System.out.println("here");
ArrayList<Node> arr = new ArrayList<>();
for(int l=1;l<=N;l++){
for(int r=l;r<=N;r++){
arr.add(new Node(l,r,sum[r]-sum[l-1]));
}
}
Collections.sort(arr);
for(int i=0;i<arr.size();i++){
ArrayList<Node> a=mp.get(arr.get(i).s);
if(a==null) {
a=new ArrayList<>();
mp.put(arr.get(i).s,a);
}
a.add(arr.get(i));
}
int mx=-1;
long mxv=-1;
Iterator<Long> it=mp.keySet().iterator();
while(it.hasNext()){
int ans=0,t=0;
long v=it.next();
ArrayList<Node> vec= mp.get(v);
for(int i=0;i<vec.size();i++){
if(t<vec.get(i).l){
ans++;
t=vec.get(i).r;
}
}
//
if(ans>mx){
mx=ans;
mxv=v;
// System.out.println(mxv);
}
}
ArrayList<Node> vec=mp.get(mxv);
System.out.println(mx);
int t=0;
for(int i=0;i<vec.size();i++){
// System.out.println(vec.get(i).l+" "+vec.get(i).r);
// System.out.println("h");
if(t<vec.get(i).l){
System.out.println(vec.get(i).l+" "+vec.get(i).r);
t=vec.get(i).r;
}
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while ( sc.hasNextInt() ) {
int n = sc.nextInt();
long m = sc.nextInt();
boolean edge[][] = new boolean[n][n];
long dp[][] = new long[1<<n][n];
for ( long i = 1 ; i<=m ; ++i ) {
int u = sc.nextInt();
int v = sc.nextInt();
-- u;
-- v;
edge[u][v] = edge[v][u] = true;
}
for ( int i = 0 ; i<n ; ++i ) {
dp[1<<i][i] = 1;
}
long res = 0;
for ( int i = 1 ; i<(1<<n) ; ++i ) {
int first = cal(i);
for ( int j = first ; j<n ; ++j ) {
if ( dp[i][j]==0 ) {
continue;
}
for ( int k = first ; k<n ; ++k ) {
if ( j==k || !edge[j][k] ) {
continue;
}
if ( k==first && judge(i) ) {
res += dp[i][j];
}
if ( (i&(1<<k))==0 ) {
dp[i|(1<<k)][k] += dp[i][j];
}
}
}
}
System.out.println(res/2);
}
}
public static int cal( int x ) {
int ord = 0;
while ( true ) {
if ( (x&(1<<ord))!=0 ) {
break;
}
++ ord;
}
return ord;
}
public static boolean judge( int x ) {
int cnt = 0;
while ( x>=1 ) {
if ( (x&1)==1 ) {
++ cnt;
}
x >>= 1;
}
return cnt >= 3;
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.*;
public class Dj {
public static long run(long l, long r) {
if(l == r) {
return 0;
}
long[] sq2 = new long[62];
sq2[0] = 1;
for(int i = 1; i < 62; i++) sq2[i] = sq2[i-1]*2;
//System.out.println(sq2[61]);
for(int i = sq2.length - 1; i >= 0; i--) {
//log("L = " + l + " R = " + r + " 2^" + i + "=" + sq2[i]);
if(l >= sq2[i] && r >= sq2[i]) {
l -= sq2[i];
r -= sq2[i];
} else if(l < sq2[i] && sq2[i] <= r) {
break;
}
}
for(int i = sq2.length - 1; i >= 0; i--) {
//log("L = " + l + " R = " + r + " 2^" + i + "=" + sq2[i]);
if(l < sq2[i] && sq2[i] <= r) {
return sq2[i+1]-1;
}
}
return -1;
}
public static void log(String str) {
System.out.println(str);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long l = sc.nextLong();
long r = sc.nextLong();
System.out.println(run(l, r));
//System.out.println(run(9999999999998l, 9999999999999l));
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
import static java.lang.Math.*;
public class a111 {
public static void debug(Object... obs) {
System.out.println(Arrays.deepToString(obs));
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int[]a=new int[n];
int su=0;
for(int i=0;i<n;i++)
{
a[i]=-sc.nextInt();
su+=-1*a[i];
}
Arrays.sort(a);
int ss=0;
for(int i=0;i<n;i++)
{
ss+=-1*a[i];
su-=-1*a[i];
if(ss > su)
{
System.out.println(i+1);
return;
}
}
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
/* spar5h */
public class cf1 implements Runnable{
public void run() {
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t = 1;
while(t-- > 0) {
int n = s.nextInt(), m = s.nextInt();
int[] a = new int[n + 1];
for(int i = 1; i <= n; i++)
a[i] = s.nextInt();
int[] b = new int[n + 1];
for(int i = 1; i <= n; i++)
b[i] = s.nextInt();
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(a[1]);
for(int i = 2; i <= n; i++) {
list.add(b[i]); list.add(a[i]);
}
list.add(b[1]);
double wt = m;
boolean check = true;
for(int i = list.size() - 1; i >= 0; i--) {
if(list.get(i) <= 1) {
check = false; break;
}
double x = wt / (list.get(i) - 1);
wt += x;
}
if(check)
w.println(wt - m);
else
w.println(-1);
}
w.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);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new cf1(),"cf1",1<<26).start();
}
}
|
linear
|
1010_A. Fly
|
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int MOD = 1000000007;
public void solve(int testNumber, FastScanner in, PrintWriter out) {
long x = in.nextLong();
long k = in.nextLong();
if (x == 0) {
out.print(0);
return;
}
long b = fast_expo(2, k);
long a = (b * 2) % MOD;
long u = ((x % MOD) * a) % MOD;
long v = (b - 1 + MOD) % MOD;
out.print((u - v + MOD) % MOD);
}
private long fast_expo(long a, long b) {
long res = 1L;
a = a % MOD;
while (b > 0) {
if ((b & 1) != 0) {
res = (res * a) % MOD;
}
b = b >> 1;
a = (a * a) % MOD;
}
return res % MOD;
}
}
static class FastScanner {
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
public FastScanner(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class p481a {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long l = sc.nextLong();
long r = sc.nextLong();
if (r - l <= 1) {
System.out.println("-1");
} else if (r - l >= 3) {
if (l % 2 == 0) {
System.out.println(l + " " + (l + 1) + " " + (l + 2));
} else {
System.out.println((l + 1) + " " + (l + 2) + " " + (l + 3));
}
} else {
long g1 = GCD(l, (l + 1));
long g2 = GCD((l + 1), (l + 2));
long g3 = GCD(l, r);
if (g1 == 1 && g2 == 1 && g3 != 1) {
System.out.println(l + " " + (l + 1) + " " + r);
} else {
System.out.println("-1");
}
}
}
public static long GCD(long a, long b) {
if (b == 0) return a;
return GCD(b, a % b);
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class E {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
readInput();
out.close();
}
static long[][] dp;
static int n;
static long m;
static long pow(long b, long e) {
if (e== 0) return 1;
long r= pow(b,e/2);
r = r * r % m;
if ((e&1)==1) return r *b%m;
return r;
}
static long modinv(long a) {return pow(a,m-2);}
static long solve(int len, int num) {
if (len == -1 && num == -1) return 1;
if (num < 0 || len <= 0) return 0;
if (dp[len][num] == -1) {
dp[len][num] = 0;
for (int i = 0; i < len; i++) {
if (i == 1) continue;
long sol = pow[len-i-1]*solve(i-1,num-1)%m;
sol = sol * faci[len-i]% m;
dp[len][num] += sol;
dp[len][num] %= m;
}
}
return dp[len][num];
}
static long[] fac, faci, pow;
//asdf
public static void readInput() throws IOException {
// br = new BufferedReader(new FileReader(".in"));
// out = new PrintWriter(new FileWriter(".out"));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Long.parseLong(st.nextToken());
fac = new long[500];
pow = new long[500];
faci = new long[fac.length];
fac[0] = pow[0] = 1;
faci[0] = modinv(fac[0]);
for (int i = 1; i < fac.length; i++) {
fac[i] = fac[i-1]*i%m;
faci[i] = modinv(fac[i]);
pow[i] = pow[i-1] * 2 % m;
}
dp = new long[n+1][n+1];
for (long[] a: dp) Arrays.fill(a, -1);
// Number of ways to make a segment of length x is 2^(x-1)
// DP: Given position I.
long ans =0 ;
for (int i = 0 ; i <= n/2+1; i++) {
//System.out.println(i + ": " + solve(n,i) + " " + (n-i) + " " + (i));
long sol = solve(n,i) * fac[n-i];
sol %= m;
ans += sol;
}
out.println(ans%m);
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.util.*;
public class cf112e {
static int n,m,s;
static int[][][] memo;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
m = in.nextInt();
if(n > m) {
int tmp = n;
n = m;
m = tmp;
}
s = (1<<n);
memo = new int[s][s][m];
for(int i=0; i<s; i++)
for(int j=0; j<s; j++)
Arrays.fill(memo[i][j], -1);
int ret = go(0,0,0);
System.out.println(n*m - ret);
}
static int go(int last, int trans, int r) {
if(r==m) {
if(trans == 0) return 0;
return 100;
}
if(memo[last][trans][r] != -1) return memo[last][trans][r];
int best = 100;
for(int crnt = 0; crnt < s; crnt++) {
if((trans & ~crnt) != 0) continue; //certain ones have to be here
for(int pass = 0; pass < s; pass++) {
int tmp = ((1<<n)-1) & ~last; //move back the ones you can
if((pass & ~tmp) != 0) continue; //certain ones have to move on
tmp = tmp & ~pass; //find which ones stay
boolean fail = false;
for(int k=0; k<n; k++) //make sure that the ones that stay
if(isSet(tmp,k) && !(isSet(crnt,k-1) || isSet(crnt,k) || isSet(crnt,k+1)))
fail = true;
if(fail) continue;
best = Math.min(best, Integer.bitCount(crnt) + go(crnt,pass,r+1));
}
}
return memo[last][trans][r] = best;
}
static boolean isSet(int x, int p) {
if(p < 0 || p >= n) return false;
return (x & (1<<p)) != 0;
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.util.*;
import static java.lang.Math.*;
public class C {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
hx = sc.nextInt();
hy = sc.nextInt();
N = sc.nextInt();
X = new int[N];
Y = new int[N];
for(int i = 0; i < N;i++){
X[i] = sc.nextInt();
Y[i] = sc.nextInt();
}
DP = new int[1<<N];
Arrays.fill(DP,-1);
int ans = recur(0);
ArrayList<Integer> aa = new ArrayList<Integer>();
int U = 0;
aa.add(0);
int test = 0;
while(U != (1<<N)-1){
int a = 0;
for(int i = 0; i < N;i++)
if(((1<<i)&U) == 0){
a = i;
break;
}
int ans2 = recur(U|(1<<a))+2*(pw(X[a]-hx)+pw(Y[a]-hy));
int temp = 2*(pw(X[a]-hx)+pw(Y[a]-hy));
int best = -1;
for(int i = a+1;i<N;i++){
if(((1<<i)&U) == 0){
int ans3 = pw(X[a]-X[i])+pw(Y[a]-Y[i])+pw(X[a]-hx)+pw(Y[a]-hy)+pw(X[i]-hx)+pw(Y[i]-hy)+recur(U|(1<<a)|(1<<i));
if(ans3 < ans2){
ans2 = ans3;
best = i;
temp = pw(X[a]-X[i])+pw(Y[a]-Y[i])+pw(X[a]-hx)+pw(Y[a]-hy)+pw(X[i]-hx)+pw(Y[i]-hy);
}
}
}
if(best == -1){
aa.add(a+1);
aa.add(0);
U |= (1<<a);
}else{
aa.add(a+1);
aa.add(best+1);
aa.add(0);
U |= (1<<a) | (1<<best);
}
test += temp;
}
// System.out.println(test);
if(test != ans)
throw new RuntimeException();
System.out.println(ans);
for(int i = 0; i < aa.size();i++)
System.out.print(aa.get(i)+(i == aa.size()-1?"":" "));
System.out.println();
}
private static int recur(int U) {
if(DP[U] != -1)
return DP[U];
if(U == (1<<N)-1)
return 0;
int a = 0;
for(int i = 0; i < N;i++)
if(((1<<i)&U) == 0){
a = i;
break;
}
int ans = recur(U|(1<<a))+2*(pw(X[a]-hx)+pw(Y[a]-hy));
for(int i = a+1;i<N;i++){
if(((1<<i)&U) == 0){
ans = min(ans,pw(X[a]-X[i])+pw(Y[a]-Y[i])+pw(X[a]-hx)+pw(Y[a]-hy)+pw(X[i]-hx)+pw(Y[i]-hy)+recur(U|(1<<a)|(1<<i)));
}
}
DP[U] = ans;
return ans;
}
static int pw(int a){
return a*a;
}
static int hx,hy;
static int[] X,Y;
static int N;
static int[] DP;
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
public class Main{
public static void main(String[] args){
InputReader reader = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = reader.nextInt();
int r = reader.nextInt();
int[] x = new int[n];
double[] y = new double[n];
for(int i=0;i<n;++i){
int iniX = reader.nextInt();
double bestY = (double)r;
for(int j=0;j<i;++j){
// pw.printf("testing %d %d\n", i, j);
if(Math.abs(iniX - x[j]) < 2*r){
// pw.printf("on colision %d %d\n", i, j);
bestY = Math.max(bestY, collisionY((double)x[j], y[j], (double)iniX, r));
}
if(Math.abs(iniX - x[j]) == 2*r){
// pw.printf("touvhing %d %d\n", i, j);
bestY = Math.max(bestY, y[j]);
}
}
x[i] = iniX;
y[i] = bestY;
}
for(int i=0;i<n;++i){
pw.printf("%.9f ", y[i]);
}
pw.flush();
pw.close();
}
public static double collisionY(double x1, double y1, double x2, double r){
double dhsq = r*r*4-(x1-x2)*(x1-x2);
return y1+Math.sqrt(dhsq);
}
public static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader (InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream));
}
public String next(){
while(tokenizer == null || !tokenizer.hasMoreTokens()){
try{
String line = reader.readLine();
if(line == null){
return "0";
}
tokenizer = new StringTokenizer(line);
} catch(IOException ioe){
throw new RuntimeException(ioe);
}
}
return tokenizer.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
public Long nextLong(){
return Long.parseLong(next());
}
public BigInteger nextBigInteger(){
return new BigInteger(next());
}
public String nextLine(){
String line = "";
try{
while(line.equals("")){
line = reader.readLine();
}
} catch(IOException ioe){
throw new RuntimeException(ioe);
}
return line;
}
}
public static class MultiSet<E> {
HashMap<E, Integer> map = new HashMap<E, Integer>();
int multiSize = 0;
public int add(E key){
multiSize ++;
Integer amount = map.get(key);
if(amount == null){
map.put(key, 1);
return 1;
}
map.put(key, amount+1);
return amount+1;
}
public int remove(E key){
Integer amount = map.get(key);
if(amount == null){
return -1;
}
multiSize --;
if(amount == 1){
map.remove(key);
} else {
map.put(key, amount-1);
}
return amount-1;
}
public ArrayList<E> elems(){
ArrayList<E> ret = new ArrayList<E>(multiSize);
for(Map.Entry<E, Integer> e : map.entrySet()){
E key = e.getKey();
int v = e.getValue();
while(v-->0){
ret.add(key);
}
}
return ret;
}
public int getMultiSize(){
return multiSize;
}
}
public static class MaxBIT{
int n;
int[]t;
public MaxBIT(int n){
this.n = Integer.highestOneBit(n)<<1;
this.t = new int[this.n<<1];
for(int i=0;i<2*this.n;++i){
t[i] = -1;
}
}
public void setMax(int p, int val){
p+=n;
while(p>1){
t[p] = Math.max(t[p], val);
p>>=1;
}
}
public int getMax(int p, int q){
p+=n;
q+=n;
int ret = -1;
while(p<q){
if((p&1)==1){
ret=Math.max(t[p++], ret);
}
if((q&1)==1){
ret=Math.max(t[--q], ret);
}
p = p>>1;
q = q>>1;
}
return ret;
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main implements Runnable {
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
private void eat(String line)
{
st = new StringTokenizer(line);
}
private String next() throws IOException
{
while(!st.hasMoreTokens()) {
String line = in.readLine();
if(line == null)
return null;
eat(line);
}
return st.nextToken();
}
private int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public void run()
{
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
eat("");
go();
out.close();
} catch(Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args)
{
new Thread(new Main()).start();
}
public void go() throws IOException
{
int n = nextInt(), t = nextInt();
int[] x = new int[n], a = new int[n];
for(int i = 0; i < n; ++i) {
x[i] = nextInt();
a[i] = nextInt();
}
out.println(new Algo().solve(n, t, x, a));
}
}
final class Algo {
public int solve(int n, int t, final int[] x, final int[] a)
{
Integer[] order = new Integer[n];
for(int i = 0; i < n; ++i)
order[i] = i;
Arrays.sort(order, new Comparator<Integer>() {
public int compare(Integer a, Integer b)
{
return x[a] - x[b];
}
});
int result = 2;
for(int i = 0; i + 1 < n; ++i) {
int u = order[i], v = order[i + 1];
int dist = 2 * (x[v] - x[u]) - (a[v] + a[u]);
if(dist > 2 * t)
result += 2;
else if(dist == 2 * t)
++result;
}
return result;
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class j
{
public static void main(String a[])throws IOException
{
BufferedReader b = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
int l=0,x2=0,x=0,y1=0,y=0,max=-1,min=100000,x1=0,n=0,j=0,k=0,p=0,m=0,i=0;
String s;
s=b.readLine();
StringTokenizer c=new StringTokenizer(s);
n=Integer.parseInt(c.nextToken());
m=Integer.parseInt(c.nextToken());
k=Integer.parseInt(b.readLine());
int e[][]=new int[k][2];
s=b.readLine();
StringTokenizer z=new StringTokenizer(s);
for(i=0;i<k;i++)
{
e[i][0]=Integer.parseInt(z.nextToken());
e[i][1]=Integer.parseInt(z.nextToken());
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
for(l=0;l<k;l++)
{
p=(int)Math.abs(e[l][0]-i)+(int)Math.abs(e[l][1]-j);
if(p<min)
{
min=p;
x1=i;
y1=j;
}
}
if(min>max)
{
max=min;
x=x1;
y=y1;
}
min=100000;
}
}
out.print(x+" "+y);
out.close();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
long r,l;
r = sc.nextLong();
l = sc.nextLong();
if ((r+2)>l) { System.out.print("-1"); return;}
if ((r % 2) == 0) {
System.out.print(r);
System.out.print(" ");
System.out.print(r+1);
System.out.print(" ");
System.out.print(r+2);return; }
if((r+3)<=l )
{ System.out.print(r+1);
System.out.print(" ");
System.out.print(r+2);
System.out.print(" ");
System.out.print(r+3);return; }
System.out.print("-1");
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
long n = nextLong();
long s = nextLong();
long ans = 0;
if (s+200 <= n)
ans += n - (s+200) + 1;
for (long i = s; i < s+200; i++) {
if (i <= n && i-sumDigits(i) >= s) {
ans++;
}
}
System.out.println(ans);
pw.close();
}
private static long sumDigits(long n) {
long sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
InputReader in = new InputReader(inputStream);
// for(int i=4;i<=4;i++) {
// InputStream uinputStream = new FileInputStream("shortcut.in");
// String f = i+".in";
// InputStream uinputStream = new FileInputStream(f);
// InputReader in = new InputReader(uinputStream);
// PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("shortcut.out")));
Task t = new Task();
t.solve(in, out);
out.close();
// }
}
static class Task {
public void solve(InputReader in, PrintWriter out) throws IOException {
int n = in.nextInt();
int arr[] = in.readIntArray(n);
int v[][] = new int[n][n];
int c=0;
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
for(int i=0;i<n;i++) {
for(int j=i;j<n;j++) {
v[i][j] = arr[j];
if(j>i) v[i][j] += v[i][j-1];
if(!mp.containsKey(v[i][j])) mp.put(v[i][j], c++);
}
}
ArrayList<seg>[] all = new ArrayList[c];
for(int i=0;i<c;i++) all[i] = new ArrayList<seg>();
for(int i=0;i<n;i++) {
for(int j=i;j<n;j++) {
int idx = mp.get(v[i][j]);
all[idx].add(new seg(i,j,v[i][j]));
}
}
for(int i=0;i<c;i++) Collections.sort(all[i]);
int max = Integer.MIN_VALUE;
int val = -1;
for(int i=0;i<c;i++) {
if(all[i].size()==0) continue;
int num=1;
int p=0;int q=p+1;
while(q<all[i].size()) {
if(all[i].get(q).s>all[i].get(p).e) {
p=q;
num++;
}
q++;
}
if(num>max) {
max=num;
val = i;
}
}
out.println(max);
StringBuilder sb = new StringBuilder();
int p=0;int q=p+1;
sb.append(all[val].get(0).toString());
while(q<all[val].size()) {
if(all[val].get(q).s>all[val].get(p).e) {
sb.append(all[val].get(q).toString());
p=q;
}
q++;
}
out.println(sb.toString());
}
public class seg implements Comparable<seg>{
int s; int e; int val;
public seg(int a, int b, int c) {
s=a;e=b;val=c;
}
@Override
public int compareTo(seg t) {
if(this.e==t.e) return this.s-t.s;
return this.e-t.e;
}
public String toString() {
return (s+1)+" "+(e+1)+"\n";
}
}
public int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
}
static class ArrayUtils {
static final long seed = System.nanoTime();
static final Random rand = new Random(seed);
public static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void shuffle(int[] a) {
for (int i = 0; i < a.length; i++) {
int j = rand.nextInt(i + 1);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
static class BIT{
int arr[];
int n;
public BIT(int a) {
n=a;
arr = new int[n];
}
int sum(int p) {
int s=0;
while(p>0) {
s+=arr[p];
p-=p&(-p);
}
return s;
}
void add(int p, int v) {
while(p<n) {
arr[p]+=v;
p+=p&(-p);
}
}
}
static class DSU{
int[] arr;
int[] sz;
public DSU(int n) {
arr = new int[n];
sz = new int[n];
for(int i=0;i<n;i++) arr[i] = i;
Arrays.fill(sz, 1);
}
public int find(int a) {
if(arr[a]!=a) arr[a] = find(arr[a]);
return arr[a];
}
public void union(int a, int b) {
int x = find(a);
int y = find(b);
if(x==y) return;
arr[x] = y;
sz[y] += sz[x];
}
public int size(int x) {
return sz[find(x)];
}
}
static class MinHeap<Key> implements Iterable<Key> {
private int maxN;
private int n;
private int[] pq;
private int[] qp;
private Key[] keys;
private Comparator<Key> comparator;
public MinHeap(int capacity){
if (capacity < 0) throw new IllegalArgumentException();
this.maxN = capacity;
n=0;
pq = new int[maxN+1];
qp = new int[maxN+1];
keys = (Key[]) new Object[capacity+1];
Arrays.fill(qp, -1);
}
public MinHeap(int capacity, Comparator<Key> c){
if (capacity < 0) throw new IllegalArgumentException();
this.maxN = capacity;
n=0;
pq = new int[maxN+1];
qp = new int[maxN+1];
keys = (Key[]) new Object[capacity+1];
Arrays.fill(qp, -1);
comparator = c;
}
public boolean isEmpty() { return n==0; }
public int size() { return n; }
public boolean contains(int i) {
if (i < 0 || i >= maxN) throw new IllegalArgumentException();
return qp[i] != -1;
}
public int peekIdx() {
if (n == 0) throw new NoSuchElementException("Priority queue underflow");
return pq[1];
}
public Key peek(){
if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
return keys[pq[1]];
}
public int poll(){
if(isEmpty()) throw new NoSuchElementException("Priority queue underflow");
int min = pq[1];
exch(1,n--);
down(1);
assert min==pq[n+1];
qp[min] = -1;
keys[min] = null;
pq[n+1] = -1;
return min;
}
public void update(int i, Key key) {
if (i < 0 || i >= maxN) throw new IllegalArgumentException();
if (!contains(i)) {
this.add(i, key);
}else {
keys[i] = key;
up(qp[i]);
down(qp[i]);
}
}
private void add(int i, Key x){
if (i < 0 || i >= maxN) throw new IllegalArgumentException();
if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue");
n++;
qp[i] = n;
pq[n] = i;
keys[i] = x;
up(n);
}
private void up(int k){
while(k>1&&less(k,k/2)){
exch(k,k/2);
k/=2;
}
}
private void down(int k){
while(2*k<=n){
int j=2*k;
if(j<n&&less(j+1,j)) j++;
if(less(k,j)) break;
exch(k,j);
k=j;
}
}
public boolean less(int i, int j){
if (comparator == null) {
return ((Comparable<Key>) keys[pq[i]]).compareTo(keys[pq[j]]) < 0;
}
else {
return comparator.compare(keys[pq[i]], keys[pq[j]]) < 0;
}
}
public void exch(int i, int j){
int swap = pq[i];
pq[i] = pq[j];
pq[j] = swap;
qp[pq[i]] = i;
qp[pq[j]] = j;
}
@Override
public Iterator<Key> iterator() {
// TODO Auto-generated method stub
return null;
}
}
private static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int zcurChar;
private int znumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (znumChars == -1)
throw new InputMismatchException();
if (zcurChar >= znumChars)
{
zcurChar = 0;
try
{
znumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (znumChars <= 0)
return -1;
}
return buf[zcurChar++];
}
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
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
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 long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return nextString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public int[] readIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
static class Dumper {
static void print_int_arr(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_char_arr(char[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_double_arr(double[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("---------------------");
}
static void print_2d_arr(int[][] arr, int x, int y) {
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("---------------------");
}
static void print_2d_arr(boolean[][] arr, int x, int y) {
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("---------------------");
}
static void print(Object o) {
System.out.println(o.toString());
}
static void getc() {
System.out.println("here");
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
// practice with rainboy
import java.io.*;
import java.util.*;
public class CF256B extends PrintWriter {
CF256B() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF256B o = new CF256B(); o.main(); o.flush();
}
long count(int n, int x, int y, int r) {
long a = 2L * r * r + 2 * r + 1;
int w;
if ((w = 1 - (x - r)) > 0)
a -= (long) w * w;
if ((w = 1 - (y - r)) > 0)
a -= (long) w * w;
if ((w = (x + r) - n) > 0)
a -= (long) w * w;
if ((w = (y + r) - n) > 0)
a -= (long) w * w;
if ((w = r - 1 - (x - 1) - (y - 1)) > 0)
a += (long) w * (w + 1) / 2;
if ((w = r - 1 - (x - 1) - (n - y)) > 0)
a += (long) w * (w + 1) / 2;
if ((w = r - 1 - (n - x) - (y - 1)) > 0)
a += (long) w * (w + 1) / 2;
if ((w = r - 1 - (n - x) - (n - y)) > 0)
a += (long) w * (w + 1) / 2;
return a;
}
void main() {
int n = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
int c = sc.nextInt();
int lower = -1, upper = c;
while (upper - lower > 1) {
int r = (lower + upper) / 2;
if (count(n, x, y, r) >= c)
upper = r;
else
lower = r;
}
println(upper);
}
}
|
logn
|
256_B. Mr. Bender and Square
|
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);
C489 solver = new C489();
solver.solve(1, in, out);
out.close();
}
static class C489 {
int mod = 1000000007;
public void solve(int testNumber, ScanReader in, PrintWriter out) {
long x = in.scanLong();
long k = in.scanLong();
if (x == 0) {
out.println(0);
return;
}
long p = CodeX.power(2, k, mod);
long ans = (2 * p * (x % mod)) % mod;
ans = (ans + 1) % mod;
ans = (ans - p + mod) % mod;
out.println(ans);
}
}
static class CodeX {
public static long power(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if ((y & 1) != 0)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
}
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++];
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() {
long 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;
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class C {
public static void main(String[] args) throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int t = Integer.parseInt(f.readLine());
while(t-->0){
int n = Integer.parseInt(f.readLine());
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = Integer.parseInt(f.readLine());
}
int[] levels = new int[n];
int curr_level = 0;
for(int i = 0; i < n; i++){
if(levels[curr_level] == arr[i]-1){
levels[curr_level]++;
}else if(arr[i] == 1){
curr_level++;
levels[curr_level]++;
}else if(arr[i] > 1){
while(curr_level > 0 && levels[curr_level] != arr[i]-1){
levels[curr_level] = 0;
curr_level--;
}
levels[curr_level]++;
}
StringBuilder ostring = new StringBuilder();
for(int level = 0; level <= curr_level; level++){
ostring.append(levels[level]);
if(level != curr_level) ostring.append(".");
}
out.println(ostring);
}
}
out.close();
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A {
FastScanner in;
PrintWriter out;
public void run() {
try {
in = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void solve() throws IOException {
long l = new Long(in.next());
long r = new Long(in.next());
if (r - l < 2 || (r - l == 2 && l % 2 != 0)) {
out.println("-1");
} else {
if (l % 2 != 0) {
l++;
}
out.println(l);
out.println(l+1);
out.println(l+2);
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStreamReader in) {
br = new BufferedReader(in);
}
String nextLine() {
String str = null;
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] arg) {
A o = new A();
o.run();
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeSet;
public final class CF_599_D1_C
{
static boolean verb=true;
static void log(Object X){if (verb) System.err.println(X);}
static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}
static void logWln(Object X){if (verb) System.err.print(X);}
static void info(Object o){ System.out.println(o);}
static void output(Object o){outputWln(""+o+"\n"); }
static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}}
static long mod=1000000007;
// Global vars
static BufferedWriter out;
static InputReader reader;
static class Composite implements Comparable<Composite>{
int idx;
int v;
public int compareTo(Composite X) {
if (v!=X.v)
return v-X.v;
return idx-X.idx;
}
public Composite(int idx, int v) {
this.idx = idx;
this.v = v;
}
}
static void test() {
log("testing");
log("done");
}
static void explore(ArrayList<Integer>[] components,ArrayList<Integer> bob,int[][] move,ArrayList<int[]>[] howto,int[][] list) {
for (int x:bob) {
if (components[x].size()==1) {
int tm[]=howto[x].get(0);
int L=howto[x].size();
howto[x].add(tm);
for (int i=0;i<L;i++) {
int[] cur=howto[x].get(i);
int[] nx=howto[x].get(i+1);
int a=cur[0];
int a2=nx[0];
int b2=nx[1];
move[a2][0]=list[a2][b2];
move[a2][1]=a;
}
} else {
explore(components,components[x],move,howto,list);
}
}
}
static void process() throws Exception {
//arrayTest();
out = new BufferedWriter(new OutputStreamWriter(System.out));
reader = new InputReader(System.in);
int k=reader.readInt();
int[][] list=new int[k][];
long[] sum=new long[k];
int[] L=new int[k];
HashMap<Integer,int[]> target=new HashMap<Integer,int[]>();
long tot=0;
for (int i=0;i<k;i++) {
L[i]=reader.readInt();
list[i]=new int[L[i]];
for (int j=0;j<L[i];j++) {
list[i][j]=reader.readInt();
sum[i]+=list[i][j];
target.put(list[i][j],new int[] {i,j});
}
tot+=sum[i];
}
int MX=1<<k;
int AX=1000000001;
ArrayList<int[]>[] howto=new ArrayList[MX];
log("ok with the data");
if (tot%k!=0) {
output("No");
} else {
tot/=k;
for (int i=0;i<k;i++) {
if (sum[i]==tot) {
//log("nothing to do for i:"+i);
// nothing to do
int mask=1<<i;
ArrayList<int[]> cand=new ArrayList<int[]>();
cand.add(new int[] {i,0});
howto[mask]=cand;
} else
for (int j=0;j<L[i];j++) {
int u=i;
int v=j;
boolean ok=true;
int src_u=u;
int src_v=v;
int mask=0;
boolean goon=true;
ArrayList<int[]> cand=new ArrayList<int[]>();
//log("start loop");
while (goon) {
cand.add(new int[] {u,v});
//log("u:"+u+" v:"+v);
ok=false;
goon=false;
long need=tot-((long)sum[u]-(long)list[u][v]);
if (Math.abs(need)<=AX) {
//log("need:"+need);
int nd=(int)need;
int[] tm=target.get(nd);
//log("tm:"+tm);
if (tm!=null) {
//log("can find successor");
int nxu=tm[0];
int nxv=tm[1];
if ((mask&(1<<nxu))==0) {
mask|=1<<nxu;
if (nxu==src_u) {
// looping back to source
if (nxv==src_v)
ok=true;
} else {
u=nxu;
v=nxv;
ok=true;
goon=true;
}
}
}
}
}
if (ok) {
if (howto[mask]==null) {
howto[mask]=cand;
}
}
}
}
log("step 1 done");
// now mask
ArrayList[] components=new ArrayList[MX];
for (int m=0;m<MX;m++) {
if (howto[m]!=null) {
//String s=Integer.toBinaryString(m);
//while (s.length()<k)
// s="0"+s;
//log("found mask:"+s);
components[m]=new ArrayList<Integer>();
components[m].add(m);
}
}
int[] msk=new int[MX];
int w=0;
for (int a=0;a<MX;a++) {
if (howto[a]!=null) {
ArrayList<Integer> add=new ArrayList<Integer>();
int ww=w;
for (int i=0;i<ww;i++) {
int b=msk[i];
if ((b&a)==0) {
int c=b|a;
log("creating c:"+c+" ");
if (components[c]==null ) {
components[c]=new ArrayList<Integer>();
components[c].add(a);
components[c].add(b);
msk[w++]=c;
}
}
}
msk[w++]=a;
}
}
//log("msk:"+msk);
//log(components[MX-1]);
if (components[MX-1]!=null) {
output("Yes");
int[][] move=new int[k][2];
explore(components,components[MX-1],move,howto,list);
for (int i=0;i<k;i++) {
output(move[i][0]+" "+(move[i][1]+1));
}
} else {
output("No");
}
}
try {
out.close();
} catch (Exception e) {
}
}
public static void main(String[] args) throws Exception {
process();
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public final int readInt() throws IOException {
int c = read();
boolean neg = false;
while (isSpaceChar(c)) {
c = read();
}
char d = (char) c;
// log("d:"+d);
if (d == '-') {
neg = true;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
// log("res:"+res);
if (neg)
return -res;
return res;
}
public final long readLong() throws IOException {
int c = read();
boolean neg = false;
while (isSpaceChar(c)) {
c = read();
}
char d = (char) c;
// log("d:"+d);
if (d == '-') {
neg = true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
// log("res:"+res);
if (neg)
return -res;
return res;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
np
|
1242_C. Sum Balance
|
CODEFORCES
|
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class R035CRetry {
public void debug(Object... objects) { System.err.println(Arrays.deepToString(objects)); }
public static final int INF = 987654321;
public static final long LINF = 987654321987654321L;
public static final double EPS = 1e-9;
Scanner scanner;
PrintWriter out;
boolean[][] bss;
public R035CRetry() {
try {
this.scanner = new Scanner(new File("input.txt"));
this.out = new PrintWriter("output.txt");
} catch(FileNotFoundException ex) { ex.printStackTrace(); }
}
class Point implements Comparable<Point> {
int x, y, count;
Point(int x, int y) { this.x = x; this.y = y; }
public int hashCode() { return x * 17 + y; }
public boolean equals(Object o) {
if(!(o instanceof Point)) return false;
Point that = (Point)o;
return this.x == that.x && this.y == that.y;
}
public int compareTo(Point that) { return this.count - that.count; }
public String toString() { return "(" + x + ", " + y + ":" + count + ")"; }
}
int[] dx = new int[] { 0, 0, -1, 1 };
int[] dy= new int[] { -1, 1, 0, 0 };
int n, m;
Queue<Point> q;
Point bfs() {
int max = -INF;
Point p = null;
while(!q.isEmpty()) {
Point cur = q.remove();
if(max < cur.count) { max = cur.count; p = cur; }
for(int i=0; i<dx.length; i++) {
int nx = cur.x + dx[i];
int ny = cur.y + dy[i];
if(nx < 0 || nx >= n) { continue; }
if(ny < 0 || ny >= m) { continue; }
Point np = new Point(nx, ny);
if(bss[nx][ny] ) { continue; }
np.count = cur.count+1;
bss[nx][ny] = true;
q.add(np);
}
}
return p;
}
private void solve() {
this.n = scanner.nextInt();
this.m = scanner.nextInt();
this.bss = new boolean[n][m];
int k = scanner.nextInt();
q = new LinkedList<Point>();
for(int i=0; i<k; i++) {
int x = scanner.nextInt() - 1;
int y = scanner.nextInt() - 1;
Point init = new Point(x, y);
init.count = 1;
q.add(init);
bss[x][y] = true;
}
Point p = bfs();
out.println((p.x+1) + " " + (p.y+1));
}
private void finish() { this.out.close(); }
public static void main(String[] args) {
R035CRetry obj = new R035CRetry();
obj.solve();
obj.finish();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
import java.math.*;
public class Split {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
int k= sc.nextInt();
int a[] = new int[n];
int d[] = new int[n-1];
for(int i=0;i<n;i++) {
a[i] = sc.nextInt();
if(i>0)
d[i-1] = a[i-1] - a[i];
}
Arrays.sort(d);
int t = 0;
for(int i=0;i<k-1;i++)
t += d[i];
System.out.println(a[n-1]-a[0]+t);
}
}
|
nlogn
|
1197_C. Array Splitting
|
CODEFORCES
|
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
void solve(){
int n=ni();
int c1[]=new int[9];
int c2[]=new int[9];
for(int i=0;i<n;i++){
String s=ns();
if(s.equals("M")) c1[0]++;
else if(s.equals("S")) c1[1]++;
else if(s.equals("L")) c1[2]++;
else if(s.equals("XS")) c1[3]++;
else if(s.equals("XL")) c1[4]++;
else if(s.equals("XXS")) c1[5]++;
else if(s.equals("XXL")) c1[6]++;
else if(s.equals("XXXS")) c1[7]++;
else if(s.equals("XXXL")) c1[8]++;
}
for(int i=0;i<n;i++){
String s=ns();
if(s.equals("M")) c2[0]++;
else if(s.equals("S")) c2[1]++;
else if(s.equals("L")) c2[2]++;
else if(s.equals("XS")) c2[3]++;
else if(s.equals("XL")) c2[4]++;
else if(s.equals("XXS")) c2[5]++;
else if(s.equals("XXL")) c2[6]++;
else if(s.equals("XXXS")) c2[7]++;
else if(s.equals("XXXL")) c2[8]++;
}
int ans=0;
for(int i=0;i<9;i++){
if(c2[i]<c1[i]) ans+=c1[i]-c2[i];
}
pw.println(ans);
}
long M=(long)1e9+7;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Main().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class C{
static PrintWriter out;
static InputReader in;
public static void main(String args[]){
out = new PrintWriter(System.out);
in = new InputReader();
new C();
out.flush(); out.close();
}
C(){
int a = solve();
out.print(a == 0 ? "tokitsukaze" : a == 1 ? "quailty" : "once again");
}
int n, k;
char ch[]; int a[], c0 = 0, c1 = 0;
TreeSet<Integer> ts[] = new TreeSet[2];
boolean check(){
int min = 0, max = n;
if(!ts[0].isEmpty()){
min = ts[0].first(); max = ts[0].last();
if(max - min + 1 > k)return true;
}
if(!ts[1].isEmpty()){
min = ts[1].first(); max = ts[1].last();
if(max - min + 1 > k)return true;
}
return false;
}
int solve(){
n = in.nextInt(); k = in.nextInt();
ch = in.next().trim().toCharArray(); a = new int[n];
for(int i = 0; i < n; i++)c1 += a[i] = ch[i] - '0';
c0 = n - c1;
for(int i = 0; i < k; i++){
if(a[i] == 0)c0--; else c1--;
}
if(c0 == 0 || c1 == 0)return 0;
for(int i = k; i < n; i++){
if(a[i] == 0)c0--; else c1--;
if(a[i - k] == 0)c0++; else c1++;
if(c0 == 0 || c1 == 0)return 0;
}
for(int i = 0; i < 2; i++)ts[i] = new TreeSet<>();
for(int i = 0; i < n; i++){
ts[a[i]].add(i);
}
for(int i = 0; i < k; i++){
ts[a[i]].remove(i);
}
if(check())return 2;
for(int i = k; i < n; i++){
ts[a[i]].remove(i); ts[a[i - k]].add(i - k);
if(check())return 2;
}
return 1;
}
public static class InputReader{
BufferedReader br;
StringTokenizer st;
InputReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
public String next(){
while(st == null || !st.hasMoreTokens()){
try{
st = new StringTokenizer(br.readLine());
}catch(IOException e){}
}
return st.nextToken();
}
}
}
|
linear
|
1190_C. Tokitsukaze and Duel
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class CFC {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static final long MOD = 1000L * 1000L * 1000L + 7;
private static final int[] dx = {0, -1, 0, 1};
private static final int[] dy = {1, 0, -1, 0};
private static final String yes = "Yes";
private static final String no = "No";
void solve() throws IOException {
long x = nextLong();
long k = nextLong();
if (x == 0) {
outln(0);
return;
}
x %= MOD;
long two = powMod(2, k, MOD);
long res = two;
res *= 2;
res %= MOD;
res *= x;
res %= MOD;
res -= two - 1;
while (res < 0) {
res += MOD;
}
while (res >= MOD) {
res -= MOD;
}
outln(res);
}
public long powMod(long N, long M, long MOD){//N^M % MOD
if(M == 0L)
return 1L;
long[] hp = new long[64];
boolean[] bp = new boolean[64];
hp[0] = N;
for(int i = 1; i < hp.length; i++) {
hp[i] = (hp[i - 1] * hp[i - 1]) % MOD;
}
for(int j = 0; j < hp.length; j++) {
if((M & (1L << j)) != 0)
bp[j] = true;
}
long res = 1;
for(int i = 0;i < bp.length; i++){
if(bp[i]) {
res = (res * hp[i]) % MOD;
}
}
return res;
}
void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
public CFC() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFC();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
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());
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author wilso
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class codeforces {
static final long MOD2 = 998_244_353;
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int tc = sc.ni();
// int tc = 1;
for (int rep = 0; rep < tc; rep++) {
int N = sc.ni();
int[] arr = sc.intArray(N);
pw.println(solve(arr));
}
pw.close();
}
static String solve(int[] arr) {
StringBuilder sb = new StringBuilder();
List<Integer> list = new ArrayList();
list.add(0);
for (int i = 0; i < arr.length; i++) {
int x = arr[i];
for (int j = list.size() - 1; j >= 0; j--) {
if (x - 1 == list.get(j)) {
list.set(j, x);
while (list.size() > j+1) {
list.remove(list.size() - 1);
}
list.add(0);
//append
for (int idx = 0; idx < list.size() - 1; idx++) {
sb.append(list.get(idx) + ".");
}
sb.setLength(sb.length() - 1);
sb.append("\n");
break;
}
}
}
sb.setLength(sb.length() - 1);
return sb.toString();
}
static int summation(int x) {
return x * (x+1) / 2;
}
static long pow(long num, long exp, long mod){
long ans=1;
for(int i=1;i<=exp;i++){
ans=(ans*num)%mod;
}
return ans;
}
static boolean isPrime(int n)
{
if (n <= 1)
return false;
else if (n == 2)
return true;
else if (n % 2 == 0)
return false;
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);
}
static long gcd(long a, long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
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);
}
static int charint(char c) {
return Integer.parseInt(String.valueOf(c));
}
/* */
//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");
}
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 MultiSet {
TreeMap<Long, Integer> map = new TreeMap<>();
private int size = 0;
public MultiSet() {
}
public void add(Long val) {
map.put(val, map.getOrDefault(val, 0) + 1);
size++;
}
public void remove(Long val) {
map.put(val, map.get(val) - 1);
if (map.get(val) == 0) {
map.remove(val);
}
size--;
}
public int size() {
return size;
}
public Long higher(Long val) {
return map.higherKey(val);
}
public Long lower(Long val) {
return map.lowerKey(val);
}
public Long ceiling(Long val) {
return map.ceilingKey(val);
}
public Long floor(Long val) {
return map.floorKey(val);
}
public Long first() {
return map.firstKey();
}
public Long last() {
return map.lastKey();
}
public boolean isEmpty() {
return map.isEmpty();
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.*;
public class cf16e {
static int n;
static double[][] prob;
static double[] memo;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
prob = new double[n][n];
memo = new double[1<<n];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
prob[i][j] = in.nextDouble();
memo[(1<<n)-1] = 1;
for(int k=(1<<n)-1; k>0; k--) {
int numWays = Integer.bitCount(k);
numWays = (numWays*(numWays-1))/2;
for(int first = 0; first < n; first++) {
if(!isSet(k,first)) continue;
for(int second = first+1; second < n; second++) {
if(!isSet(k,second)) continue;
memo[reset(k,first)] += prob[second][first]*memo[k]/numWays;
memo[reset(k,second)] += prob[first][second]*memo[k]/numWays;
}
}
}
for(int i=0; i<n; i++)
System.out.printf("%.6f ", memo[set(0,i)]);
System.out.println();
}
static boolean isSet(int x, int p) {
return (x&(1<<p)) != 0;
}
static int set(int x, int p) {
return x|(1<<p);
}
static int reset(int x, int p) {
return x&~(1<<p);
}
static boolean isDone(int x) {
return Integer.bitCount(x)==n-1;
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.*;
public class Q3a {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
String s = in.nextLine();
HashMap<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < n; i++) {
Character c = s.charAt(i);
int ci = (int) c.charValue();
// System.out.println(ci);
seen.put(ci, seen.get(ci) == null ? 1 : seen.get(ci) + 1);
}
HashMap<Integer, Integer> sub = new HashMap<Integer, Integer>();
int start = 0;
int min = 10000000;
for (int i = 0; i < n; i++) {
Character c = s.charAt(i);
int ci = (int) c.charValue();
sub.put(ci, sub.get(ci) == null ? 1 : sub.get(ci) + 1);
while(sub.size() == seen.size()) {
min = Math.min(min, i - start + 1);
c = s.charAt(start);
start ++;
ci = (int) c.charValue();
if( sub.get(ci) == 1)
sub.remove(ci);
else
sub.put(ci, sub.get(ci) - 1);
}
}
System.out.print(min);
// System.out.println( seen_all_at - begin + 1);
in.close();
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.util.Scanner;
public class New_Year_and_Curling {
static final double E = 0.00001;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int r = sc.nextInt();
double[] y = new double[n];
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] =sc.nextInt();
double top = r; // if we make it 0 and subtract from the result will get WA (do not know why!!!)
int x = arr[i];
for(int j =0 ;j<i;j++)
{
if(Math.abs(arr[j] -x )<=2*r) {
top = Math.max(top , y[j] + Math.sqrt((4 * r * r) - ((arr[j] - x) * (arr[j] - x))));
}
}
y[i] = top ;
double res = y[i] ;
System.out.print(res+" ");
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.Scanner;
public class A_YoureGivenAString {
//1:11
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
for (int l = str.length()-1; l >= 1; l--) {
for (int i = 0; i < str.length()-l+1; i++) {
String subs = str.substring(i, i+l);
if(str.lastIndexOf(subs) != i){
System.out.println(l);
return;
}
}
}
System.out.println(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
public static void main(String[] args) throws Exception {
new A().solve();
}
void solve() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
if (n == 0) {
System.out.println("0 0 0");
return;
}
int p2 = 0;
int p1 = 1;
while (true) {
int now = p2 + p1;
if (n == now) {
System.out.println("0 " + p1 + " " + p2);
return;
} else {
p2 = p1;
p1 = now;
}
}
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
//package round428;
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 E2 {
InputStream is;
PrintWriter out;
String INPUT = "";
// String INPUT = "";
void solve()
{
int n = ni(), K = ni();
long[] g = new long[n];
for(int i = 0;i < n;i++){
for(int j = 0;j < n;j++){
g[i] |= nl()<<j;
}
g[i] |= 1L<<i;
}
// (K/M)^2*M(M-1)/2
// K^2*(M-1)/2M
int mc = solveMaximumClique(g);
out.printf("%.14f\n", (double)K*K*(mc-1)/2/mc);
}
public static int solveMaximumClique(long[] g)
{
int n = g.length;
int h = n/2;
int[] dp = new int[1<<n-h];
for(int i = 0;i < 1<<h;i++){
long cover = (1L<<n)-1;
for(int j = 0;j < h;j++){
if(i<<~j<0)cover &= g[j];
}
if((cover&i) == i){
dp[(int)(cover>>>h)] = Math.max(dp[(int)(cover>>>h)], Integer.bitCount(i));
}
}
for(int i = 0;i < n-h;i++){
for(int j = 0;j < 1<<n-h;j++){
if(j<<~i>=0){
dp[j] = Math.max(dp[j], dp[j|1<<i]);
}
}
}
int ret = 0;
for(int i = 0;i < 1<<n-h;i++){
long cover = (1L<<n)-1;
for(int j = 0;j < n-h;j++){
if(i<<~j<0)cover &= g[j+h];
}
if((cover&(long)i<<h) == (long)i<<h){
ret = Math.max(ret, Integer.bitCount(i) + dp[i]);
}
}
return ret;
}
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 E2().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
np
|
839_E. Mother of Dragons
|
CODEFORCES
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Saransh
*/
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try
{
Parserdoubt pd=new Parserdoubt(System.in);
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=pd.nextInt();
PrintWriter pw=new PrintWriter(System.out);
pw.println((n*3)/2);
pw.flush();
}
catch(Exception e)
{}
}
}
class Parserdoubt
{
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parserdoubt(InputStream in)
{
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws Exception
{
StringBuffer sb=new StringBuffer("");
byte c = read();
while (c <= ' ') c = read();
do
{
sb.append((char)c);
c=read();
}while(c>' ');
return sb.toString();
}
public char nextChar() throws Exception
{
byte c=read();
while(c<=' ') c= read();
return (char)c;
}
public int nextInt() throws Exception
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
public long nextLong() throws Exception
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Ideone {
static long ans=0;
public static void Stepgcd(long a,long b) {
if (b!=0) {ans+=(a/b);Stepgcd(b,a%b);}
}
public static void main (String[] args) throws java.lang.Exception {
Scanner in=new Scanner(System.in);
long a=in.nextLong(),b=in.nextLong();
Stepgcd(a,b);
System.out.println(ans);
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.util.ArrayDeque;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Zyflair Griffane
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream("output.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
PandaScanner in = new PandaScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
C solver = new C();
solver.solve(1, in, out);
out.close();
}
}
class C {
final int dx[] = { -1, 0, 1, 0};
final int dy[] = { 0, -1, 0, 1};
final int SHIFT = 15;
final int COLUMN_MASK = (1 << SHIFT) - 1;
public void solve(int testNumber, PandaScanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
boolean burning[][] = new boolean[n][m];
int k = in.nextInt();
ArrayDeque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < k; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
burning[x][y] = true;
q.add((x << SHIFT) + y);
}
int last = 0;
while (!q.isEmpty()) {
last = q.poll();
int x = last >> SHIFT;
int y = last & COLUMN_MASK;
for (int d = 0; d < 4; d++) {
int nx = x + dx[d];
int ny = y + dy[d];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && !burning[nx][ny]) {
burning[nx][ny] = true;
q.add((nx << SHIFT) + ny);
}
}
}
out.printf("%d %d\n", (last >> SHIFT) + 1, (last & COLUMN_MASK) + 1);
}
}
class PandaScanner {
public BufferedReader br;
public StringTokenizer st;
public InputStream in;
public PandaScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(this.in = in));
}
public String nextLine() {
try {
return br.readLine();
}
catch (Exception e) {
return null;
}
}
public String next() {
if (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine().trim());
return next();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while ( sc.hasNextInt() ) {
int n = sc.nextInt();
long m = sc.nextInt();
boolean edge[][] = new boolean[n][n];
long dp[][] = new long[1<<n][n];
for ( long i = 1 ; i<=m ; ++i ) {
int u = sc.nextInt();
int v = sc.nextInt();
-- u;
-- v;
edge[u][v] = edge[v][u] = true;
}
for ( int i = 0 ; i<n ; ++i ) {
dp[1<<i][i] = 1;
}
long res = 0;
for ( int i = 1 ; i<(1<<n) ; ++i ) {
int first = cal(i);
for ( int j = 0 ; j<n ; ++j ) {
if ( dp[i][j]==0 ) {
continue;
}
for ( int k = first ; k<n ; ++k ) {
if ( j==k || !edge[j][k] ) {
continue;
}
if ( k==first && (i&(1<<k))!=0 ) {
res += dp[i][j];
}
if ( (i&(1<<k))==0 ) {
dp[i|(1<<k)][k] += dp[i][j];
}
}
}
}
res -= m;
System.out.println(res/2);
}
}
public static int cal( int x ) {
int ord = 0;
while ( true ) {
if ( (x&(1<<ord))!=0 ) {
break;
}
++ ord;
}
return ord;
}
public static boolean judge( int x ) {
int cnt = 0;
while ( x>=1 ) {
if ( (x&1)==1 ) {
++ cnt;
}
x >>= 1;
}
return cnt >= 3;
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Edu_46A {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int nE = Integer.parseInt(reader.readLine());
int[][] cnt = new int[][] { { 0, 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
for (int i = 0; i < nE; i++) {
String nxt = reader.readLine();
if (nxt.equals("S")) {
cnt[0][0]++;
}
if (nxt.equals("M")) {
cnt[0][1]++;
}
if (nxt.equals("L")) {
cnt[0][2]++;
}
if (nxt.equals("XS")) {
cnt[1][0]++;
}
if (nxt.equals("XL")) {
cnt[1][1]++;
}
if (nxt.equals("XXS")) {
cnt[2][0]++;
}
if (nxt.equals("XXL")) {
cnt[2][1]++;
}
if (nxt.equals("XXXS")) {
cnt[3][0]++;
}
if (nxt.equals("XXXL")) {
cnt[3][1]++;
}
}
for (int i = 0; i < nE; i++) {
String nxt = reader.readLine();
if (nxt.equals("S")) {
cnt[0][0]--;
}
if (nxt.equals("M")) {
cnt[0][1]--;
}
if (nxt.equals("L")) {
cnt[0][2]--;
}
if (nxt.equals("XS")) {
cnt[1][0]--;
}
if (nxt.equals("XL")) {
cnt[1][1]--;
}
if (nxt.equals("XXS")) {
cnt[2][0]--;
}
if (nxt.equals("XXL")) {
cnt[2][1]--;
}
if (nxt.equals("XXXS")) {
cnt[3][0]--;
}
if (nxt.equals("XXXL")) {
cnt[3][1]--;
}
}
int ans = 0;
for (int i = 1; i <= 3; i++) {
ans += Math.abs(cnt[i][0]);
}
int max = 0;
for (int i = 0; i < 3; i++) {
max = Math.max(max, Math.abs(cnt[0][i]));
}
ans += max;
printer.println(ans);
printer.close();
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class C {
public static void main(String[] args) throws Exception {
final int fuck = 2001;
Scanner in = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter(new File("output.txt"));
int n = in.nextInt(), m = in.nextInt();
int[] D = new int[ fuck*fuck ], Q = new int[ fuck*(fuck + 1) ],
dx = new int[] { 1, -1, 0, 0},
dy = new int[] { 0, 0, -1, 1};
Arrays.fill(D, -1);
int H = -1, T = 0;
int k = in.nextInt(), ans = 0;
for(int i = 0; i < k; ++i) {
int x = in.nextInt(), y = in.nextInt();
D[x * fuck + y] = 0;
++H; H %= Q.length;
ans = Q[H] = x * fuck + y;
}
while(H >= T) {
int idx = Q[T++]; T %= Q.length;
int x = idx / fuck, y = idx % fuck;
for(int i = 0; i < 4; ++i) {
int wtf = (dx[i] + x) * fuck + (dy[i] + y);
if(dx[i] + x <= n && dx[i] + x >= 1 && dy[i] + y <= m && dy[i] + y >= 1 && D[wtf] == -1) {
D[wtf] = D[idx] + 1;
++H; H %= Q.length;
Q[H] = wtf;
if(D[wtf] >= D[ans])
ans = wtf;
}
}
}
out.println((ans / fuck) + " " + (ans % fuck));
out.close();
in.close();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class FireAgain {
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream("output.txt"));
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String s[] = r.readLine().split("\\s+");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
int k = Integer.parseInt(r.readLine());
int[][] a = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++)
a[i][j] = Integer.MAX_VALUE;
}
assert k >= 1 && k < n * m;
int max = 0;
StringTokenizer st = new StringTokenizer(r.readLine());
assert st.countTokens() == k;
for(; k > 0; k--) {
int x = Integer.parseInt(st.nextToken()) - 1;
int y = Integer.parseInt(st.nextToken()) - 1;
assert x >= 1 && x <= n && y >= 1 && y <= n;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int d = Math.abs(i - x) + Math.abs(j - y);
if(a[i][j] > d)
a[i][j] = d;
if(k == 1 && a[i][j] > max)
max = a[i][j];
}
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(a[i][j] == max) {
System.out.println((i + 1) + " " + (j + 1));
return;
}
}
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
// Don't place your source in a package
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.stream.Stream;
// Please name your class Main
public class Main {
static FastScanner fs=new FastScanner();
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int Int() {
return Integer.parseInt(next());
}
long Long() {
return Long.parseLong(next());
}
String Str(){
return next();
}
}
public static void main (String[] args) throws java.lang.Exception {
PrintWriter out = new PrintWriter(System.out);
int T=1;
for(int t=0;t<T;t++){
int n=Int();
int A[]=new int[n];
for(int i=0;i<n;i++){
A[i]=Int();
}
Solution sol=new Solution();
sol.solution(out,A);
}
out.flush();
}
public static int Int(){
return fs.Int();
}
public static long Long(){
return fs.Long();
}
public static String Str(){
return fs.Str();
}
}
class Solution{
public void solution(PrintWriter out,int A[]){
Map<Integer,List<int[]>>f=new HashMap<>();
List<int[]>res=new ArrayList<>();
for(int i=0;i<A.length;i++){
int sum=0;
for(int j=i;j<A.length;j++){
sum+=A[j];
if(!f.containsKey(sum))f.put(sum,new ArrayList<>());
List<int[]>list=f.get(sum);
list.add(new int[]{i,j});
}
}
for(Integer key:f.keySet()){
List<int[]>list=f.get(key);
Collections.sort(list,(a,b)->{
return a[1]-b[1];
});
int pre[]=new int[list.size()];
Arrays.fill(pre,-1);
int dp[][]=new int[list.size()][2];
dp[0][0]=1;
dp[0][1]=0;
for(int i=1;i<list.size();i++){
int pair[]=list.get(i);
int l=0,r=i-1;
int pos=-1;
while(l<=r){
int mid=l+(r-l)/2;
if(list.get(mid)[1]<pair[0]){
pos=mid;
l=mid+1;
}
else{
r=mid-1;
}
}
if(pos!=-1){
int mx=1+dp[pos][0];
if(mx>=dp[i-1][0]){
dp[i][0]=mx;
dp[i][1]=i;
pre[i]=dp[pos][1];
}
else{
dp[i][0]=dp[i-1][0];
dp[i][1]=dp[i-1][1];
}
}
else{
dp[i][0]=dp[i-1][0];
dp[i][1]=dp[i-1][1];
}
}
int n=list.size();
if(dp[n-1][0]>res.size()){
res=new ArrayList<>();
int j=dp[n-1][1];
while(j!=-1){
res.add(list.get(j));
j=pre[j];
}
}
}
out.println(res.size());
for(int p[]:res){
out.println((p[0]+1)+" "+(p[1]+1));
}
}
}
/*
;\
|' \
_ ; : ;
/ `-. /: : |
| ,-.`-. ,': : |
\ : `. `. ,'-. : |
\ ; ; `-.__,' `-.|
\ ; ; ::: ,::'`:. `.
\ `-. : ` :. `. \
\ \ , ; ,: (\
\ :., :. ,'o)): ` `-.
,/,' ;' ,::"'`.`---' `. `-._
,/ : ; '" `;' ,--`.
;/ :; ; ,:' ( ,:)
,.,:. ; ,:., ,-._ `. \""'/
'::' `:'` ,'( \`._____.-'"'
;, ; `. `. `._`-. \\
;:. ;: `-._`-.\ \`.
'`:. : |' `. `\ ) \
-hrr- ` ;: | `--\__,'
'` ,'
,-'
free bug dog
*/
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int t = sc.nextInt();
double [] left = new double[n];
double [] right = new double[n];
for (int i = 0; i<n; i++){
int x = sc.nextInt();
int a = sc.nextInt();
double l = x - (double)a/2;
double r = x + (double)a/2;
left[i] = l;
right[i] = r;
}
int answer = 2;
quickSort(left, right, 0, n-1);
for (int i = 0; i<n-1; i++){
if (left[i+1] - right[i] == t){
answer++;
}
if (left[i+1] - right[i] > t){
answer += 2;
}
}
System.out.println(answer);
}
////////////////////////////////////////////////////////////////
int partition(double arr[], int left, int right)
{
int i = left, j = right;
double tmp;
double pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
return i;
}
void quickSort(double arr[], int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1)
quickSort(arr, left, index - 1);
if (index < right)
quickSort(arr,index, right);
}
/////////////////////////////////////////////////////////////////////
static int partition(double arr[], double arr2[], int left, int right)
{
int i = left, j = right;
double tmp; double tmp2;
double pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
tmp2 = arr2[i];
arr2[i] = arr2[j];
arr2[j] = tmp2;
i++;
j--;
}
};
return i;
}
static void quickSort(double arr[], double[]arr2, int left, int right) {
int index = partition(arr, arr2, left, right);
if (left < index - 1)
quickSort(arr, arr2, left, index - 1);
if (index < right)
quickSort(arr, arr2, index, right);
}
////////////////////////////////////////////////////////////////////////
}
|
nlogn
|
15_A. Cottage Village
|
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.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class TwoSets<V> {
private static int n;
private static int a;
private static int b;
private static List<Node<Integer>> nodes = new LinkedList<Node<Integer>>();
private static Map<Integer, Node<Integer>> datas = new HashMap<Integer, Node<Integer>>();
private static Node<Integer> first;
private static Node<Integer> second;
private static TwoSets<Integer> sets = new TwoSets<Integer>();
private static class Node<V> {
V node;
Node<V> parent;
int rank;
int color = -1;
boolean inprogress;
public Node() {
this.parent = this;
}
@Override
public String toString() {
return String.format("{node: %s, parent: %s, rank: %s, color:%s}",
node, parent.node, rank, color);
}
}
public Node<V> makeSet(V x) {
Node<V> node = new Node<V>();
node.node = x;
node.parent = node;
node.rank = 0;
return node;
}
public void link(Node<V> x, Node<V> y) {
if (x.rank > y.rank) {
y.parent = x;
} else {
x.parent = y;
if (x.rank == y.rank) {
y.rank++;
}
}
}
public Node<V> findSet(Node<V> x) {
if (x.parent != x) {
x.parent = findSet(x.parent);
}
return x.parent;
}
public void union(Node<V> x, Node<V> y) {
Node<V> rtX = findSet(x);
Node<V> rtY = findSet(y);
if (rtX.parent != rtY.parent) {
link(rtX, rtY);
}
}
public V getNode(Node<V> x) {
return x.node;
}
private int getColor(Node<V> node) {
int color;
Node<V> parent = findSet(node);
color = parent.color;
return color;
}
private void setColor(Node<V> node, int color) {
Node<V> parent = findSet(node);
parent.color = color;
}
private static Node<Integer> getOrInitNode(Integer key) {
Node<Integer> node = datas.get(key);
if (node == null) {
node = sets.makeSet(key);
datas.put(key, node);
}
return node;
}
private static void initNodes(Scanner scanner) {
int key;
Node<Integer> node;
for (int i = 0; i < n; i++) {
key = scanner.nextInt();
node = getOrInitNode(key);
nodes.add(node);
}
}
private static void unionAll(Node<Integer> value) {
int color = sets.getColor(value);
if (color == 0) {
if (first == null) {
first = value;
} else {
sets.union(first, value);
}
} else if (color == 1) {
if (second == null) {
second = value;
} else {
sets.union(second, value);
}
}
}
private static int getKey(Node<Integer> value, int color) {
int key = value.node;
if (color == 0) {
key = a - key;
} else {
key = b - key;
}
return key;
}
private static boolean checkOpposite(Node<Integer> value, int color) {
boolean valid;
if (value.inprogress) {
valid = Boolean.TRUE;
} else {
value.inprogress = Boolean.TRUE;
int opColor = 1 - color;
int key = getKey(value, opColor);
Node<Integer> node = datas.get(key);
valid = (value.node.equals(key)) || (node == null);
if (!valid) {
key = getKey(node, color);
Node<Integer> child = datas.get(key);
valid = (child != null);
if (valid) {
valid = checkOpposite(child, color);
if (valid) {
sets.union(value, node);
sets.union(value, child);
value.inprogress = Boolean.FALSE;
}
}
}
value.inprogress = Boolean.FALSE;
}
return valid;
}
private static boolean checkNodes(Node<Integer> value, int color) {
boolean valid;
int key = getKey(value, color);
int opColor = 1 - color;
Node<Integer> node = datas.get(key);
valid = (value.node.equals(key)) || (node != null);
if (valid) {
valid = checkOpposite(value, color);
if (valid) {
sets.union(value, node);
sets.setColor(value, color);
} else if (color == 0) {
valid = checkNodes(value, opColor);
}
} else if (color == 0) {
valid = checkNodes(value, opColor);
}
return valid;
}
private static void format(StringBuilder builder, int i) {
if (i > 0) {
builder.append(' ');
}
}
private static String printNodes() {
String text;
StringBuilder builder = new StringBuilder();
Iterator<Node<Integer>> iterator = nodes.iterator();
int i = 0;
Node<Integer> node;
while (iterator.hasNext()) {
format(builder, i);
node = iterator.next();
builder.append(sets.getColor(node));
i++;
}
text = builder.toString().trim();
return text;
}
private static boolean checkNodes(int color) {
boolean valid = Boolean.TRUE;
for (Node<Integer> value : nodes) {
if (sets.getColor(value) == -1) {
valid = checkNodes(value, color);
if (valid) {
unionAll(value);
} else {
break;
}
}
}
return valid;
}
private static void calculate() {
int color = 0;
boolean valid = checkNodes(color);
String message = "NO";
if (valid) {
message = "YES";
String array = printNodes();
System.out.println(message);
System.out.println(array);
} else {
System.out.println(message);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
n = scanner.nextInt();
a = scanner.nextInt();
b = scanner.nextInt();
initNodes(scanner);
calculate();
} finally {
scanner.close();
}
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.util.Scanner;
public class B_14 {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
for(int test = 0; test < t; test++){
int n = input.nextInt();
if(n % 2 == 0){
if(Math.sqrt(n / 2) == (int)(Math.sqrt(n / 2))){
System.out.println("YES");
}else if(n % 4 == 0 && Math.sqrt(n / 4) == (int)(Math.sqrt(n / 4))){
System.out.println("YES");
}else{
System.out.println("NO");
}
}else{
System.out.println("NO");
}
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if (((n % 4) == 0) || ((n % 7) == 0) || ((n % 44) == 0) || ((n % 47) == 0) || ((n % 74) == 0) || ((n % 77) == 0) || ((n % 444) == 0) || ((n % 447) == 0) || ((n % 474) == 0) || ((n % 477) == 0) || ((n % 744) == 0) || ((n % 747) == 0) || ((n % 774) == 0) || ((n % 777) == 0))
System.out.print("YES");
else
System.out.print("NO");
in.close();
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rishabhdeep Singh
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int MOD = (int) 1e9 + 7;
long power(long a, long k) {
long res = 1;
while (k > 0) {
if ((k & 1) != 0) {
res = res * a % MOD;
}
a = a * a % MOD;
k /= 2;
}
return res;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
long x = in.nextLong(), k = in.nextLong();
if (x == 0) {
out.println(0);
return;
}
long res = ((power(2, k + 1) % MOD) * (x % MOD)) % MOD;
long temp = power(2, k);
res = res - temp + 1;
while (res < 0) res += MOD;
out.println(res);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] A = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
A[i] = in.nextInt();
sum += A[i];
}
Arrays.sort(A);
int cnt = 0;
int temp = 0;
for (int i = n - 1; i >= 0; i--) {
temp += A[i];
sum -= A[i];
cnt++;
if (temp > sum)
break;
}
System.out.println(cnt);
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.*;
import java.util.Arrays;
public class Main{
public static void main(String[] args) throws Exception {
int n = nextInt();
int a = nextInt();
int b = nextInt();
int[] tasks = new int[n];
for(int i = 0; i < n; i++){
tasks[i] = nextInt();
}
Arrays.sort(tasks);
exit(tasks[b] - tasks[b-1]);
}
private static PrintWriter out;
private static BufferedReader inB;
private static boolean FILE = false;
static {
try {
out = new PrintWriter(FILE ? (new FileOutputStream("output.txt")) : System.out);
inB = new BufferedReader(new InputStreamReader(FILE ? new FileInputStream("input.txt") : System.in));
} catch(Exception e) {e.printStackTrace();}
}
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 int nextInt() throws Exception {
in.nextToken();
return (int)in.nval;
}
private static String nextString() throws Exception {
in.nextToken();
return in.sval;
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.util.Scanner;
public class TaskD {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
int m = s.nextInt();
int inv = 0;
// count inversions
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
inv++;
}
}
}
boolean odd = (inv % 2 == 1);
for (int i = 0; i < m; i++) {
int l = s.nextInt();
int r = s.nextInt() + 1; // r excluding, l including
int num = (r - l)*(r - l - 1)/2;
if (num % 2 == 1) {
odd = !odd;
}
System.out.println((odd) ? "odd" : "even");
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int n, m, k;
static int inf = (int) 1e9;
static class Pair {
int x, y;
Pair(int a, int b) {
x = a; y = b;
}
}
static int[] dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1};
static boolean valid(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < m;
}
static int[][] bfs(int[] xs, int[] ys) {
int[][] dist = new int[n][m];
for(int i = 0; i < n; i++)
Arrays.fill(dist[i], inf);
Queue<Pair> q = new LinkedList<>();
for(int i = 0; i < k; i++) {
dist[xs[i]][ys[i]] = 0;
q.add(new Pair(xs[i], ys[i]));
}
while(!q.isEmpty()) {
Pair p = q.remove();
for(int d = 0; d < 4; d++) {
int nx = p.x + dx[d], ny = p.y + dy[d];
if(valid(nx, ny) && dist[nx][ny] == inf) {
dist[nx][ny] = dist[p.x][p.y] + 1;
q.add(new Pair(nx, ny));
}
}
}
return dist;
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner();
int n = in.nextInt() ;
int m = in.nextInt();
int k = in.nextInt();
int x[] = new int[k] ;
int y[] = new int[k] ;
int trees [][] = new int [n][m] ;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
trees[i][j]=Integer.MAX_VALUE ;
for (int i = 0; i < k; i++)
{
x[i]=in.nextInt()-1;
y[i]=in.nextInt()-1;
trees[x[i]][y[i]]=0 ;
}
int dis = Integer.MIN_VALUE ; ;
int xp=0; ;
int yp=0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if(trees[i][j] != 0)
for (int j2 = 0; j2 < k; j2++)
trees[i][j]=Math.min(trees[i][j], Math.abs(i-x[j2])+Math.abs(j-y[j2]));
for (int i = 0; i <n; i++)
for (int j = 0; j < m; j++)
if(trees[i][j] > dis)
{
dis=trees[i][j];
xp=i+1;
yp=j+1;
}
PrintWriter out = new PrintWriter("output.txt");
out.printf("%d %d\n", xp ,yp);
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() throws FileNotFoundException {
br = new BufferedReader(new FileReader("input.txt"));
}
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());
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.BufferedReader;
import static java.lang.Math.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class CodeforcesA implements Runnable {
public static final String taskname = "A";
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
public static void main(String[] args) {
new Thread(new CodeforcesA()).start();
}
static class Square implements Comparable<Square>{
int x, a;
public Square(int x, int a) {
this.x = x;
this.a = a;
}
@Override
public int compareTo(Square o) {
return x - o.x;
}
int distance(Square a, int t) {
double dist = a.x - x - this.a / 2.0 - a.a / 2.0;
if(dist > t) return 2;
else if(abs(dist - t) < 1e-9) return 1;
return 0;
}
public String toString() {
return x + " " + a;
}
}
void solve() throws IOException {
int n = nextInt(), t = nextInt();
Square[] x = new Square[n];
for(int i = 0; i < n; ++i) {
x[i] = new Square(nextInt(), nextInt());
}
Arrays.sort(x);
long res = 2;
for(int i = 0; i < n - 1; ++i) {
res += x[i].distance(x[i + 1], t);
}
out.println(res);
}
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
//in = new BufferedReader(new FileReader(new File("input.txt")));
out = new PrintWriter(System.out);
//out = new PrintWriter(new File("output.txt"));
solve();
out.flush();
out.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String nextLine() throws IOException {
tok = null;
return in.readLine();
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.ArrayList;
public class C{
static long s;
public static void main(String[] args)throws IOException {
Reader.init(System.in);
long n=Reader.nextLong();
s=Reader.nextLong();
long lo=1,hi=n,mid;
while(lo<hi){
mid=(lo+hi)/2;
if(diff(mid)>=s)
hi=mid;
else
lo=mid+1;
}
if(diff(lo)>=s)
System.out.println(n-lo+1);
else
System.out.println(0);
}
static long diff(long n){
String s=String.valueOf(n);
int sum=0;
for(int i=0;i<s.length();i++){
sum+=Integer.parseInt(s.valueOf(s.charAt(i)));
}
return (n-sum);
}
}
/** Class for buffered reading int and double values */
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.