src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.io.PrintWriter;
import java.util.Scanner;
public class D {
public void solve(Scanner in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n + 1];
for(int i = 1; i <= n; ++i) a[i] = in.nextInt();
int[] rangeInv = new int[n + 1];
BIT bit = new BIT(n + 1);
for(int i = 1; i <= n; ++i) {
int cur = a[i];
int inv = (int) bit.sum(cur, n);
rangeInv[i] = rangeInv[i - 1] + inv;
bit.add(cur, 1);
}
int m = in.nextInt();
int curTotal = rangeInv[n];
for(int qq = 0; qq < m; ++qq) {
int l = in.nextInt();
int r = in.nextInt();
int N = r - l + 1;
int total = N * (N - 1) / 2;
int cur = rangeInv[r] - rangeInv[l - 1];
int newInv = total - cur;
curTotal -= cur;
curTotal += newInv;
if(curTotal % 2 == 0) {
out.println("even");
} else {
out.println("odd");
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
new D().solve(in, out);
in.close();
out.close();
}
class BIT {
long[] tree;
int n;
public BIT(int n) {
this.n = n;
tree = new long[n + 1];
}
public void add(int i, long val)
{
while(i <= n)
{
tree[i] += val;
i += i & -i;
}
}
public long sum(int to)
{
long res = 0;
for(int i = to; i >= 1; i -= (i & -i))
{
res += tree[i];
}
return res;
}
public long sum(int from, int to) {
return sum(to) - sum(from - 1);
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class B {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static void main(String[] args) throws Exception {
String[] split = br.readLine().split(" ");
long n = Long.parseLong(split[0]);
long k = Long.parseLong(split[1]);
long left = -1;
long right = n + 1;
while(right - left >= 2) {
long mid = (left + right) / 2; // 10
// if(mid > n) {
// right = mid;
// continue;
// }
long newN = n - mid; //-5
long temp = newN * (newN + 1) / 2; //10
long eh = temp - k - mid;
if(eh == 0) {
pw.println(mid);
break;
}
else if(eh < 0)
right = mid;
else
left = mid;
}
pw.close();
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.*;
import java.math.*;
public class fuck {
public static int[] a;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long r = input.nextLong();
long l = input.nextLong();
if((l - r + 1) < 3){
System.out.println(-1);
}
else
{
if(r % 2 == 0)
System.out.println(r + " " + (r +1)+ " " + (r+2) );
else{
if(l -r + 1 >3){
++r;
System.out.println(r + " " + (r +1)+ " " + (r+2) );
}
else
System.out.println(-1);
}
}
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class cf8c {
static int n;
static int[] bb;
static int[] memo;
static int[][] cost;
static FastIO in = new FastIO(), out = in;
public static void main(String[] args) {
vec2 cen = new vec2(in.nextInt(),in.nextInt());
n = in.nextInt();
cost = new int[n][n];
vec2[] v = new vec2[n];
for(int i=0; i<n; i++)
v[i] = new vec2(in.nextInt(),in.nextInt());
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
cost[i][j] = v[i].dist(cen) + v[i].dist(v[j]) + v[j].dist(cen);
memo = new int[1<<n];
bb = new int[1<<n];
Arrays.fill(memo,-1);
out.println(go(0));
build(0);
out.close();
}
static void build(int mask) {
if(mask == (1<<n)-1) {
out.println(0);
return;
}
int first = 0;
while((mask & (1<<first)) != 0) first++;
int second = bb[mask];
out.print("0 " + (first+1) + " ");
if(second != first)
out.print((second+1)+" ");
build(mask|(1<<first)|(1<<second));
}
static int go(int mask) {
if(mask == (1<<n)-1) return 0;
if(memo[mask] != -1) return memo[mask];
int first = 0;
int ans = Integer.MAX_VALUE;
while((mask & (1<<first)) != 0) first++;
for(int second = first; second < n; second++) {
if((mask & (1<<second)) != 0) continue;
int tans = cost[first][second] + go(mask|(1<<first)|(1<<second));
if(tans < ans) {
ans = tans;
bb[mask] = second;
}
}
return memo[mask] = ans;
}
static class vec2 {
int x, y;
vec2(int a, int b) {
x = a; y = b;
}
vec2 sub(vec2 v) {
return new vec2(x-v.x,y-v.y);
}
int dist(vec2 v) {
return sub(v).mag2();
}
int mag2() {
return x*x+y*y;
}
}
static class FastIO extends PrintWriter {
BufferedReader br;
StringTokenizer st;
public FastIO() {
this(System.in,System.out);
}
public FastIO(InputStream in, OutputStream out) {
super(new BufferedWriter(new OutputStreamWriter(out)));
br = new BufferedReader(new InputStreamReader(in));
scanLine();
}
public void scanLine() {
try {
st = new StringTokenizer(br.readLine().trim());
} catch(Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public int numTokens() {
if(!st.hasMoreTokens()) {
scanLine();
return numTokens();
}
return st.countTokens();
}
public String next() {
if(!st.hasMoreTokens()) {
scanLine();
return next();
}
return st.nextToken();
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
private static final double EPS = 1e-11;
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
double a = nextDouble();
double v = nextDouble();
double l = nextDouble();
double d = nextDouble();
double w = nextDouble();
double ans = 0.0;
if (v < w + EPS || sqr(w) / 2 / a > d - EPS) {
double t1 = sqrt(2 * l / a);
double t2 = v / a;
if (t1 < t2 + EPS) {
ans = t1;
} else {
ans = t2 + (l - a * sqr(t2) / 2) / v;
}
} else {
double t1 = v / a;
double t2 = (v - w) / a;
double s12 = a * sqr(t1) / 2 + w * t2 + a * sqr(t2) / 2;
if (s12 < d + EPS) {
ans += t1 + t2 + (d - s12) / v;
} else {
double ta = sqrt(d / a + sqr(w / a) / 2);
double tb = ta - w / a;
ans += ta + tb;
}
double r = l - d;
double tm = (v - w) / a;
double tx = (sqrt(sqr(w) + 2 * a * r) - w) / a;
if (tx < tm + EPS) {
ans += tx;
} else {
ans += tm + (r - w * tm - a * sqr(tm) / 2) / v;
}
}
out.printf(Locale.US, "%.12f%n", ans);
out.close();
}
double sqr(double x) {
return x * x;
}
String nextToken() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
public class Main {
private static void solve() {
long x = nl();
long k = nl();
long mod = 1000000000 + 7;
if (x == 0) {
System.out.println(0);
} else if (k == 0) {
System.out.println(x * 2 % mod);
} else {
//x > 0, n > 0
x %= mod;
long a;
a = (x - 1 + mod) * pow(2, k, mod) + 1;
a %= mod;
long b = x * pow(2, k, mod);
b %= mod;
System.out.println((a + b) % mod);
}
}
public static long pow(long a, long n, long mod)
{
// a %= mod;
long ret = 1; // 1%mod if mod=1,n=0
int x = 63-Long.numberOfLeadingZeros(n);
for(;x >= 0;x--){
ret = ret * ret % mod;
if(n<<~x<0)ret = ret * a % mod;
}
return ret;
}
public static void main(String[] args) {
new Thread(null, new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
String debug = args.length > 0 ? args[0] : null;
if (debug != null) {
try {
is = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(debug));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
reader = new java.io.BufferedReader(new java.io.InputStreamReader(is), 32768);
solve();
out.flush();
tr((System.currentTimeMillis() - start) + "ms");
}
}, "", 64000000).start();
}
private static java.io.InputStream is = System.in;
private static java.io.PrintWriter out = new java.io.PrintWriter(System.out);
private static java.util.StringTokenizer tokenizer = null;
private static java.io.BufferedReader reader;
public static String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new java.util.StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
private static double nd() {
return Double.parseDouble(next());
}
private static long nl() {
return Long.parseLong(next());
}
private static int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private static char[] ns() {
return next().toCharArray();
}
private static long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private static int[][] ntable(int n, int m) {
int[][] table = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[i][j] = ni();
}
}
return table;
}
private static int[][] nlist(int n, int m) {
int[][] table = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
table[j][i] = ni();
}
}
return table;
}
private static int ni() {
return Integer.parseInt(next());
}
private static void tr(Object... o) {
if (is != System.in)
System.out.println(java.util.Arrays.deepToString(o));
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class B {
static BufferedReader in;
static StringTokenizer st;
static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int n = nextInt();
int k = nextInt();
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = nextInt();
}
Set<Integer> set_1 = new HashSet<Integer>();
for (int i = 1; i <= n; i++) {
set_1.add(a[i]);
if (set_1.size() == k) {
Set<Integer> set_2 = new HashSet<Integer>();
for (int j = i; j >= 1; j--) {
set_2.add(a[j]);
if (set_2.size() == k) {
out.print(j + " " + i);
out.close();
return;
}
}
}
}
out.print("-1 -1");
out.close();
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author beginner1010
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
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, Integer> lastIndex = new HashMap<>();
HashMap<Integer, Integer> maxSize = new HashMap<>();
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += a[j];
if (maxSize.containsKey(sum) == false) {
maxSize.put(sum, 0);
}
int curMaxSize = maxSize.get(sum);
int curLastIndex = curMaxSize == 0 ? -1 : lastIndex.get(sum);
if (curMaxSize == 0 || curLastIndex < i) {
curMaxSize++;
curLastIndex = j;
} else if (curLastIndex >= j) {
curLastIndex = j;
}
maxSize.put(sum, curMaxSize);
lastIndex.put(sum, curLastIndex);
}
}
int bestSum = -1;
int bestSize = -1;
for (int sum : maxSize.keySet()) {
if (maxSize.get(sum) > bestSize) {
bestSize = maxSize.get(sum);
bestSum = sum;
}
}
ArrayList<Interval> best = new ArrayList<>();
lastIndex = new HashMap<>();
maxSize = new HashMap<>();
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += a[j];
if (sum != bestSum)
continue; // consider only bestSums
if (maxSize.containsKey(sum) == false) {
maxSize.put(sum, 0);
}
int curMaxSize = maxSize.get(sum);
int curLastIndex = curMaxSize == 0 ? -1 : lastIndex.get(sum);
if (curMaxSize == 0 || curLastIndex < i) {
curMaxSize++;
curLastIndex = j;
best.add(new Interval(i, j));
} else if (curLastIndex >= j) {
curLastIndex = j;
best.set(best.size() - 1, new Interval(i, j));
}
maxSize.put(sum, curMaxSize);
lastIndex.put(sum, curLastIndex);
}
}
out.println(bestSize);
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.*;
import java.io.*;
import java.math.*;
public class Test5 {
static StreamTokenizer st = new StreamTokenizer(new InputStreamReader(System.in));
static int[] m;
public static void main(String[] z) throws Exception {
PrintWriter pw = new PrintWriter(System.out);
Scanner s = new Scanner(System.in);
int a = ni(), b=ni(), o=2;
m = new int[a];
for(int q=0; q<a; q++) m[q] = ni();
Arrays.sort(m);
for(int q=1; q<a; q++){
if(m[q]-m[q-1]==b*2) o++;
else if(m[q]-m[q-1]>b*2) o+=2;
}
System.out.println(o);
pw.flush();
}
static int ni() throws Exception{
st.nextToken();
return (int)st.nval;
}
static String ns() throws Exception{
st.nextToken();
return st.sval;
}
static long gcd(long a, long b){
for(; a>0 && b>0;)
if(a>b) a%=b;
else b%=a;
return a+b;
}
static class PyraSort {
private static int heapSize;
public static void sort(int[] a) {
buildHeap(a);
while (heapSize > 1) {
swap(a, 0, heapSize - 1);
heapSize--;
heapify(a, 0);
}
}
private static void buildHeap(int[] a) {
heapSize = a.length;
for (int i = a.length / 2; i >= 0; i--) {
heapify(a, i);
}
}
private static void heapify(int[] a, int i) {
int l = 2 * i + 2;
int r = 2 * i + 1;
int largest = i;
if (l < heapSize && a[i] < a[l]) {
largest = l;
}
if (r < heapSize && a[largest] < a[r]) {
largest = r;
}
if (i != largest) {
swap(a, i, largest);
heapify(a, largest);
}
}
private static void swap(int[] a, int i, int j) {
a[i] ^= a[j] ^= a[i];
a[j] ^= a[i];
}
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class P911d {
private static void solve() {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
int cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
cnt++;
}
}
}
cnt %= 2;
int m = nextInt();
for (int i = 0; i < m; i++) {
int l = nextInt();
int r = nextInt();
int size = r - l + 1;
int sum = (size * (size - 1)) / 2;
sum %= 2;
cnt += sum;
cnt %= 2;
out.println(cnt == 0 ? "even" : "odd");
}
}
private static void run() {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
private static StringTokenizer st;
private static BufferedReader br;
private static PrintWriter out;
private static String next() {
while (st == null || !st.hasMoreElements()) {
String s;
try {
s = br.readLine();
} catch (IOException e) {
return null;
}
st = new StringTokenizer(s);
}
return st.nextToken();
}
private static int nextInt() {
return Integer.parseInt(next());
}
private static long nextLong() {
return Long.parseLong(next());
}
public static void main(String[] args) {
run();
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.*;
public class maestro{
public static long inversions(long[] arr) {
long x = 0;
int n = arr.length;
for (int i = n - 2; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
x++;
//temp++;
}
//if (temp%2==0) inv_a[i][j]=0;
//else inv_a[i][j]=1;
}
}
return x;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] arr = new long[n];
for (int i=0;i<n;i++) arr[i] = sc.nextLong();
long m = sc.nextLong();
long x = inversions(arr)%2;
for (int i=0;i<m;i++){
int l = sc.nextInt()-1;
int r = sc.nextInt()-1;
if ((r-l+1)%4>1) x=(x+1)%2;
if (x==1) System.out.println("odd");
else System.out.println("even");
}
/*int inv=0;
int temp=0;
long[][] inv_a = new long[n][n];
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
inv_a[i][j]=-1;
}
}
for (int i=n-2;i>=0;i--){
for (int j=i+1;j<n;j++){
if (arr[i]<arr[j]){
inv++;
temp++;
}
if (temp%2==0) inv_a[i][j]=0;
else inv_a[i][j]=1;
}
temp=0;
}
if (inv%2==0) inv=0;
else inv=1;
for (int i=0;i<m;i++){
int l = sc.nextInt()-1;
int r = sc.nextInt()-1;
long[][] exp = new long[r-l+1][r-l+1];
for (int k=0;k<exp.length;k++){
for (int h=0;h<exp.length;h++){
exp[k][h]=-1;
}
}
for (int j=l;j<=r;j++){
}
}*/
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class A implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException{
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException{
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException{
return Integer.parseInt(readString());
}
long readLong() throws IOException{
return Long.parseLong(readString());
}
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
public static void main(String[] args){
new Thread(null, new A(), "", 256 * (1L << 20)).start();
}
public void run(){
try{
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = "+(t2-t1));
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
void solve() throws IOException{
int n = readInt();
int[] a = new int[n];
for (int i = 0; i < n; i++){
a[i] = readInt();
}
Arrays.sort(a);
a[n-1] = a[n-1] == 1? 2:1;
Arrays.sort(a);
for (int i = 0; i < n; i++){
out.print(a[i] + " ");
}
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.util.*;
import java.awt.*;
public class A
{
static Comparator<Point> cmp = new Comparator<Point>()
{
public int compare(Point a, Point b)
{
if(a.x < b.x)
return -1;
else if(a.x > b.x)
return 1;
return 0;
}
};
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
while(scan.hasNextInt())
{
int n = scan.nextInt();
int k = scan.nextInt();
Point[] a = new Point[n];
for(int i=0;i < n;i++)
{
a[i] = new Point();
a[i].x = scan.nextInt();
a[i].y = scan.nextInt();
}
Arrays.sort(a, cmp);
int rtn = 0;
ArrayList<Double> ans = new ArrayList<Double>();
for(int i=0;i < n;i++)
{
//Left
double lb = a[i].x - (a[i].y / 2.0) - k;
double pos = lb + (k/2.0);
boolean good = true;
for(int j=0;j < ans.size();j++)
if(Math.abs(ans.get(j) - pos) < 0.0000001)
good = false;
if(good && (i == 0 || a[i-1].x + (a[i-1].y / 2.0) <= lb))
{
rtn++;
ans.add(pos);
}
double rb = a[i].x + (a[i].y / 2.0) + k;
pos = rb - (k/2.0);
good = true;
for(int j=0;j < ans.size();j++)
if(Math.abs(ans.get(j) - pos) < 0.0000001)
good = false;
if(good && (i == n-1 || a[i+1].x - (a[i+1].y / 2.0) >= rb))
{
rtn++;
ans.add(pos);
}
}
System.out.println(rtn);
}
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Queue;
import java.io.BufferedReader;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Nasko
*/
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);
}
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
int M = in.nextInt();
int[][] dist = new int[N][M];
for (int[] ini : dist) Arrays.fill(ini, (1 << 30));
int K = in.nextInt();
Queue<Integer> q = new LinkedList<Integer>();
for (int k = 0; k < K; ++k) {
int r = in.nextInt() - 1;
int c = in.nextInt() - 1;
dist[r][c] = 0;
q.offer(r);
q.offer(c);
}
int[] dx = new int[]{1, -1, 0, 0};
int[] dy = new int[]{0, 0, 1, -1};
while (!q.isEmpty()) {
int rr = q.poll();
int cc = q.poll();
for (int a = 0; a < 4; ++a) {
int x = dx[a] + rr;
int y = dy[a] + cc;
if (x >= 0 && x < N && y >= 0 && y < M) {
if (dist[x][y] > dist[rr][cc] + 1) {
dist[x][y] = dist[rr][cc] + 1;
q.offer(x);
q.offer(y);
}
}
}
}
int max = 0;
for (int i = 0; i < N; ++i)
for (int j = 0; j < M; ++j)
max = Math.max(max, dist[i][j]);
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
if (max == dist[i][j]) {
out.println((i + 1) + " " + (j + 1));
return;
}
}
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
static final int MAXN= 1005;
static final long MOD =1_000_000_007;
static final boolean DEBUG= false;
static int n, m;
static long stlr[][]= new long[MAXN][MAXN],bell[]= new long[MAXN],occ[];
static PrintStream cerr=System.err;
public static void main(String[] args) {
// TODO Auto-generated method stub
Readin();
stlr[0][0]= bell[0] =1;
for (int i=1; i<=m; i++)
for (int j=1;j<=i;j++) {
stlr[i][j]= (stlr[i-1][j-1]+stlr[i-1][j]*(long)j)%MOD;
bell[i]= (bell[i]+stlr[i][j])%MOD;
}
if (DEBUG)
for (int i=1; i<=m; i++) cerr.println("Bell["+i+"] ="+bell[i]);
Arrays.sort(occ);
if (DEBUG) {
cerr.println("After Sorting");
for (int i=0;i<m; i++) cerr.println(occ[i]+" ");}
long ans=1;
for (int i=0,j=0; i<m; i=j) {
for (j=i+1; j<m && occ[i]==occ[j];j++);
ans= (ans*bell[j-i])%MOD;
}
System.out.println(ans);
}
static void Readin() {
Scanner cin;
if ( !DEBUG)cin= new Scanner(System.in);
else {
try {
cin = new Scanner(new File("input.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
if ( DEBUG)cerr.println("Not Fount input.txt");
return ;
}
}
m = cin.nextInt(); n=cin.nextInt();
occ= new long[m];
for (int i=0; i<n; i++) {
String s= cin.next();
for (int j=0;j <m; j++)
occ[j]|=((long)(s.charAt(j)-'0'))<<i;
}
cin.close();
}
}
|
quadratic
|
908_E. New Year and Entity Enumeration
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class History {
static final int INF = (int)1E9;
static final double EPS = 1E-9;
static final long MOD = INF + 9;
static long powmod(long p) {
long res = 1;
long d = 2;
while (p > 0) {
if (p % 2 == 1) {
res = (res * d) % MOD;
p--;
}
else {
d = (d * d) % MOD;
p /= 2;
}
}
return res % MOD;
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
long n = in.nextLong();
long m = in.nextLong();
long k = in.nextLong();
long ans = 0;
long t = (k - 1) * (n - m);
if (t <= m) {
n -= k * (n - m);
long g = n / k;
ans = 2 * k * (powmod(g) - 1) + n % k;
ans = (ans + t) % MOD;
}
else {
ans = m;
}
System.out.println(ans % MOD);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
};
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.text.DecimalFormat;
import java.util.Scanner;
/**
*
* @author Alvaro
*/
public class Main{
public static int n;
public static double [] dp;
public static double [][] p;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
dp = new double[1<<n];
p = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
p[i][j]= in.nextDouble();
}
}
for (int i = 0; i <(1<<n); i++) {
dp[i] = -1;
}
dp[(1<<n)-1]=1;
DecimalFormat d = new DecimalFormat("0.000000");
System.out.print(d.format(f(1<<0)));
for (int i = 1; i < n; i++) {
System.out.print(" "+d.format(f(1<<i)));
}
}
public static double f(int mask) {
if(dp[mask]>-0.5) return dp[mask];
dp[mask] = 0;
int vivos = 1;
for (int i = 0; i < n; i++)
if((mask>>i)%2==1) vivos++;
double pares = (vivos*(vivos-1))/2;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if((mask&(1<<i))!=0&&(mask&(1<<j))==0){
dp[mask]+=f(mask|(1<<j))*p[i][j]/pares;
}
}
}
return dp[mask];
}
}
|
np
|
16_E. Fish
|
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.
*/
//package newpackage;
import java.util.*;
/**
*
* @author parpaorsa
*/
public class NewClass {
static Scanner in=new Scanner(System.in);
public static void main(String[] args) {
int n = in.nextInt(),ans=Integer.MAX_VALUE,t=0;
String x = in.next();
for (int i = 0; i < n; i++) {
if(x.charAt(i)=='-')t--;
else t++;
ans=Math.min(ans,t);
}
if(ans <= 0)
System.out.println(Math.abs(ans)+t);
else
System.out.println(t);
}
}
|
linear
|
1159_A. A pile of stones
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class E implements Runnable {
public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();}
int n, m;
char[] str;
int[][] occs, cost;
int[] dp;
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
n = fs.nextInt(); m = fs.nextInt();
str = fs.next().toCharArray();
occs = new int[m][m];
for(int i = 0; i < n-1; i++) {
occs[str[i]-'a'][str[i+1]-'a']++;
occs[str[i+1]-'a'][str[i]-'a']++;
}
//cost[mask][v] = numPairs with v for some all bits on in mask
int all = (1<<m)-1;
cost = new int[m][1<<m];
for(int i = 0; i < m; i++) {
for(int mask = 1; mask < all; mask++) {
if(((1<<i)&mask) > 0) continue;
int lb = mask & (-mask);
int trail = Integer.numberOfTrailingZeros(lb);
int nmask = mask ^ lb;
cost[i][mask] = cost[i][nmask]+occs[i][trail];
}
}
dp = new int[1<<m];
for(int mask = dp.length-2; mask >= 0; mask--) {
int addOn = 0;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
addOn += cost[nxt][mask];
}
int res = oo;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
int ret = addOn+dp[mask | (1<<nxt)];
res = min(res, ret);
}
dp[mask] = res;
}
System.out.println(dp[0]);
out.close();
}
int oo = (int)1e9;
int min(int a, int b) {
if(a < b) return a;
return b;
}
class FastScanner {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
}
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
BPhoenixAndPuzzle solver = new BPhoenixAndPuzzle();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class BPhoenixAndPuzzle {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
if (n % 2 == 1) {
out.println("NO");
return;
}
n /= 2;
int h = (int) Math.sqrt(n + 0.5);
if (h * h == n) {
out.println("YES");
return;
}
if (n % 2 == 1) {
out.println("NO");
return;
}
n /= 2;
h = (int) Math.sqrt(n + 0.5);
if (h * h == n) {
out.println("YES");
} else out.println("NO");
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
writer.print('\n');
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String next() {
int c;
while (isSpaceChar(c = this.read())) {
;
}
StringBuilder result = new StringBuilder();
result.appendCodePoint(c);
while (!isSpaceChar(c = this.read())) {
result.appendCodePoint(c);
}
return result.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.*;
import java.util.StringTokenizer;
public class C {
static final int MOD = (int)1e9 + 7;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
long x = sc.nextLong(), k = sc.nextLong();
if(x == 0)
out.println(0);
else
out.println(((x % MOD * 2 - 1 + MOD) % MOD * modPow(2, k) % MOD + 1) % MOD);
out.close();
}
static long modPow(long b, long e) {
long res = 1;
while(e > 0) {
if((e & 1) == 1)
res = res * b % MOD;
b = b * b % MOD;
e >>= 1;
}
return res;
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException { return br.ready(); }
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main implements Runnable {
public void _main() throws IOException {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
Arrays.sort(a);
for (int i = 1; i < n; i++)
if (a[i] != a[0]) {
out.print(a[i]);
return;
}
out.print("NO");
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
private String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String rl = in.readLine();
if (rl == null)
return null;
st = new StringTokenizer(rl);
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(next());
}
private long nextLong() throws IOException {
return Long.parseLong(next());
}
private double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) {
new Thread(new Main()).start();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
_main();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(202);
}
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class A {
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
Application solver = new Application();
solver.solve(System.in, out);
out.close();
}
}
class Application {
int max(int a, int b) { return a > b ? a : b; }
public void solve(InputStream in, PrintWriter out) {
Scanner scanner = new Scanner(in);
int n = scanner.nextInt();
int n1 = n/10;
int n2 = (n/100)*10+(n%10);
int m = max(max(n1, n2), n);
out.println(m);
}
}
|
constant
|
313_A. Ilya and Bank Account
|
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 D5 {
static StringTokenizer st;
static BufferedReader in;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
double a = nextInt();
double v = nextInt();
double L = nextInt();
double d = nextInt();
double w = nextInt();
double ans = 0;
if (w >= v)
ans = go(0, a, L, v);
else {
ans = go(Math.min(w, Math.sqrt(2*a*d)), a, L-d, v);
if (2*a*d < w*w)
ans += Math.sqrt(2*d/a);
else {
if (d-v*v/(2*a) >= (v*v-w*w)/(2*a))
ans += v/a+(v-w)/a+(d-v*v/(2*a)-(v*v-w*w)/(2*a))/v;
else {
double x = Math.sqrt((w*w+2*a*d)/2);
ans += x/a+(x-w)/a;
}
}
}
System.out.println(ans);
pw.close();
}
private static double go(double v0, double a, double s, double vmax) {
double t = (vmax-v0) / a;
if (v0*t+a*t*t/2 < s)
return t+(s-v0*t-a*t*t/2) / vmax;
else {
double D = v0*v0+2*a*s;
return (-v0+Math.sqrt(D))/a;
}
}
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(in.readLine());
}
return st.nextToken();
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception{
FastReader sc=new FastReader();
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
int n=sc.nextInt();
int[] font=new int[n];
int[] cost=new int[n];
for(int i=0;i<n;i++) {
font[i]=sc.nextInt();
}
for(int i=0;i<n;i++) {
cost[i]=sc.nextInt();
}
int[] dou= new int[n];
for(int i=0;i<n;i++) {
int min=Integer.MAX_VALUE;
for(int j=0;j<i;j++) {
if(font[j]<font[i]) {
if(min>cost[i]+cost[j]) {
min=cost[i]+cost[j];
}
}
}
dou[i]=min;
}
int ans=Integer.MAX_VALUE;
for(int i=0;i<n;i++) {
int min=Integer.MAX_VALUE;
for(int j=0;j<i;j++) {
if(dou[j]!=Integer.MAX_VALUE && font[j]<font[i]) {
if(min>dou[j]+cost[i]) {
min=dou[j]+cost[i];
}
}
}
if(min<ans) {
ans=min;
}
}
if(ans==Integer.MAX_VALUE) {
System.out.println(-1);
}
else {
System.out.println(ans);
}
}
}
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;
}
}
|
quadratic
|
987_C. Three displays
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
String in1 = in.readLine();
String store = "";
HashSet<Character> contain = new HashSet<Character>();
for(int i = 0; i < n;i++){
if(!contain.contains(in1.charAt(i))){
store += in1.charAt(i);
contain.add(in1.charAt(i));
}
}
int[] index = new int[store.length()];
for(int i = 0; i < store.length(); i++){
index [i] = -1;
}
HashSet<Integer> index2 = new HashSet<Integer>();
ArrayList<Integer> index3 = new ArrayList<Integer>();
int min = Integer.MAX_VALUE;
for(int i = 0; i < n; i++){
int index4 = store.indexOf(in1.charAt(i));
if(index[index4] == -1){
index[index4] = i;
index2.add(i);
index3.add(i);
}
else{
index2.remove(index[index4]);
index2.add(i);
index3.add(i);
index[index4] = i;
}
if(index2.size() == index.length){
while(!index2.contains(index3.get(0))){
index3.remove(0);
}
min = Math.min(min, i - index3.get(0)+ 1);
}
}
System.out.println(min);
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class TestClass {
static PrintWriter out = new PrintWriter(System.out);
public static void main(String args[] ) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s[] = in.readLine().split(" ");
long n = Long.parseLong(s[0]);
long k = Long.parseLong(s[1]);
long x = bs(n,k);
out.println(n-x+1);
out.close();
}
public static long bs(long n,long k)
{
long l=0,h=n;
while(l<=h)
{
long mid = l + (h-l)/2;
long x = mid - sum(mid);
if(x>=k)
{
h = mid-1;
}
else
{
l = mid+1;
}
}
return l;
}
public static long sum(long x)
{
long ans=0;
while(x>0)
{
ans += x%10;
x=x/10;
}
return ans;
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Scanner;
public class Main implements Runnable {
/**
* @param args
*/
public static void main(String[] args) {
new Thread(new Main()).start();
}
public void run() {
Locale.setDefault(Locale.US);
try {
run1();
} catch (IOException e) {
throw new RuntimeException();
}
}
int nextInt(StreamTokenizer st) throws IOException {
st.nextToken();
return (int) st.nval;
}
double nextDouble(StreamTokenizer st) throws IOException {
st.nextToken();
return st.nval;
}
String nextLine(StreamTokenizer st) throws IOException {
st.nextToken();
return st.sval;
}
Map<String, BigInteger> map = new HashMap<String, BigInteger>();
public void run1() throws IOException {
Locale.setDefault(Locale.US);
// long time = -System.currentTimeMillis();
Scanner sc = new Scanner(new InputStreamReader(System.in));
// BufferedReader br = new BufferedReader(new
// InputStreamReader(System.in));
// Scanner sc = new Scanner(new File("input.txt"));
// BufferedReader br = new BufferedReader(new FileReader("input.txt"));
// PrintStream ps = System.out;// new PrintStream(new
// File("output.txt"));
// gopa(br, ps);
double a = sc.nextDouble();
double vmax = sc.nextDouble();
double l2 = sc.nextDouble();
double l1 = sc.nextDouble();
l2 -= l1;
double boundv = sc.nextDouble();
if (boundv >= vmax || boundv * boundv / a / 2 > l1) {
System.out.print(get(0, a, vmax, l1 + l2));
System.exit(0);
}
double tmplen = vmax * vmax / a / 2 + (vmax + boundv) / 2
* (vmax - boundv) / a;
if (tmplen < l1) {
System.out.print(get(boundv, a, vmax, l2) + vmax
/ a + (vmax - boundv) / a + (l1 - tmplen) / vmax);
System.exit(0);
}
double v = Math.sqrt(l1 * a + boundv * boundv / 2);
System.out.print(get(boundv, a, vmax, l2) + v / a
+ (v - boundv) / a);
}
double get(double v0, double a, double vmax, double l) {
double tmplen = (vmax + v0) / 2 * (vmax - v0) / a;
// System.out.println(tmplen);
if (l >= tmplen) {
return (vmax - v0) / a + (l - tmplen) / vmax;
}
return (-v0 + Math.sqrt(v0 * v0 + 2 * a * l)) / a;
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.Set;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Mahmoud Aladdin <aladdin3>
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, InputReader jin, OutputWriter jout) {
int n = jin.int32();
int a = jin.int32();
int b = jin.int32();
Set<Integer> present = new HashSet<Integer>();
int[] arr = new int[n];
int[] sarr = new int[n];
for(int i = 0; i < n; i++) {
sarr[i] = arr[i] = jin.int32();
present.add(arr[i]);
}
boolean rev = b < a;
if(b < a) {b ^= a; a ^= b; b ^= a; }
Arrays.sort(sarr);
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
for(int i = 0; i < n; i++) {
if(set1.contains(sarr)) continue;
if(set2.contains(sarr)) continue;
int comp1 = b - sarr[i];
if(present.contains(comp1)) {
set2.add(sarr[i]);
set2.add(comp1);
present.remove(comp1);
} else {
int comp2 = a - sarr[i];
if(present.contains(comp2)) {
set1.add(sarr[i]);
set1.add(comp2);
present.remove(comp2);
} else {
jout.println("NO");
return;
}
}
}
jout.println("YES");
for(int i = 0; i < n; i++) {
if(i != 0) jout.print(' ');
if(rev) jout.print(set2.contains(arr[i])? 0 : 1);
else jout.print(set1.contains(arr[i])? 0 : 1);
}
}
}
class InputReader {
private static final int bufferMaxLength = 1024;
private InputStream in;
private byte[] buffer;
private int currentBufferSize;
private int currentBufferTop;
private static final String tokenizers = " \t\r\f\n";
public InputReader(InputStream stream) {
this.in = stream;
buffer = new byte[bufferMaxLength];
currentBufferSize = 0;
currentBufferTop = 0;
}
private boolean refill() {
try {
this.currentBufferSize = this.in.read(this.buffer);
this.currentBufferTop = 0;
} catch(Exception e) {}
return this.currentBufferSize > 0;
}
private Byte readChar() {
if(currentBufferTop < currentBufferSize) {
return this.buffer[this.currentBufferTop++];
} else {
if(!this.refill()) {
return null;
} else {
return readChar();
}
}
}
public String token() {
StringBuffer tok = new StringBuffer();
Byte first;
while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) != -1));
if(first == null) return null;
tok.append((char)first.byteValue());
while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) == -1)) {
tok.append((char)first.byteValue());
}
return tok.toString();
}
public Integer int32() throws NumberFormatException {
String tok = token();
return tok == null? null : Integer.parseInt(tok);
}
}
class OutputWriter {
private final int bufferMaxOut = 1024;
private PrintWriter out;
private StringBuilder output;
private boolean forceFlush = false;
public OutputWriter(OutputStream outStream) {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outStream)));
output = new StringBuilder(2 * bufferMaxOut);
}
public OutputWriter(Writer writer) {
forceFlush = true;
out = new PrintWriter(writer);
output = new StringBuilder(2 * bufferMaxOut);
}
private void autoFlush() {
if(forceFlush || output.length() >= bufferMaxOut) {
flush();
}
}
public void print(Object... tokens) {
for(int i = 0; i < tokens.length; i++) {
if(i != 0) output.append(' ');
output.append(tokens[i]);
}
autoFlush();
}
public void println(Object... tokens) {
print(tokens);
output.append('\n');
autoFlush();
}
public void flush() {
out.print(output);
output.setLength(0);
}
public void close() {
flush();
out.close();
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
/** Oct 21, 2012 **/
import java.util.InputMismatchException;
import java.util.LinkedList;
/**
* @author DOAN Minh Quy
* @email mquy.doan@gmail.com
*/
public class C236 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new C236().run();
}
void run() {
InputScanner scanner = new InputScanner(System.in);
PrintStream printer = new PrintStream(System.out);
int n = scanner.nextInt();
long answer;
if ( n == 1 ){
answer = 1;
}else if ( n == 2 ){
answer = 2;
}else{
if ( (n & 1) != 0 ){
answer = (long)n * (long)(n-1) * (long)(n-2);
}else{
if ( n % 3 == 0 ){
answer = (long)(n-1) * (long)(n-2) * (long)(n-3);
}else{
answer = (long)(n) * (long)(n-1) * (long)(n-3);
}
}
}
printer.println(answer);
}
class InputScanner{
BufferedInputStream bis;
byte[] buffer = new byte[1024];
int currentChar;
int charCount;
public InputScanner(InputStream stream){
bis = new BufferedInputStream(stream);
}
public byte read() {
if (charCount == -1)
throw new InputMismatchException();
if (currentChar >= charCount) {
currentChar = 0;
try {
charCount = bis.read(buffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (charCount <= 0)
return -1;
}
return buffer[currentChar++];
}
public int nextInt(){
int c = read();
while (isSpaceChar(c)){
c = read();
}
int sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
int rep = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
rep *= 10;
rep += c - '0';
c = read();
} while (!isSpaceChar(c));
return rep * sign;
}
public long nextLong(){
int c = read();
while (isSpaceChar(c)){
c = read();
}
int sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
long rep = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
rep *= 10;
rep += c - '0';
c = read();
} while (!isSpaceChar(c));
return rep * (long)sign;
}
public String next(){
char c = (char)read();
while (isSpaceChar(c)){
c = (char)read();
}
StringBuilder build = new StringBuilder();
do{
build.append(c);
c = (char)read();
}while(!isSpaceChar(c));
return build.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void close(){
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
constant
|
235_A. LCM Challenge
|
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 A {
private static StringTokenizer tokenizer;
private static BufferedReader bf;
private static PrintWriter out;
private static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
@SuppressWarnings("unused")
private static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private static String nextToken() throws IOException {
while(tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(bf.readLine());
}
return tokenizer.nextToken();
}
public static void main(String[] args) throws IOException {
bf = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
if(n >= 0) out.println(n);
else {
n = -n;
int a = n % 10; int m = n/10;
int b = m % 10;
if(a >= b) {
if(m == 0) out.println(0);
else out.println(-m);
}
else {
m = (m-b)+a;
if(m == 0) out.println(0);
else out.println(-m);
}
}
out.close();
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
FastIO io = new FastIO();
int test=io.nextInt();
while(test>0)
{
int n=io.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)arr[i]=io.nextInt();
List<int[]> list=new ArrayList<>();
Stack<int[]> stk=new Stack<>();
int temp[]={1};
list.add(temp);
stk.push(temp);
for(int i=1;i<n;i++)
{
if(arr[i]==1)
{
int t[]=stk.peek();
int nt[]=new int[t.length+1];
for(int j=0;j<t.length;j++)nt[j]=t[j];
nt[nt.length-1]=arr[i];
stk.push(nt);
list.add(nt);
continue;
}
while(stk.size()>0)
{
int t[]=stk.peek();
if(t[t.length-1]+1==arr[i]){
int nt[]=new int[t.length];
for(int j=0;j<t.length-1;j++)nt[j]=t[j];
nt[t.length-1]=arr[i];
stk.pop();
stk.push(nt);
list.add(nt);
break;
}
else
{
stk.pop();
}
}
}
for(int i=0;i<list.size();i++)
{
StringBuilder sb=new StringBuilder();
sb.append(list.get(i)[0]);
for(int j=1;j<list.get(i).length;j++)
{
sb.append("."+list.get(i)[j]);
}
io.println(sb.toString());
}
test--;
}
io.close();
}
}
class FastIO extends PrintWriter {
private InputStream stream;
private byte[] buf = new byte[1<<16];
private int curChar, numChars;
// standard input
public FastIO() { this(System.in,System.out); }
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
public String nextLine() {
int c; do { c = nextByte(); } while (c <= '\n');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n');
return res.toString();
}
public String next() {
int c; do { c = nextByte(); } while (c <= ' ');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');
return res.toString();
}
public int nextInt() {
int c; do { c = nextByte(); } while (c <= ' ');
int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() {
int c; do { c = nextByte(); } while (c <= ' ');
long sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() { return Double.parseDouble(next()); }
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A {
FastScanner in;
PrintWriter out;
boolean systemIO = true;
public class Fenvik {
int[] sum;
public Fenvik(int n) {
sum = new int[n];
}
public void add(int x) {
for (; x < sum.length; x = (x | (x + 1))) {
sum[x]++;
}
}
public int sum(int r) {
int ans = 0;
for (; r >= 0; r = (r & (r + 1)) - 1) {
ans += sum[r];
}
return ans;
}
}
public int gcd(int x, int y) {
if (y == 0) {
return x;
}
if (x == 0) {
return y;
}
return gcd(y, x % y);
}
public class Edge {
int to;
long s;
public Edge(int to, long s) {
this.to = to;
this.s = s;
}
}
public long dfs(int v, int prev, long sumth, long minsum, long s) {
tin[v] = timer;
timer++;
up[v][0] = new Edge(prev, s);
for (int i = 1; i <= l; i++) {
Edge e = up[v][i - 1];
up[v][i] = new Edge(up[e.to][i - 1].to, up[e.to][i - 1].s + e.s);
}
minsum = Math.min(minsum, sumth);
maxup[v] = sumth - minsum;
long mxdown = sumth;
for (Edge e : list[v]) {
if (e.to != prev) {
mxdown = Math.max(mxdown, dfs(e.to, v, sumth + e.s, minsum, e.s));
}
}
tout[v] = timer;
timer++;
maxdown[v] = mxdown - sumth;
return mxdown;
}
public boolean upper(int a1, int b1) {
return tin[a1] <= tin[b1] && tout[a1] >= tout[b1];
}
public Edge lca(int a, int b) {
if (a == b) {
return new Edge(a, 0);
}
int v = -1;
int a1 = a;
int b1 = b;
if (tin[a] <= tin[b] && tout[a] >= tout[b]) {
v = b;
long lenb = 0;
for (int i = l; i >= 0; i--) {
a1 = up[v][i].to;
b1 = a;
if (!(tin[a1] <= tin[b1] && tout[a1] >= tout[b1])) {
lenb += up[v][i].s;
v = up[v][i].to;
}
}
lenb += up[v][0].s;
v = up[v][0].to;
return new Edge(v, lenb);
}
if (upper(b, a)) {
v = a;
long lena = 0;
for (int i = l; i >= 0; i--) {
a1 = up[v][i].to;
b1 = b;
if (!(tin[a1] <= tin[b1] && tout[a1] >= tout[b1])) {
lena += up[v][i].s;
v = up[v][i].to;
}
}
lena += up[v][0].s;
v = up[v][0].to;
return new Edge(v, lena);
}
v = a;
long lena = 0;
for (int i = l; i >= 0; i--) {
a1 = up[v][i].to;
b1 = b;
if (!(tin[a1] <= tin[b1] && tout[a1] >= tout[b1])) {
lena += up[v][i].s;
v = up[v][i].to;
}
}
lena += up[v][0].s;
v = up[v][0].to;
v = b;
long lenb = 0;
for (int i = l; i >= 0; i--) {
a1 = up[v][i].to;
b1 = a;
if (!(tin[a1] <= tin[b1] && tout[a1] >= tout[b1])) {
lenb += up[v][i].s;
v = up[v][i].to;
}
}
lenb += up[v][0].s;
v = up[v][0].to;
return new Edge(v, lena + lenb);
}
int n;
int l;
int[] tin;
int[] tout;
int timer = 0;
long[] maxup;
long[] maxdown;
Edge[][] up;
ArrayList<Edge>[] list;
public void solve() {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = in.nextInt();
}
Arrays.sort(a);
int ans = 0;
boolean[] used = new boolean[n];
for (int i = 0; i < used.length; i++) {
if (!used[i]) {
ans++;
for (int j = i; j < used.length; j++) {
if (a[j] % a[i] == 0) {
used[j] = true;
}
}
}
}
out.print(ans);
}
public void run() {
try {
if (systemIO) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new FastScanner(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
}
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
public static void main(String[] arg) {
new A().run();
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.*;
public class D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = 1;
for (int i = 0; i < t; i++) {
solve(sc, pw);
}
pw.close();
}
static void solve(Scanner in, PrintWriter out){
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
int[][] ri = new int[n][m - 1];
int[][] dn = new int[n - 1][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m - 1; j++) {
ri[i][j] = in.nextInt();
}
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m; j++) {
dn[i][j] = in.nextInt();
}
}
long[][][] dp = new long[n][m][k + 1];
if (k % 2 == 1){
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.print(-1 +" ");
}
out.println();
}
}else{
for (int l = 2; l <= k; l += 2) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
long dm = Long.MAX_VALUE;
if (i > 0){
int pi = i - 1, pj = j;
dm = Math.min(dm, dp[pi][pj][l - 2] + dn[pi][pj] * 2);
}
if (j > 0){
int pi = i ,pj = j - 1;
dm = Math.min(dm, dp[pi][pj][l - 2] + ri[pi][pj] * 2);
}
if (i < n - 1){
dm = Math.min(dm, dp[i + 1][j][l - 2] + dn[i][j] * 2);
}
if (j < m - 1){
dm = Math.min(dm, dp[i][j + 1][l - 2] + ri[i][j] * 2);
}
dp[i][j][l] = dm;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (dp[i][j][k] == Long.MAX_VALUE){
out.print(-1 +" ");
}else{
out.print(dp[i][j][k] +" ");
}
}
out.println();
}
}
}
static boolean isPrime(long n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// method to return LCM of two numbers
static long lcm(long a, long b)
{
return (a / gcd(a, b)) * b;
}
public static int[] sieveEratosthenes(int n) {
if (n <= 32) {
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int i = 0; i < primes.length; i++) {
if (n < primes[i]) {
return Arrays.copyOf(primes, i);
}
}
return primes;
}
int u = n + 32;
double lu = Math.log(u);
int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];
ret[0] = 2;
int pos = 1;
int[] isnp = new int[(n + 1) / 32 / 2 + 1];
int sup = (n + 1) / 32 / 2 + 1;
int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int tp : tprimes) {
ret[pos++] = tp;
int[] ptn = new int[tp];
for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31);
for (int j = 0; j < sup; j += tp) {
for (int i = 0; i < tp && i + j < sup; i++) {
isnp[j + i] |= ptn[i];
}
}
}
// 3,5,7
// 2x+3=n
int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14};
int h = n / 2;
for (int i = 0; i < sup; i++) {
for (int j = ~isnp[i]; j != 0; j &= j - 1) {
int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];
int p = 2 * pp + 3;
if (p > n) break;
ret[pos++] = p;
if ((long) p * p > n) continue;
for (int q = (p * p - 3) / 2; q <= h; q += p) isnp[q >> 5] |= 1 << q;
}
}
return Arrays.copyOf(ret, pos);
}
// reverse division for 2
public static long[] rdiv2(int n, int mod){
long[] arr = new long[n + 5];
arr[0] = 1;
long rev2 = (mod + 1) / 2;
for (int i = 1; i < n; i++) {
arr[i] = arr[i - 1] * rev2 % mod;
}
return arr;
}
static List<Integer> primeFactors(int n)
{
// Print the number of 2s that divide n
List<Integer> ls = new ArrayList<>();
if (n % 2 == 0) ls.add(2);
while (n%2==0)
{
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
if (n % i == 0) ls.add(i);
while (n%i == 0)
{
n /= i;
}
}
if (n > 1) ls.add(n);
return ls;
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.lang.*;
public class Practice {
public static long mod = (long) Math.pow(10, 9) + 7;
public static long tt = 0;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int c = 1;
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
int n = Integer.parseInt(br.readLine());
HashMap<Integer, Integer> map = new HashMap<>();
// map.put(1, 0);
int curr = 0;
for (int i = 0; i < n; i++) {
int tt = Integer.parseInt(br.readLine());
if (tt == 1) {
curr++;
map.put(curr, 1);
} else {
ArrayList<Integer> list = new ArrayList<Integer>(map.keySet());
Collections.sort(list);
for (int a = list.size() - 1; a >= 0; a--) {
if (map.get(list.get(a)) == tt - 1) {
map.put(list.get(a), tt);
break;
} else {
curr--;
map.remove(list.get(a));
}
}
}
ArrayList<Integer> list = new ArrayList<Integer>(map.keySet());
Collections.sort(list);
StringBuilder str=new StringBuilder();
for(int a=0;a<list.size();a++) {
if(list.size()-1==a) {
str.append(map.get(list.get(a)));
continue;
}
str.append(map.get(list.get(a))+".");
}pw.println(str);
}
}
pw.close();
}
// private static long getGCD(long l, long m) {
// // TODO Auto-generated method stub
//
// long t1 = Math.min(l, m);
// long t2 = Math.max(l, m);
// while (true) {
// long temp = t2 % t1;
// if (temp == 0) {
// return t1;
// }
// t2 = t1;
// t1 = temp;
// }
// }
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new PrintStream(System.out));
int n=Integer.parseInt(f.readLine());
StringTokenizer st=new StringTokenizer(f.readLine());
int[]arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=Integer.parseInt(st.nextToken());
}
Arrays.sort(arr);
int ans=0;
boolean[]used=new boolean[n];
for(int i=0;i<n;i++){
if(!used[i]){
ans++;
for(int j=i+1;j<n;j++){
if(!used[j] && arr[j]%arr[i]==0){
used[j]=true;
}
}
used[i]=true;
}
}
System.out.print(ans);
f.close();
out.close();
}
}
class pair implements Comparable <pair>{
int num;
int idx;
public int compareTo(pair other){
return num- other.num;
}
pair(int a, int b)
{
num=a;
idx=b;
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main implements Runnable {
private int n;
private int nn;
private long[][] dp;
private boolean[][] gr;
// ////////////////////////////////////////////////////////////////////
// Solution
private void solve() throws Throwable {
n = nextInt();
nn = 1 << n;
gr = new boolean[n][n];
dp = new long[n][nn];
for (int i = 0; i < n; i++) {
Arrays.fill(dp[i], -1);
}
int m = nextInt();
for (int i = 0; i < m; i++) {
int a = nextInt() - 1, b = nextInt() - 1;
gr[a][b] = gr[b][a] = true;
}
for (int i = 0; i < n; i++) {
dp[i][0] = 0;
}
for (int mask = 1; mask < nn; mask++) {
int bCount = Integer.bitCount(mask);
if (bCount < 2) {
dp[Integer.numberOfTrailingZeros(mask)][mask] = 0;
} else if (bCount == 2) {
int msk = mask;
int one = Integer.numberOfTrailingZeros(msk);
msk ^= (1 << one);
int two = Integer.numberOfTrailingZeros(msk);
dp[two][mask] = gr[one][two] ? 1 : 0;
}
}
long count = 0;
for (int mask = 1; mask < nn; mask++) {
if (Integer.bitCount(mask) < 3) continue;
int i = Integer.numberOfTrailingZeros(mask);
for (int j = i + 1; j < n; j++) {
int jj = 1 << j;
if (gr[i][j] && ((jj & mask) != 0)) {
count += Dp(j, mask);
}
}
}
pw.println(count / 2);
}
private long Dp(int j, int mask) {
if (dp[j][mask] != -1) return dp[j][mask];
int i = Integer.numberOfTrailingZeros(mask);
assert i < j;
int m = mask ^ (1 << j);
long ans = 0;
for (int p = i + 1; p < n; p++) {
if (!gr[p][j]) continue;
if ((mask & (1 << p)) == 0) continue;
ans += Dp(p, m);
}
dp[j][mask] = ans;
return ans;
}
// ////////////////////////////////////////////////////////////////////
// Utility functions
PrintWriter pw;
BufferedReader in;
StringTokenizer st;
void initStreams() throws FileNotFoundException {
//System.setIn(new FileInputStream("2"));
in = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
}
String nextString() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextString());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextString());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextString());
}
static Throwable sError;
public static void main(String[] args) throws Throwable {
Thread t = new Thread(new Main());
t.start();
t.join();
if (sError != null) {
throw sError;
}
}
public void run() {
try {
initStreams();
solve();
} catch (Throwable e) {
sError = e;
} finally {
if (pw != null)
pw.close();
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.Point;
public final class Solution {
BufferedReader br;
StringTokenizer st;
{
st = null;
br = new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args) throws Exception {
new Solution().run();
}
void run() throws Exception {
int n = ni();
int[] a = new int[n];
for(int i=0; i<n; i++) a[i] = ni();
for(int i=1; i<n; i++) a[i] += a[i-1];
HashMap<Integer, List<Point>> map = new HashMap<>();
for(int i=0; i<n; i++) {
for(int j=i; j<n; j++) {
int sum = getSum(a, i, j);
if(!map.containsKey(sum)) map.put(sum, new ArrayList<>());
map.get(sum).add(new Point(i+1, j+1));
}
}
for(int key : map.keySet()) {
Collections.sort(map.get(key), new Comparator<Point>() {
@Override
public int compare(Point p1, Point p2) {
if(p1.x == p2.x) return p1.y - p2.y;
return p1.x - p2.x;
}
});
}
Stack<Point> stack = new Stack<>();
for(int key : map.keySet()) {
Stack<Point> st = getPairs(map.get(key));
if(st.size() > stack.size()) stack = st;
}
pl(stack.size());
while(!stack.isEmpty()) {
Point p = stack.pop();
pl(p.x + " " + p.y);
}
}
Stack<Point> getPairs(List<Point> list) {
Stack<Point> stack = new Stack<>();
stack.push(list.get(0));
for(int i=1; i<list.size(); i++) {
Point p = list.get(i);
if(p.x >= stack.peek().x && p.x <= stack.peek().y) {
Point p2 = stack.pop();
if(p2.y < p.y) {
stack.push(p2);
} else {
stack.push(p );
}
} else {
stack.push(p);
}
}
return stack;
}
int getSum(int[] a, int l, int r) {
return (l == 0) ? a[r] : a[r] - a[l-1];
}
class Node {
HashSet<Integer> adj;
public Node() {
adj = new HashSet<>();
}
}
// I/O
String nt() throws Exception {
if(st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine(), " ");
}
return st.nextToken();
}
int ni() throws Exception {
return Integer.parseInt(nt());
}
long nl() throws Exception {
return Long.parseLong(nt());
}
void p(Object o) {
System.out.print(o);
}
void pl(Object o) {
System.out.println(o);
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.*;
import java.util.List;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Problem {
public static Pair solve(Forest f, List<Pair> queue){
Pair current = null, next = null;
int index = 0;
while(queue.size() > 0){
current = queue.remove(0);
index = f.desk[current.x][current.y];
if(current.x>0){
next = new Pair(current.x-1,current.y);
if(f.desk[next.x][next.y]==0){
f.desk[next.x][next.y] = index+1;
queue.add(next);
}
}
if(current.x<f.N-1){
next = new Pair(current.x+1,current.y);
if(f.desk[next.x][next.y]==0){
f.desk[next.x][next.y] = index+1;
queue.add(next);
}
}
if(current.y>0){
next = new Pair(current.x,current.y-1);
if(f.desk[next.x][next.y]==0){
f.desk[next.x][next.y] = index+1;
queue.add(next);
}
}
if(current.y<f.M-1){
next = new Pair(current.x,current.y+1);
if(f.desk[next.x][next.y]==0){
f.desk[next.x][next.y] = index+1;
queue.add(next);
}
}
}
return f.findMax();
}
public static void main(String[] args){
String buffer = null;
StringTokenizer st = null;
Forest f = null;
List<Pair> pairs = new LinkedList<Pair>();
Integer N,M,K,x,y;
try {
BufferedReader in = new BufferedReader(
new FileReader("input.txt")
);
FileWriter out = new FileWriter("output.txt");
buffer = in.readLine();
st = new StringTokenizer(buffer);
N = new Integer(st.nextToken());
M = new Integer(st.nextToken());
f = new Forest(N,M);
buffer = in.readLine();
st = new StringTokenizer(buffer);
K = new Integer(st.nextToken());
buffer = in.readLine();
st = new StringTokenizer(buffer);
for(int i = 0; i<K; i++){
x = new Integer(st.nextToken());
y = new Integer(st.nextToken());
f.desk[x-1][y-1] = 1;
pairs.add(new Pair(x-1,y-1));
}
Pair res = solve(f,pairs);
out.write(res.toString());
out.flush();
} catch (Exception e) {
}
}
}
class Pair {
public Pair(int i, int j){
x = i;
y = j;
}
public String toString(){
return (x+1) + " " + (y+1);
}
public int x;
public int y;
}
class Forest {
public Forest(int n, int m){
N = n;
M = m;
desk = new int[N][M];
}
public Pair findMax(){
Pair max = new Pair(0,0);
for(int i = 0; i<N; i++){
for(int j = 0; j<M; j++){
if(desk[i][j]>desk[max.x][max.y]){
max.x = i;
max.y = j;
}
}
}
return max;
}
public int N;
public int M;
public int[][] desk;
}
|
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.List;
import java.util.Map;
import java.util.Scanner;
import java.util.HashMap;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(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, Scanner in, PrintWriter out) {
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
Map<Long, List<Pair>> map = new HashMap<>();
for (int r = 0; r < n; r++) {
long sum = 0;
for (int l = r; l >= 0; l--) {
sum += arr[l];
if (map.containsKey(sum)) {
map.get(sum).add(new Pair(l, r));
} else {
map.put(sum, new ArrayList<>());
map.get(sum).add(new Pair(l, r));
}
}
}
int ans = -1;
List<Pair> ansPairs = new ArrayList<>();
for (long sum : map.keySet()) {
List<Pair> pairs = map.get(sum);
int count = 0;
int idx = -1;
List<Pair> tempPairs = new ArrayList<>();
for (Pair pair : pairs) {
if (pair.i > idx) {
idx = pair.j;
tempPairs.add(pair);
count++;
}
}
if (ans < count) {
ans = count;
ansPairs = tempPairs;
}
}
out.println(ans);
for (Pair pair : ansPairs) {
out.print((pair.i + 1) + " " + (pair.j + 1));
out.println();
}
}
class Pair {
int i;
int j;
Pair(int p, int q) {
i = p;
j = q;
}
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
public class ProblemA {
static final int INF = 100000000;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String[] nmd = in.readLine().split(" ");
long a = Long.valueOf(nmd[0]);
long b = Long.valueOf(nmd[1]);
long cnt = 0;
while (true) {
if (a == 0) {
break;
}
if (a >= b) {
cnt += a / b;
a = a % b;
} else {
if (b % a == 0) {
cnt += b / a - 1;
b = a;
} else {
cnt += b / a;
b = b % a;
}
}
}
out.println(cnt);
out.flush();
}
public static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.util.Scanner;
import java.util.StringTokenizer;
/**
* Created with IntelliJ IDEA.
* User: Саша
* Date: 08.08.12
* Time: 14:12
*/
public class LuckyDivision {
public final String check (String s) {
String result = "NO";
StringTokenizer stringTokenizer = new StringTokenizer(s, "47");
if(!stringTokenizer.hasMoreTokens()) return "YES";
int S = Integer.parseInt(s);
generateSimpleAndDivide(S, 4, 4, 7);
generateSimpleAndDivide(S, 7, 4, 7);
if(lucky) return "YES";
return result;
}
public static final void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(new LuckyDivision().check(scanner.next()));
}
public void generateSimpleAndDivide(int divided, int n, int n1, int n2) {
if(lucky || n >= divided) return;
if(divided % n == 0) lucky = true;
generateSimpleAndDivide(divided, Integer.parseInt(n + "" + n1), n1, n2);
generateSimpleAndDivide(divided, Integer.parseInt(n + "" + n2), n1, n2);
}
private boolean lucky = false;
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class e1515 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
solve(s.nextInt(), s.nextLong());
}
public static long inv(long n, long mod) {
if (n == 1) return 1;
return (inv(mod % n, mod) * (mod - mod / n)) % mod;
}
public static void solve(int n, long mod) {
long fact[] = new long[n + 2];
long invFact[] = new long[n + 2];
long twoPow[] = new long[n + 2];
fact[0] = 1;
invFact[0] = 1;
twoPow[0] = 1;
for (int i = 1; i < n + 2; i++) {
fact[i] = (fact[i - 1] * i) % mod;
invFact[i] = (invFact[i - 1] * inv(i, mod)) % mod;
twoPow[i] = (2 * twoPow[i - 1]) % mod;
}
long dp[][] = new long[n + 2][];
dp[0] = new long[]{1};
long next[] = null;
for (int i = 1; i <= n + 1; i++) {
next = new long[i + 1];
for (int j = 0; j < i - 1; j++) {
for (int k = 0; k < dp[j].length; k++) {
next[k + i - j - 1] = (next[k + i - j - 1] + ((((dp[j][k] * twoPow[i - j - 2]) % mod * fact[k + i - j - 1]) % mod * invFact[k]) % mod * invFact[i - j - 1]) % mod) % mod;
}
}
dp[i] = next;
}
long sum = 0;
for (int i = 0; i < next.length; i++) {
sum = (sum + next[i]) % mod;
}
System.out.println(sum);
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
static final int MAX_N = 1000010;
static final int INF = 0x3f3f3f3f;
static final int mod = 1000000007;
public static void main(String[] args) throws IOException {
initReader(System.in);
// int T = nextInt();
// for (int i = 1; i <= T; i++)
solve();
pw.flush();
}
/*******************************************************************************************************************************/
public static void solve() throws IOException {
while (hasNext()) {
long n = nextLong() - 1;
long k = 1, x = 9;
while (n - k * x >= 0) {
n -= k * x;
k += 1;
x *= 10;
}
if (n == 0)
pw.println(1);
else {
long num = x / 9 + n / k;
String s = String.valueOf(num);
pw.println(s.charAt((int) (n % k)));
}
}
}
/*******************************************************************************************************************************/
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter pw;
public static void initReader(InputStream input) throws IOException {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
// reader = new BufferedReader(new FileReader("ate.in"));
// tokenizer = new StringTokenizer("");
// printWriter = new PrintWriter(new BufferedWriter(new FileWriter("ate.out")));
}
public static boolean hasNext() {
try {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
}
return true;
}
public static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
return null;
}
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static char nextChar() throws IOException {
return next().charAt(0);
}
static class Pair {
char first;
boolean second;
public Pair(char first, boolean second) {
// TODO Auto-generated constructor stub
this.first = first;
this.second = second;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "(" + this.first + ", " + this.second + ")";
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class A {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
long MOD = 1000000009;
public long mod_add(long n1, long n2){
return (n1 + n2) % MOD;
}
public long mod_time(long n1, long n2){
return (n1 * n2) % MOD;
}
public long mod_power(long a, int k) {
if (k == 0) return 1;
if (k % 2 == 0) return mod_power(a * a % MOD, k / 2);
return a * mod_power(a, k - 1) % MOD;
}
public void solve() throws IOException {
int N = nextInt();
int M = N - nextInt(); //wrong
int K = nextInt();
int full = N/K - M;
if( full < 0){
out.println( N - M );return;
}
long ans = mod_time( K * 2, mod_power(2, full) - 1 );
// out.println( full + ", " + ans );
ans = mod_add(ans, N-M-full*K );
out.println( ans );
}
/**
* @param args
*/
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.util.*;
public class Compute {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long M = sc.nextInt();
long fact[] = new long[n+1];
long inv[] = new long[n+1];
long ifact[] = new long[n+1];
long dp[][] = new long[n+1][n+1];
fact[1] = 1;
ifact[1] = 1;
ifact[0] = 1;
inv[1] = 1;
dp[1][1] = 1;
for(int i = 2; i <= n; i++) {
fact[i] = (i*fact[i-1]) % M;
inv[i] = (inv[(int)(M % i)]*(M - M/i)) % M;
dp[i][i] = (dp[i-1][i-1] * 2) % M;
ifact[i] = (ifact[i-1]*inv[i]) % M;
}
for(int i = 3; i <= n; i++) {
for(int j = i/2 + 1; j <= i-1; j++) {
for(int k = 2; k <= i-1 && j-k+1 > (i-k)/2; k++) {
dp[i][j] = (dp[i][j] + ((((dp[k-1][k-1]*dp[i-k][j-k+1] % M)*fact[j] % M)*ifact[k-1] % M)*ifact[j-k+1] % M)) % M;
}
}
}
long sum = 0;
for(int i = n/2 + 1; i <= n; i++)
sum = (sum + dp[n][i]) % M;
System.out.println(sum % M);
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer split = new StringTokenizer(in.readLine());
int n = Integer.parseInt(split.nextToken());
double t = Double.parseDouble(split.nextToken());
House[] xaxis = new House[n];
for (int i = 0; i < n; i++) {
split = new StringTokenizer(in.readLine());
xaxis[i] = new House(Double.parseDouble(split.nextToken()), Double.parseDouble(split.nextToken()));
}
Arrays.sort(xaxis);
int count = 2;
for (int i = 0; i < xaxis.length - 1; i++) {
double free = (xaxis[i + 1].getX() - xaxis[i + 1].getSize() / 2.0) - (xaxis[i].getX() + xaxis[i].getSize() / 2.0);
if (free / t == 1.0) {
count++;
} else if (free / t > 1.0) {
count += 2;
}
}
System.out.println(count);
}
}
class House implements Comparable<House> {
private double x;
private double size;
public House(double x, double size) {
this.x = x;
this.size = size;
}
public double getX() {
return x;
}
public double getSize() {
return size;
}
public int compareTo(House o) {
if (this.x > o.getX()) {
return 1;
} else if (this.x == o.getX()) {
return 0;
}
return -1;
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Contest1_1{
public static void main(String ar[]) throws Exception {
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
int input = Integer.parseInt(buff.readLine());
if(input==0){
System.out.println("0 0 0");
}else if(input==1){
System.out.println("0 0 1");
}else if(input==2){
System.out.println("0 1 1");
}else if(input==3){
System.out.println("1 1 1");
}else {
int output[] = checkFibo(input);
int get[] = checkFibo(output[1]);
output[0] = get[1];
output[1] = get[2];
System.out.print(output[0]);
System.out.print(" " + output[1]);
System.out.println(" " + output[2]);
}
}
public static int[] checkFibo(int input){
int output[] = new int[3];
int fibo_1 = 0;
int fibo_2 = 1;
int temp = 0;
while(fibo_2!=input){
temp = fibo_2;
output[1] = fibo_1;
output[2] = fibo_2;
fibo_2 += fibo_1;
fibo_1 = temp;
}
return output;
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
* User: piyushd
* Date: 3/26/11
* Time: 10:53 PM
* To change this template use File | Settings | File Templates.
*/
public class TaskC {
final int INF = 123456;
int[][][] memo;
int N, M;
int solve(int row, int prevFreeMask, int curStayMask) {
if(row == N) return (curStayMask == 0) ? 0 : -INF;
if(memo[row][prevFreeMask][curStayMask] != -1) return memo[row][prevFreeMask][curStayMask];
int res = 0;
for(int mask = 0; mask < (1<<M); mask++) {
if((mask & curStayMask) == curStayMask) {
int freeCellsMask = (1<<M) - 1 - mask;
int toMoveMask = freeCellsMask;
for(int i = 0; i < M; i++) {
if((toMoveMask & (1<<i)) > 0) {
if(i > 0) {
if((mask & (1<<(i - 1))) > 0) {
toMoveMask -= (1<<i);
continue;
}
}
if(i < M - 1) {
if((mask & (1<<(i + 1))) > 0) {
toMoveMask -= (1<<i);
continue;
}
}
}
}
if (row > 0) {
for (int prevFillMask = toMoveMask; prevFillMask > 0; prevFillMask = (prevFillMask - 1) & toMoveMask) {
int bc1 = Integer.bitCount(freeCellsMask);
int bc2 = Integer.bitCount(prevFreeMask & prevFillMask);
res = Math.max(res, bc1 - bc2 + solve(row + 1, freeCellsMask, toMoveMask ^ prevFillMask));
}
}
res = Math.max(res, Integer.bitCount(freeCellsMask) + solve(row + 1, freeCellsMask, toMoveMask));
}
}
return memo[row][prevFreeMask][curStayMask] = res;
}
void run() {
N = nextInt();
M = nextInt();
if(M > N) {
int temp = M;
M = N;
N = temp;
}
this.memo = new int[N + 1][1<<M][1<<M];
for(int[][] g : memo) for(int[] f : g) Arrays.fill(f, -1);
System.out.println(solve(0, 0, 0));
}
int nextInt(){
try{
int c = System.in.read();
if(c == -1) return c;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return c;
}
if(c == '-') return -nextInt();
int res = 0;
do{
res *= 10;
res += c - '0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
long nextLong(){
try{
int c = System.in.read();
if(c == -1) return -1;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return -1;
}
if(c == '-') return -nextLong();
long res = 0;
do{
res *= 10;
res += c-'0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
double nextDouble(){
return Double.parseDouble(next());
}
String next(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(Character.isWhitespace(c))
c = System.in.read();
do{
res.append((char)c);
}while(!Character.isWhitespace(c=System.in.read()));
return res.toString();
}catch(Exception e){
return null;
}
}
String nextLine(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(c == '\r' || c == '\n')
c = System.in.read();
do{
res.append((char)c);
c = System.in.read();
}while(c != '\r' && c != '\n');
return res.toString();
}catch(Exception e){
return null;
}
}
public static void main(String[] args){
new TaskC().run();
}
}
|
np
|
112_E. Petya and Spiders
|
CODEFORCES
|
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class temp
{
void solve()
{
FastReader sc =new FastReader();
int n = sc.nextInt();
ArrayList<String> a[] = new ArrayList[5];
for(int i=0;i<=4;i++)
a[i] = new ArrayList<>();
for(int i=0;i<n;i++)
{
String s = sc.next();
a[s.length()].add(s);
}
int ans = 0;
for(int i=0;i<n;i++)
{
String s = sc.next();
if(a[s.length()].contains(s))
a[s.length()].remove(new String(s));
}
for(int i=1;i<=4;i++)
ans+=a[i].size();
System.out.println(ans);
}
public static void main(String[] args)
{
new temp().solve();
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main implements Runnable {
private int n;
private int nn;
private boolean[][] gr;
private long[][] D;
// ////////////////////////////////////////////////////////////////////
// Solution
private void solve() throws Throwable {
n = nextInt();
nn = 1 << n;
gr = new boolean[n][n];
int m = nextInt();
for (int i = 0; i < m; i++) {
int a = nextInt() - 1, b = nextInt() - 1;
gr[a][b] = gr[b][a] = true;
}
D = new long[n][nn];
for (int i = 0; i < n; i++) {
Arrays.fill(D[i], -1);
}
long count = 0;
for (int i = 0; i < n; i++) {
count += getD(i, i, 1, 1 << i);
}
pw.println(count / 2);
}
private long getD(int first, int last, int cnt, int mask) {
if (D[last][mask] != -1) return D[last][mask];
long ans = 0;
if (cnt >= 3 && gr[first][last])
ans++;
for (int i = first + 1; i < n; i++) {
if (gr[last][i] && (mask & (1 << i)) == 0) {
ans += getD(first, i, cnt + 1, mask | (1 << i));
}
}
D[last][mask] = ans;
return ans;
}
// ////////////////////////////////////////////////////////////////////
// Utility functions
PrintWriter pw;
BufferedReader in;
StringTokenizer st;
void initStreams() throws FileNotFoundException {
//System.setIn(new FileInputStream("2"));
in = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
}
String nextString() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextString());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextString());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextString());
}
static Throwable sError;
public static void main(String[] args) throws Throwable {
Thread t = new Thread(new Main());
t.start();
t.join();
if (sError != null) {
throw sError;
}
}
public void run() {
try {
initStreams();
solve();
} catch (Throwable e) {
sError = e;
} finally {
if (pw != null)
pw.close();
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.*;
public class LCM235A
{
public static void main(String[] args)
{
// Set up scanner
Scanner sc = new Scanner(System.in);
// System.out.println("Enter n");
long n = sc.nextLong();
if (n==1)
{
System.out.println(1);
return;
}
if (n==2)
{
System.out.println(2);
return;
}
if (n==3)
{
System.out.println(6);
return;
}
if (n==4)
{
System.out.println(12);
return;
}
if (n%2 ==1) // Odd number easy
{
System.out.println(n*(n-1)*(n-2));
return;
}
// Even number is a bit harder
if (n%3 == 0)
{
System.out.println((n-1)*(n-2)*(n-3));
}
else
{
System.out.println(n*(n-1)*(n-3));
}
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main{
/**
* @param args
*/
public static void main(String[] args) {
Parser p = new Parser(System.in);
PrintWriter pw= new PrintWriter(System.out);
int n = p.nextInt();
int k = p.nextInt();
int[] a = p.nextIntArray(n);
int [] pos = new int[100001];
Arrays.fill(pos,-1);
int cnt = 0;
for(int i=0; i<n; ++i){
int e = a[i];
if( pos[e] == -1 ){
++cnt;
}
pos[e] = i;
if( cnt == k){
break;
}
}
if( cnt < k){
pw.println("-1 -1");
pw.close();
return;
}
int min = 1000000;
int max = -1;
for(int i=0; i<100001; ++i){
if(pos[i] != -1 && pos[i] < min ){
min = pos[i];
}
if( pos[i] > max){
max = pos[i];
}
}
++min;
++max;
pw.println(min+" "+max);
pw.close();
}
static class Parser{
StringTokenizer st;
BufferedReader br;
public Parser(InputStream is){
this.br = new BufferedReader( new InputStreamReader(is));
}
public int nextInt(){
return Integer.parseInt(nextToken());
}
public double nextDouble(){
return Double.parseDouble(nextToken());
}
public String nextString(){
return nextToken();
}
public int[] nextIntArray(int s){
int[] a = new int[s];
for(int i=0; i<s; ++i){
a[i] = nextInt();
}
return a;
}
public int[][] nextIntTable(int r, int c){
int[][] a = new int[r][c];
for(int i=0; i<r; ++i){
a[i] = nextIntArray(c);
}
return a;
}
private String nextToken() {
if( st == null || ! st.hasMoreTokens() ){
try{
st = new StringTokenizer( br.readLine());
}catch( Exception e){
e.printStackTrace();
}
}
return st.nextToken();
}
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;
public class A {
public void run() throws Exception {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
int[] arr = new int[n];
int[] color = new int[n];
for (int i = 0; i<n; i++) {
arr[i] =sc.nextInt();
}
Arrays.sort(arr);
int counter = 1;
for (int i = 0; i<n; i++) {
if (color[i]!= 0) continue;
for (int j = i;j<n; j++) {
if (color[j]!= 0) continue;
else if (arr[j]%arr[i] == 0) color[j] = counter;
}
counter++;
}
// System.out.println(Arrays.toString(color));
int max = 0;
for (int i = 0; i<n; i++) {
max = Math.max(max, color[i]);
}
System.out.println(max);
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public static void main (String[] args) throws Exception {
new A().run();
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class LCM {
public static long gcd(long a,long b) {
while(true) {
a=a%b;
if (a==0) return b;
b=b%a;
if (b==0) return a;
}
}
public static void main (String[] args) throws java.lang.Exception {
Scanner in=new Scanner(System.in);
long n=in.nextInt();
if (n>2) {
if (gcd(n,n-2)>1) {
if (gcd(n,n-3)>1) {
System.out.println((n-1)*(n-2)*(n-3));
}
else System.out.println(n*(n-1)*(n-3));
}
else System.out.println(n*(n-1)*(n-2));
}
else System.out.println(n);
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter writer;
static int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
static long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
static String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out);
pineapple();
reader.close();
writer.close();
}
static void pineapple() throws NumberFormatException, IOException {
int n = nextInt();
int a = nextInt();
int b = nextInt();
TreeSet<Integer> al = new TreeSet<Integer>();
TreeMap<Integer, Integer> mp = new TreeMap<Integer, Integer>();
int[] ans = new int[n];
Arrays.fill(ans, -1);
TreeSet<Integer> used = new TreeSet<Integer>();
int[] mas = new int[n];
for (int i = 0; i < n; i++) {
int t = nextInt();
al.add(t);
mas[i] = t;
mp.put(t, i);
}
for (int st : al) {
if (used.contains(st))
continue;
{
int pr = st;
int cc = -1;
TreeSet<Integer> u2 = new TreeSet<Integer>();
u2.add(pr);
if (al.contains(a - pr) && !u2.contains(a - pr))
cc = a - pr;
else if (al.contains(b - pr) && !u2.contains(a - pr))
cc = b - pr;
if (cc != -1) {
u2.add(cc);
boolean bGo = true;
while (bGo) {
bGo = false;
int nxt = -1;
if (al.contains(a - cc) && !u2.contains(a - cc))
nxt = a - cc;
else if (al.contains(b - cc) && !u2.contains(b - cc))
nxt = b - cc;
if (nxt != -1) {
bGo = true;
u2.add(nxt);
cc = nxt;
pr = cc;
}
}
st = cc;
}
}
int x = st;
while (x != -1) {
int curr = x;
used.add(curr);
x = -1;
int next1 = a - curr;
if (al.contains(next1)) {
if (!used.contains(next1)) {
x = next1;
int ci = mp.get(curr);
int ni = mp.get(next1);
if (ans[ci] == -1 && ans[ni] == -1) {
ans[ni] = 0;
ans[ci] = 0;
}
}
}
int next2 = b - curr;
if (al.contains(next2)) {
if (!used.contains(next2)) {
x = next2;
int ci = mp.get(curr);
int ni = mp.get(next2);
if (ans[ci] == -1 && ans[ni] == -1) {
ans[ni] = 1;
ans[ci] = 1;
}
}
}
}
}
for (int i = 0; i < n; i++) {
if (ans[i] == -1) {
if (2 * mas[i] == a) {
ans[i] = 0;
continue;
}
if (2 * mas[i] == b) {
ans[i] = 1;
continue;
}
writer.println("NO");
return;
}
}
writer.println("YES");
for (int i = 0; i < n; i++) {
writer.print(ans[i] + " ");
}
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.util.*;
public class Pizza {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
long num = sc.nextLong() + 1;
sc.close();
System.out.println(num % 2 == 0 || num == 1 ? num / 2 : num);
}
}
|
constant
|
979_A. Pizza, Pizza, Pizza!!!
|
CODEFORCES
|
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.lang.System.out;
import static java.util.Collections.*;
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
static boolean LOCAL = System.getSecurityManager() == null;
Scanner in = new Scanner(System.in);
private int[] B;
private int[] A;
private int n;
private int m;
void run() {
n = in.nextInt();
m = in.nextInt();
A = new int[m];
B = new int[m];
for (int i = 0; i < m; i++) {
A[i] = in.nextInt() - 1;
B[i] = in.nextInt() - 1;
}
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
ans = min(ans, solve(i));
}
out.println(ans);
}
int solve(int x) {
int ans = 3 * (n - 1) + 1 + m;
V[] vs = new V[n * 2];
for (int i = 0; i < vs.length; i++) vs[i] = new V();
for (int i = 0; i < m; i++) {
if (A[i] == x || B[i] == x) ans -= 2;
else vs[A[i]].connect(vs[n + B[i]]);
}
return ans - 2 * bipartiteMatching(vs);
}
class V extends ArrayList<V> {
V pair;
boolean used;
void connect(V v) {
add(v);
v.add(this);
}
}
int bipartiteMatching(V[] vs) {
int match = 0;
for (V v : vs) if (v.pair == null) {
for (V u : vs) u.used = false;
if (dfs(v)) match++;
}
return match;
}
boolean dfs(V v) {
v.used = true;
for (V u : v) {
V w = u.pair;
if (w == null || !w.used && dfs(w)) {
v.pair = u;
u.pair = v;
return true;
}
}
return false;
}
void debug(Object... os) {
System.err.println(deepToString(os));
}
public static void main(String[] args) {
if (LOCAL) {
try {
System.setIn(new FileInputStream("./../../in.txt"));
// System.setOut(new PrintStream("./../../out"));
} catch (Throwable e) {
LOCAL = false;
}
}
long start = 0;
if (LOCAL)
start = System.nanoTime();
new Main().run();
if (LOCAL)
System.err.printf("[Time : %.6f s]%n",
(System.nanoTime() - start) * 1e-9);
}
}
class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
eat("");
}
void eat(String s) {
st = new StringTokenizer(s);
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
boolean hasNext() {
while (!st.hasMoreTokens()) {
String s = nextLine();
if (s == null)
return false;
eat(s);
}
return true;
}
String next() {
hasNext();
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
|
cubic
|
387_D. George and Interesting Graph
|
CODEFORCES
|
import javax.annotation.processing.SupportedSourceVersion;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(new FileReader("input.txt")); // new InputReader(inputStream);
PrintWriter out = new PrintWriter("output.txt"); //new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(in, out);
out.close();
}
private static class TaskB {
static final long max = 1000000000000000000L;
static final double eps = 0.0000001;
static final long mod = 1000000007;
static int N, M, K;
static long X, Y;
static boolean F[][][];
static int D[][];
void solve(InputReader in, PrintWriter out) throws IOException {
N = in.nextInt();
M = in.nextInt();
K = in.nextInt();
F = new boolean[K][N][M];
D = new int[N][M];
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
D[i][j] = Integer.MAX_VALUE;
List<Pair> list = new ArrayList<>();
for (int i = 0; i < K; i++) {
list.add(new Pair(in.nextInt() - 1, in.nextInt() - 1));
}
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
for (int k = 0; k < K; k++)
D[i][j] = Math.min(D[i][j], Math.abs(list.get(k).X - i) + Math.abs(list.get(k).Y - j));
int res = Integer.MIN_VALUE;
for (int j = 0; j < N; j++)
for (int k = 0; k < M; k++)
if (D[j][k] > res) {
X = j + 1;
Y = k + 1;
res = D[j][k];
}
out.println(X + " " + Y);
}
void bfs(int K, Pair P) {
Queue<Pair> Q = new LinkedList<>();
F[K][P.X][P.Y] = true;
D[P.X][P.Y] = 0;
Q.add(P);
while (!Q.isEmpty()) {
P = Q.poll();
int X = P.X;
int Y = P.Y;
if (check(X - 1, Y) && !F[K][X - 1][Y]) {
F[K][X - 1][Y] = true;
if (D[X - 1][Y] > D[X][Y] + 1) {
D[X - 1][Y] = D[X][Y] + 1;
Q.add(new Pair(X - 1, Y));
}
}
if (check(X + 1, Y) && !F[K][X + 1][Y]) {
F[K][X + 1][Y] = true;
if (D[X + 1][Y] > D[X][Y] + 1) {
D[X + 1][Y] = D[X][Y] + 1;
Q.add(new Pair(X + 1, Y));
}
}
if (check(X, Y - 1) && !F[K][X][Y - 1]) {
F[K][X][Y - 1] = true;
if (D[X][Y - 1] > D[X][Y] + 1) {
D[X][Y - 1] = D[X][Y] + 1;
Q.add(new Pair(X, Y - 1));
}
}
if (check(X, Y + 1) && !F[K][X][Y + 1]) {
F[K][X][Y + 1] = true;
if (D[X][Y + 1] > D[X][Y] + 1) {
D[X][Y + 1] = D[X][Y] + 1;
Q.add(new Pair(X, Y + 1));
}
}
}
}
boolean check(int X, int Y) {
return !(X < 0 || X >= N || Y < 0 || Y >= M);
}
class Pair {
int X, Y;
Pair(int X, int Y) {
this.X = X;
this.Y = Y;
}
}
long gcd(long A, long B) {
if (B == 0) return A;
return gcd(B, A % B);
}
boolean isPrime(long n) {
if (n <= 1 || n > 3 && (n % 2 == 0 || n % 3 == 0))
return false;
for (long i = 5, j = 2; i * i <= n; i += j, j = 6 - j)
if (n % i == 0)
return false;
return true;
}
boolean isEqual(double A, double B) {
return Math.abs(A - B) < eps;
}
double dist(double X1, double Y1, double X2, double Y2) {
return Math.sqrt((X1 - X2) * (X1 - X2) + (Y1 - Y2) * (Y1 - Y2));
}
boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
long pow(long A, long B, long MOD) {
if (B == 0) {
return 1;
}
if (B == 1) {
return A;
}
long val = pow(A, B / 2, MOD);
if (B % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * A % MOD) % MOD;
}
}
}
private static class InputReader {
StringTokenizer st;
BufferedReader br;
public InputReader(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public InputReader(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() {
while (st == null || !st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
public boolean ready() {
try {
return br.ready();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.Scanner;
public class x23A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
//input+="3";
int longest=0;
if(input.length()==1){
System.out.println(0);
System.exit(0);
}
if(input.length()==2){
if(input.charAt(0)==input.charAt(1)){
System.out.println(1);
System.exit(0);
}
else{
System.out.println(0);
System.exit(0);}
}
for(int a=0;a<input.length()-1;a++){
for(int b=a+1;b<input.length();b++){
for(int c=1;(c+b)<input.length()+1;c++){
// System.out.printf("%s %s %d\n", input.substring(a,a+c), input.substring(b,b+c), input.substring(a,a+c).compareTo(input.substring(b,b+c)));
if(input.substring(a,a+c).compareTo(input.substring(b,b+c))==0)
if(longest<c)longest=c;
}
}
}
System.out.println(longest);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.*;
public class c8 {
static int n;
static int[] ds;
static int[][] g;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int x = input.nextInt(), y = input.nextInt();
int n = input.nextInt();
int[] xs = new int[n], ys = new int[n];
for(int i = 0; i<n; i++)
{
xs[i] = input.nextInt();
ys[i] = input.nextInt();
}
ds = new int[n];
g = new int[n][n];
for(int i = 0; i<n; i++)
{
ds[i] = (x - xs[i]) * (x - xs[i]) + (y - ys[i]) * (y - ys[i]);
for(int j = 0; j<n; j++)
{
g[i][j] = (xs[i] - xs[j]) * (xs[i] - xs[j]) + (ys[i] - ys[j]) * (ys[i] - ys[j]);
}
}
int[] dp = new int[1<<n];
Arrays.fill(dp, 987654321);
dp[0] = 0;
for(int i = 0; i<(1<<n); i++)
{
if(dp[i] == 987654321) continue;
for(int a = 0; a<n; a++)
{
if((i & (1<<a)) > 0) continue;
dp[i | (1<<a)] = Math.min(dp[i | (1<<a)], dp[i] + 2*ds[a]);
for(int b = a+1; b<n; b++)
{
if((i & (1<<b)) > 0) continue;
dp[i | (1<<a) | (1<<b)] = Math.min(dp[i | (1<<a) | (1<<b)], dp[i] + ds[a] + ds[b] + g[a][b]);
}
break;
}
}
Stack<Integer> stk = new Stack<Integer>();
stk.add(0);
int i = (1<<n) - 1;
//System.out.println(Arrays.toString(dp));
trace:
while(i > 0)
{
//System.out.println(i);
for(int a = 0; a<n; a++)
{
if((i & (1<<a)) == 0) continue;
if( dp[i] == dp[i - (1<<a)] + 2*ds[a])
{
stk.add(a+1);
stk.add(0);
i -= (1<<a);
continue trace;
}
for(int b = a+1; b<n; b++)
{
if((i & (1<<b)) == 0) continue;
if(dp[i] == dp[i - (1<<a) - (1<<b)] + ds[a] + ds[b] + g[a][b])
{
stk.add(a+1);
stk.add(b+1);
stk.add(0);
i -= (1<<a) + (1<<b);
continue trace;
}
}
//break;
}
}
System.out.println(dp[(1<<n) - 1]);
while(!stk.isEmpty()) System.out.print(stk.pop()+" ");
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class SolutionC{
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(new File("input.txt"));
PrintWriter output = new PrintWriter("output.txt");
int N = sc.nextInt();
int M = sc.nextInt();
int K = sc.nextInt();
int[] x = new int[K];
int[] y = new int[K];
for(int i = 0 ; i < K ; i++){
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
int max = -1, max_x = -1, max_y = -1;
for(int i = 1 ; i <= N ; i++){
for(int j = 1 ; j <= M ; j++){
int min = Integer.MAX_VALUE;
for(int k = 0 ; k < K ; k++){
min = Math.min(min, Math.abs(x[k] - i) + Math.abs(y[k] - j));
}
if(min > max){
max = min;
max_x = i;
max_y = j;
}
}
}
output.println(max_x + " " + max_y);
output.flush();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.Scanner;
public class Training {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long index = in.nextLong();
if (index < 10) {
//one digit
System.out.println(index);
} else if (index < 190) {
//two digits
solve(2, index, 10, 10);
} else if (index < 2890) {
//three digits
solve(3, index, 190, 100);
} else if (index < 38890) {
//four digits
solve(4, index, 2890, 1000);
//start changing ------------------------------------------------------------
} else if (index < 488890) {
//five digits
solve(5, index, 38890, 10000);
} else if (index < 5888890) {
//six digits
solve(6, index, 488890, 100000);
} else if (index < 68888890) {
//seven digits
solve(7, index, 5888890, 1000000);
} else if (index < 788888890) {
//eight digits
solve(8, index, 68888890, 10000000);
} else if (index < 8888888890l) {
//nign digits
solve(9, index, 788888890, 100000000);
} else if (index < 98888888890l) {
//ten digits
solve(10, index, 8888888890l, 1000000000);
} else {
solve(11, index, 98888888890l, 10000000000l);
}
}
static void solve(int length, long index, long lastPoint, long num) {
String s = "";
num += (index - lastPoint) / length;
s += num;
int mod = (int) ((index - lastPoint) % length);
System.out.println(s.charAt(mod));
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A implements Runnable {
private void solve() throws IOException {
String str = nextToken();
for (int i=str.length()-1; i>=0; --i)
for (int j=0; j+i<=str.length(); ++j)
if (str.substring(j+1).contains(str.substring(j, j+i))) {
writer.println(i);
return;
}
writer.println(0);
}
public static void main(String[] args) {
new Thread(new A()).start();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
public class c {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
int n = in.nextInt(), m = in.nextInt();
long bounty = in.nextInt(), increase = in.nextInt();
int damage = in.nextInt();
int[] mh = new int[n];
int[] sh = new int[n];
int[] reg = new int[n];
long countKilled = 0;
ArrayList<Event> es = new ArrayList<>();
Event[] regen = new Event[n];
for(int i=0;i<n;i++) {
mh[i] = in.nextInt();
sh[i] = in.nextInt();
reg[i] = in.nextInt();
if(sh[i] <= damage)
countKilled++;
if(reg[i] > 0) {
int time = (damage+1 - sh[i]+reg[i]-1)/reg[i];
if(time > 0 && mh[i] >= damage+1) {
Event e2 = new Event(time, i, damage+1);
regen[i] = e2;
es.add(e2);
}
}
}
for(int i=0;i<m;i++) {
Event e = new Event(in.nextInt(), in.nextInt()-1, in.nextInt());
es.add(e);
if(reg[e.e] > 0) {
int time = (damage+1 - e.h+reg[e.e]-1)/reg[e.e];
if(time > 0 && mh[e.e] >= damage+1) {
Event e2 = new Event(e.t + time, e.e, damage+1);
e.regen = e2;
es.add(e2);
}
}
}
Collections.sort(es, (a,b) -> a.t-b.t);
long ans = countKilled*bounty;
int lastTime = 0;
for(Event e : es) {
if(e.t == -1) continue;
if(regen[e.e] != e && regen[e.e] != null) {
regen[e.e].t = -1;
regen[e.e] = null;
}
if(lastTime != e.t) {
ans = Math.max(ans, countKilled*(bounty+(e.t-1)*increase));
}
if(sh[e.e] <= damage)
countKilled--;
sh[e.e] = e.h;
if(sh[e.e] <= damage)
countKilled++;
if(e.regen != null) {
regen[e.e] = e.regen;
}
lastTime = e.t;
}
if(countKilled != 0) {
if(increase > 0)
ans = -1;
else
ans = Math.max(ans, countKilled*bounty);
}
System.out.println(ans);
}
static class Event {
int t;
int e;
int h;
Event regen;
public Event(int tt, int ee, int hh) {
t = tt;
e = ee;
h = hh;
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = new StringTokenizer("");
}
public String next() throws IOException {
if(st.hasMoreTokens())
return st.nextToken();
else
st = new StringTokenizer(br.readLine());
return next();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
|
nlogn
|
912_C. Perun, Ult!
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main(String[] args) throws IOException {
Reader sc = new Reader();
int k = sc.nextInt();
int[][] buckets = new int[k][];
long[] bucketSum = new long[k];
Map<Integer, Integer> map = new HashMap<>(k * 10000);
long target = 0;
for (int i = 0; i < k; i++) {
int n = sc.nextInt();
int[] arr = new int[n];
for (int j = 0; j < n; j++) {
arr[j] = sc.nextInt();
target += arr[j];
map.put(arr[j], i);
bucketSum[i] += arr[j];
}
buckets[i] = arr;
}
if ((target % k) != 0) {
System.out.println("No");
return;
} else {
target /= k;
}
int[] bitmask = new int[1 << (k )];
Arrays.fill(bitmask, -1);
for (int i = 0; i < k; i++) {
for (int j = 0; j < buckets[i].length; j++) {
int start = buckets[i][j];
int next = (int) (target - bucketSum[i]) + start;
Set<Integer> visited = new HashSet<>();
Set<Integer> visitedBuckets = new HashSet<>();
visited.add(start);
visitedBuckets.add(i);
int bitset = 1 << i;
while (map.containsKey(next)) {
int bucket = map.get(next);
if (start == next) {
bitmask[bitset] = start;
break;
} else if (visited.contains(next)) {
break;
} else if (visitedBuckets.contains(bucket)) {
break;
}
visited.add(next);
visitedBuckets.add(bucket);
next = (int) (target - bucketSum[bucket]) + next;
bitset |= 1 << bucket;
}
}
}
boolean[] dp = new boolean[1 << (k ) ];
Arrays.fill(dp, false);
int[] build = new int[1 << k];
Arrays.fill(build, -1);
for (int i = 0; i < dp.length; i++) {
dp[i] = bitmask[i] != -1;
}
for (int m = 0; m < (1 << k); m++) {
if (!dp[m]) {
for (int s = m; s != 0; s = (s - 1) & m) {
if (dp[s] && dp[(m ^ s)]) {
dp[m] = true;
build[m] = s;
break;
}
}
}
}
System.out.println(dp[dp.length - 1] ? "Yes" : "No");
ArrayList<Integer> path = new ArrayList<>();
rec(path, build, bitmask, (1 << k) - 1);
int[] picked = new int[k];
int[] out = new int[k];
if (dp[dp.length - 1]) {
for (int i : path) {
int prev = i;
int next = (int) (target - bucketSum[map.get(prev)]) + prev;
picked[map.get(next)] = next;
out[map.get(next)] = map.get(prev);
while (next != i) {
int t = next;
next = (int) (target - bucketSum[map.get(next)]) + next;
prev = t;
out[map.get(next)] = map.get(prev);
picked[map.get(next)] = next;
}
}
for (int i = 0; i < out.length; i++) {
System.out.println((picked[i]) + " " + (out[i] + 1));
}
}
}
public static void rec(ArrayList<Integer> path, int[] build, int[] bitmask, int i) {
if (!(i >= 0 && i < bitmask.length)) {
return;
}
if (bitmask[i] != -1) {
path.add(bitmask[i]);
} else {
rec(path, build, bitmask, build[i]);
rec(path, build, bitmask, i ^ build[i]);
}
}
}
|
np
|
1242_C. Sum Balance
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.PrintWriter;
public class C992
{
static class Scanner
{
BufferedReader br;
StringTokenizer tk=new StringTokenizer("");
public Scanner(InputStream is)
{
br=new BufferedReader(new InputStreamReader(is));
}
public int nextInt() throws IOException
{
if(tk.hasMoreTokens())
return Integer.parseInt(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextInt();
}
public long nextLong() throws IOException
{
if(tk.hasMoreTokens())
return Long.parseLong(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextLong();
}
public String next() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken());
tk=new StringTokenizer(br.readLine());
return next();
}
public String nextLine() throws IOException
{
tk=new StringTokenizer("");
return br.readLine();
}
public double nextDouble() throws IOException
{
if(tk.hasMoreTokens())
return Double.parseDouble(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextDouble();
}
public char nextChar() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken().charAt(0));
tk=new StringTokenizer(br.readLine());
return nextChar();
}
public int[] nextIntArray(int n) throws IOException
{
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException
{
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=nextLong();
return a;
}
public int[] nextIntArrayOneBased(int n) throws IOException
{
int a[]=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArrayOneBased(int n) throws IOException
{
long a[]=new long[n+1];
for(int i=1;i<=n;i++)
a[i]=nextLong();
return a;
}
}
static long mod=1000000007;
static long mod_exp(long base,long exp)
{
long ans=1;
base%=mod;
while(exp>0)
{
if(exp%2==1)
{
ans*=base;
ans%=mod;
}
exp/=2;
base*=base;
base%=mod;
}
return ans;
}
public static void main(String args[]) throws IOException
{
Scanner in=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
long x=in.nextLong();
long k=in.nextLong();
long ans=mod_exp(2,k+1);
ans*=(x%mod);
ans%=mod;
ans-=mod_exp(2,k);
ans%=mod;
ans++;
ans%=mod;
if(ans<0)
ans+=mod;
if(x==0)
ans=0;
out.println(ans);
out.close();
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static BufferedReader reader;
static StringTokenizer st;
private static void setReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
private static void updateST() throws IOException {
if (st==null || !st.hasMoreElements()) st = new StringTokenizer(reader.readLine());
}
private static int nextInt() throws IOException {
updateST();
return Integer.parseInt(st.nextToken());
}
public static void main(String[] args) throws IOException {
setReader();
int n = nextInt(), MOD = nextInt();
long[] pow = new long[n+2];
pow[0] = 1;
for (int i=1; i<=n+1; i++) pow[i] = (pow[i-1] * 2) % MOD;
long[][] C = new long[n+2][n+2];
for (int i=0; i<=n+1; i++) {
C[i][0] = 1;
for (int j=1; j<=i; j++) {
C[i][j] = (C[i-1][j-1] + C[i-1][j]) % MOD;
}
}
long[][] dp = new long[n+2][n+1];
dp[0][0] = 1;
for (int i=0; i<=n; i++) {
for (int j=0; j<=i; j++) {
for (int k=1; i + k + 1 <= n + 1; k++) {
dp[i + k + 1][j + k]+=(((dp[i][j] * C[j + k][k]) % MOD * pow[k-1]) % MOD);
dp[i + k + 1][j + k]%=MOD;
}
}
}
long res = 0;
for (int i=0; i<=n; i++) res = (res + dp[n+1][i]) % MOD;
System.out.println(res);
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.util.*;
public class A
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int odd = -1;
int even = -1;
int oc = 0;
int ec = 0;
for(int i=0;i < n;i++)
{
if(scan.nextInt() % 2 == 0)
{
ec++;
even = i+1;
}
else
{
oc++;
odd = i+1;
}
}
if(ec == 1)
System.out.println(even);
else
System.out.println(odd);
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) throws IOException {
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
if (N / 2 % 2 == 1) {
output(-1, out);
} else {
int half = N / 2;
int l = 1, r = half;
int first = query(half, out, sc);
int next = query(2 * half, out, sc);
if (first == next) {
output(half, out);
return;
}
boolean less = first < next;
while (l + 1 < r) {
int med = (l + r) / 2;
first = query(med, out, sc);
next = query(med + half, out, sc);
if (first == next) {
output(med, out);
return;
} else if (first < next == less) {
r = med;
} else {
l = med + 1;
}
}
output(l, out);
}
}
static int query(int pos, PrintWriter out, MyScanner sc) {
out.println("? " + pos);
out.flush();
return sc.nextInt();
}
static void output(int pos, PrintWriter out) {
out.println("! " + pos);
out.flush();
}
static class MyScanner {
private BufferedReader br;
private StringTokenizer tokenizer;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.IntStream;
public class Test {
static PrintWriter writer =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
static long readLong() {
long ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
static String readLine() {
StringBuilder b = new StringBuilder();
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (Character.isLetterOrDigit(c)) {
start = true;
b.append((char) c);
} else if (start) break;
}
} catch (IOException e) {
}
return b.toString();
}
public static void main(String[] args) {
Test te = new Test();
te.start();
writer.flush();
}
void start() {
int t = readInt();
while (t-- > 0) {
int n = readInt(), m = readInt();
int[][] a = new int[n][m];
int[][] e = new int[n*m][];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
a[i][j] = readInt();
e[i*m+j] = new int[]{a[i][j], j};
}
Arrays.sort(e, (x, y) -> x[0] == y[0] ? Integer.compare(x[1], y[1])
: Integer.compare(y[0], x[0]));
Set<Integer> cols = new HashSet<>();
for (int[] x : e) {
cols.add(x[1]);
if (cols.size() >= n) break;
}
int[] dp = new int[1<<n];
Arrays.fill(dp, -1);
dp[0] = 0;
for (int c : cols) {
for (int i = (1 << n) - 1; i >= 0; i--) {
int u = (1 << n) - 1 - i;
int p = u;
if (dp[i] >= 0)
while (p > 0) {
for (int r = 0; r < n; r++) {
int sum = 0;
for (int j = 0; j < n; j++) if (((p >> j) & 1) != 0) sum += a[(j + r) % n][c];
dp[i | p] = Math.max(dp[i | p], dp[i] + sum);
}
p = (p - 1) & u;
}
}
}
writer.println(dp[(1<<n) - 1]);
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.util.*;
import java.io.*;
/*
*/
public class e1 {
static int n;
static int m;
static int[][] mat;
public static void main(String[] args){
JS scan = new JS();
PrintWriter out = new PrintWriter(System.out);
int t = scan.nextInt();
for(int q = 1; q <= t; q++){
ans = 0;
n = scan.nextInt();
m = scan.nextInt();
mat = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
mat[i][j] = scan.nextInt();
}
}
int[] max = new int[m];
PriorityQueue<Item> pq = new PriorityQueue<Item>();
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
max[i] = Math.max(max[i], mat[j][i]);
}
pq.add(new Item(i, max[i]));
}
ArrayList<Item> guys = new ArrayList<Item>();
while(!pq.isEmpty() && guys.size() < 8){
Item tt = pq.poll();
guys.add(tt);
}
perm(guys, 0, new int[guys.size()]);
out.println(ans);
}
out.flush();
}
static int ans = 0;
static void perm(ArrayList<Item> guys, int me, int[] shift){
if(me == guys.size()){
// System.out.println(Arrays.toString(shift));
int res = 0;
int[] best = new int[n];
for(int j = 0; j < guys.size(); j++){
Item g = guys.get(j);
int pp = g.a;
for(int i = 0; i < n; i++){
best[(i+shift[j])%n] = Math.max(best[(i+shift[j])%n], mat[i][pp]);
}
}
for(int i = 0; i < n; i++) res += best[i];
ans = Math.max(res, ans);
return;
}
for(int i = 0; i < n; i++){
shift[me] = i;
perm(guys, me+1, shift);
}
}
static class Item implements Comparable<Item>{
int a;
int b;
public Item(int a, int b){
this.a = a;
this.b = b;
}
public int compareTo(Item o){
return o.b-this.b;
}
}
static class JS{
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public JS() {
in = new BufferedInputStream(System.in, BS);
}
public JS(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author ilyakor
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
int n;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
int base = calc(in, out, 0);
if (base == 0) {
out.printLine("! 1");
out.flush();
return;
}
if (Math.abs(base) % 2 != 0) {
out.printLine("! -1");
out.flush();
return;
}
int down = 0, up = n / 2;
int sdown = base < 0 ? -1 : 1;
int sup = up < 0 ? -1 : 1;
while (up - down > 1) {
int t = (up + down) / 2;
int cur = calc(in, out, t);
if (cur == 0) {
out.printLine("! " + (t + 1));
out.flush();
return;
}
int scur = cur < 0 ? -1 : 1;
if (scur == sdown) {
down = t;
} else {
up = t;
}
}
throw new RuntimeException();
}
private int calc(InputReader in, OutputWriter out, int val) {
out.printLine("? " + (val + 1));
out.flush();
int res1 = in.nextInt();
out.printLine("? " + ((val + n / 2) % n + 1));
out.flush();
int res2 = in.nextInt();
return res1 - res2;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0) {
return -1;
}
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class D0005 {
public static void main(String args[]) throws Exception {
new D0005();
}
D0005() throws Exception {
PandaScanner sc = null;
PrintWriter out = null;
try {
sc = new PandaScanner(System.in);
out = new PrintWriter(System.out);
} catch (Exception ignored) {
}
a = sc.nextInt();
max = sc.nextInt();
double length = sc.nextInt();
double dist = sc.nextInt();
double limit = sc.nextInt();
if (max <= limit) {
out.println(travelTime(length, 0));
}
else {
double tLimit = limit / a;
double dLimit = distance(0, tLimit);
if (dLimit >= dist) {
out.println(travelTime(length, 0));
}
else {
double res = tLimit + 2 * (travelTime(0.5 * (dist - dLimit), limit)) +
travelTime(length - dist, limit);
out.println(res);
}
}
out.close();
System.exit(0);
}
double a, max;
double distance(double v, double t) {
return v * t + 0.5 * a * t * t;
}
double travelTime(double d, double v) {
double tAll = (-v + Math.sqrt(v * v + 2 * a * d)) / a;
double tMax = (max - v) / a;
if (tAll <= tMax) {
return tAll;
}
else {
return tMax + (d - distance(v, tMax)) / max;
}
}
//The PandaScanner class, for Panda fast scanning!
public class PandaScanner {
BufferedReader br;
StringTokenizer st;
InputStream in;
PandaScanner(InputStream in) throws Exception {
br = new BufferedReader(new InputStreamReader(this.in = in));
}
public String next() throws Exception {
if (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine().trim());
return next();
}
return st.nextToken();
}
public boolean hasNext() throws Exception {
return (st != null && st.hasMoreTokens()) || in.available() > 0;
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Main {
public static String conv(String str) {
boolean[] Arr = new boolean[26];
for (int i = 0; i < str.length(); i++) {
Arr[str.charAt(i) - 'a'] = true;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 26; i++) {
if (Arr[i])
sb.append((char) (i + 'a'));
}
return "" + sb;
}
public static void main(String[] args) throws IOException, InterruptedException {
PrintWriter pw = new PrintWriter(System.out);
Scanner sc = new Scanner(System.in);
HashSet<String> hs = new HashSet<String>();
int[] Arr = new int[14];
long max = 0;
for (int i = 0; i < 14; i++) {
Arr[i] = sc.nextInt();
}
for (int i = 0; i < 14; i++) {
int[] arr = Arr.clone();
long sum = 0;
int r = arr[i];
arr[i] = 0;
for (int j = i + 1; j < arr.length && r > 0; j++) {
arr[j]++;
r--;
}
for (int j = 0; j < arr.length; j++) {
arr[j] +=( r / 14);
if (j + 1 <= (r % 14)) {
arr[j]++;
}
if (arr[j] % 2 == 0) {
sum += arr[j];
}
}
max = Math.max(max, sum);
}
System.out.println(max);
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
constant
|
975_B. Mancala
|
CODEFORCES
|
//package round35;
import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class C {
Scanner in;
PrintWriter out;
// String INPUT = "3 3 1 1 1";
String INPUT = "";
void solve()
{
int n = ni();
int m = ni();
int k = ni();
int[] x = new int[k];
int[] y = new int[k];
for(int i = 0;i < k;i++){
x[i] = ni() - 1;
y[i] = ni() - 1;
}
int max = -1;
int maxi = -1;
int maxj = -1;
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
int min = Integer.MAX_VALUE;
for(int l = 0;l < k;l++){
min = Math.min(min, Math.abs(x[l] - i) + Math.abs(y[l] - j));
}
if(min > max){
max = min;
maxi = i;
maxj = j;
}
}
}
out.println((maxi+1) + " " + (maxj+1));
}
void run() throws Exception
{
in = INPUT.isEmpty() ? new Scanner(new File("input.txt")) : new Scanner(INPUT);
out = INPUT.isEmpty() ? new PrintWriter("output.txt") : new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception
{
new C().run();
}
int ni() { return Integer.parseInt(in.next()); }
void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); }
static String join(int[] a, int d){StringBuilder sb = new StringBuilder();for(int v : a){sb.append(v + d + " ");}return sb.toString();}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
//package round584;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
public class E4 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
for(int T = ni(); T> 0;T--){
int n = ni(), m = ni();
int[][] a = new int[n][];
for(int i = 0;i < n;i++)a[i] = na(m);
int[][] mx = new int[m][];
for(int i = 0;i < m;i++){
int u = 0;
for(int j = 0;j < n;j++){
u = Math.max(u, a[j][i]);
}
mx[i] = new int[]{u, i};
}
Arrays.sort(mx, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return -(a[0] - b[0]);
}
});
int[] dp = new int[1<<n];
for(int i = 0;i < n && i < m;i++){
int c = mx[i][1];
int[] ls = new int[1<<n];
for(int j = 1;j < 1<<n;j++){
ls[j] = ls[j&j-1] + a[Integer.numberOfTrailingZeros(j)][c];
}
for(int j = 1;j < 1<<n;j++){
int r = rot(j, n);
ls[r] = Math.max(ls[r], ls[j]);
}
int[] ndp = new int[1<<n];
for(int j = 0;j < 1<<n;j++){
if(rot(j, n) == j){
int cur = j;
for(int sh = 0;sh < n;sh++){
cur = cur>>1|(cur&1)<<n-1;
int mask = (1<<n)-1^cur;
for(int k = mask;k >= 0;k--){
k &= mask;
ndp[k|cur] = Math.max(
ndp[k|cur], dp[k] + ls[j]);
}
}
}
}
dp = ndp;
}
out.println(dp[(1<<n)-1]);
}
}
int rot(int x, int n)
{
int ret = x;
for(int i = 0;i < n;i++){
x = x>>>1|(x&1)<<n-1;
ret = Math.min(ret, x);
}
return ret;
}
void run() throws Exception
{
// int n = 12, m = 2000;
// Random gen = new Random();
// StringBuilder sb = new StringBuilder();
// sb.append(40 + " ");
// for(int rep = 0;rep < 40;rep++){
// sb.append(n + " ");
// sb.append(m + " ");
// for (int i = 0; i < n*m; i++) {
// sb.append(gen.nextInt(100000) + " ");
// }
// }
// INPUT = sb.toString();
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 E4().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
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.io.BufferedInputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(new BufferedInputStream(System.in));
PrintStream out=System.out;
int n=in.nextInt();
if (n>=0) out.println(n);
else out.println(Math.max(-((-n)/10), -((-n)/100*10+(-n)%10)));
out.close();
in.close();
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
//stan hu tao
//join nct ridin by first year culture reps
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1209E
{
public static void main(String hi[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
while(T-->0)
{
st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[][] grid = new int[N][M];
for(int r=0; r < N; r++)
grid[r] = readArr(M, infile, st);
ArrayList<Integer> ls = new ArrayList<Integer>();
for(int i=0; i < M; i++)
ls.add(i);
Collections.sort(ls, (x,y) -> {
int m1 = grid[0][x];
int m2 = grid[0][y];
for(int r=1; r < N; r++)
{
m1 = max(m1, grid[r][x]);
m2 = max(m2, grid[r][y]);
}
return m2-m1;
});
int[][] newgrid = new int[N][M];
for(int r=0; r < N; r++)
for(int c=0; c < M; c++)
newgrid[r][c] = grid[r][ls.get(c)];
M = min(M, N);
int[][] sums = new int[M][1<<N];
for(int i=1; i < M; i++)
for(int mask=0; mask < 1<<N; mask++)
{
//try all shifts
for(int head=0; head < N; head++)
{
int temp = 0;
for(int b=0; b < N; b++)
{
int nb = b+head;
if(nb >= N)
nb -= N;
if((mask&(1<<nb)) > 0)
temp += newgrid[b][i];
}
sums[i][mask] = max(sums[i][mask], temp);
}
}
int[][] dp = new int[M][1<<N];
for(int mask=0; mask < 1<<N; mask++)
for(int b=0; b < N; b++)
if((mask&(1<<b)) > 0)
dp[0][mask] += newgrid[b][0];
for(int i=1; i < M; i++)
for(int mask=0; mask < 1<<N; mask++)
for(int pmask=mask; pmask >= 0; pmask=(pmask-1)&mask)
{
dp[i][mask] = max(dp[i][mask], dp[i-1][pmask]+sums[i][mask-pmask]);
if(pmask == 0)
break;
}
sb.append(dp[M-1][(1<<N)-1]+"\n");
}
System.out.print(sb);
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.util.*;
public class A912 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int A = scan.nextInt();
int B = scan.nextInt();
long x = scan.nextInt();
long y = scan.nextInt();
long z = scan.nextInt();
long requiredA = x * 2 + y;
long requiredB = y + z * 3;
long neededA = Math.max(0, requiredA - A);
long neededB = Math.max(0, requiredB - B);
System.out.print(neededA + neededB);
}
}
|
constant
|
912_A. Tricky Alchemy
|
CODEFORCES
|
import java.util.Scanner;
public class Solution {
public static void main(String [] args){
Scanner stdin = new Scanner(System.in);
long n = stdin.nextLong();
if(n<3) System.out.println(n);
else {
if(n%2==0){
long a=0,b=0;
if(n%3!=0) a = (n*(n-1)*(n-3));
n--;
b = (n*(n-1)*(n-2));
System.out.println(Math.max(a, b));
}
else System.out.println(n*(n-1)*(n-2));
}
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
FastReader in = new FastReader();
int n = in.nextInt();
int[] a = new int[101];
for (int i = 0; i < n; i++) {
a[in.nextInt()]++;
}
int count = 0;
for (int i = 1; i < 101; i++) {
if (a[i] > 0) {
count++;
for (int j = i; j < 101; j += i) {
a[j] = 0;
}
}
}
System.out.println(count);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int[] nextSortedIntArray(int n) {
int array[] = nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n) {
int[] array = new int[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public long[] nextSumLongArray(int n) {
long[] array = new long[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextSortedLongArray(int n) {
long array[] = nextLongArray(n);
Arrays.sort(array);
return array;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A135 {
public static void main(String[] args) throws Exception {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(r.readLine());
int[] ar = new int[n];
StringTokenizer st = new StringTokenizer(r.readLine());
for (int x = 0; x < n; x++) {
ar[x] = Integer.parseInt(st.nextToken());
}
Arrays.sort(ar);
if (n == 1) {
System.out.println(ar[0]==1?"2":"1");
return;
}
if (ar[n - 1] == 1) {
ar[n - 2] = 2;
}
System.out.print("1");
for (int x = 0; x < n - 1; x++) {
System.out.print(" " + ar[x]);
}
System.out.println();
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Round1B {
public static void main(String[] args) throws Exception {
new Round1B().run();
}
private void run() throws Exception {
Scanner sc = new Scanner(System.in);
int tc = Integer.parseInt(sc.nextLine().trim());
while (tc > 0) {
String s = sc.nextLine().trim();
if (s.matches("R[0-9]+C[0-9]+")) {
Pattern p = Pattern.compile("R([0-9]+)C([0-9]+)");
Matcher m = p.matcher(s);
if (m.matches()) {
int rows = Integer.parseInt(m.group(1));
int cols = Integer.parseInt(m.group(2));
String col = "";
while (cols > 0) {
int mod = (cols - 1) % 26;
col = (char)('A' + mod) + col;
cols = (cols - 1) / 26;
}
System.out.println(col + rows);
} else {
throw new Exception();
}
} else {
Pattern p = Pattern.compile("([A-Z]+)([0-9]+)");
Matcher m = p.matcher(s);
if (m.matches()) {
int rows = Integer.parseInt(m.group(2));
int cols = 0;
int mul = 1;
for (int i = m.group(1).length() - 1; i >= 0; i--) {
cols += mul * (m.group(1).charAt(i) - 'A' + 1);
mul *= 26;
}
System.out.printf("R%dC%d\n", rows, cols);
}
else {
throw new Exception();
}
}
tc--;
}
sc.close();
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Scanner;
/**
*
* @author dilshan
*/
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = 1;
int t = 0;
int y = 2;
int[] a = new int[100000];
if(n==0){
System.out.println(0+" "+0+" "+0);
}
else
if(n==1){
System.out.println(0+" "+0+" "+1);
}
else
if(n==2){
System.out.println(0+" "+1+" "+1);
}
else{
a[0] = 0;
a[1] = 1;
a[y] = a[y - 2] + a[y - 1];
while (a[y - 1] < n) {
a[y] = a[y - 2] + a[y - 1];
++y;
}
System.out.println(a[y - 2] + " " + a[y - 4] + " " + a[y - 5]);
}
//System.out.println(y);
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
public class Main implements Runnable {
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 Main(), "Main", 1 << 27).start();
}
static class Pair {
int f;
int s;
int p;
PrintWriter w;
// int t;
Pair(int f, int s) {
// Pair(int f,int s, PrintWriter w){
this.f = f;
this.s = s;
// this.p = p;
// this.w = w;
// this.t = t;
}
public static Comparator<Pair> wc = new Comparator<Pair>() {
public int compare(Pair e1,Pair e2){
// 1 for swap
if(Math.abs(e1.f)-Math.abs(e2.f)!=0){
// e1.w.println("**"+e1.f+" "+e2.f);
return -1*(Math.abs(e1.f)-Math.abs(e2.f));
}
else{
// e1.w.println("##"+e1.f+" "+e2.f);
return(Math.abs(e1.s)-Math.abs(e2.s));
}
}};
}
public Integer[] sort(Integer[] a) {
Arrays.sort(a);
return a;
}
public Long[] sort(Long[] a) {
Arrays.sort(a);
return a;
}
public static ArrayList<Integer> sieve(int N) {
int i, j, flag;
ArrayList<Integer> p = new ArrayList<Integer>();
for (i = 1; i < N; i++) {
if (i == 1 || i == 0)
continue;
flag = 1;
for (j = 2; j <= i / 2; ++j) {
if (i % j == 0) {
flag = 0;
break;
}
}
if (flag == 1) {
p.add(i);
}
}
return p;
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
public static int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
//// recursive dfs
public static int dfs(int s, ArrayList<Integer>[] g, long[] dist, boolean[] v, PrintWriter w, int p) {
v[s] = true;
int ans = 1;
// int n = dist.length - 1;
int t = g[s].size();
// int max = 1;
for (int i = 0; i < t; i++) {
int x = g[s].get(i);
if (!v[x]) {
// dist[x] = dist[s] + 1;
ans = Math.min(ans, dfs(x, g, dist, v, w, s));
} else if (x != p) {
// w.println("* " + s + " " + x + " " + p);
ans = 0;
}
}
// max = Math.max(max,(n-p));
return ans;
}
//// iterative BFS
public static int bfs(int s, ArrayList<Integer>[] g, long[] dist, boolean[] b, PrintWriter w, int p) {
b[s] = true;
int siz = 1;
// dist--;
Queue<Integer> q = new LinkedList<>();
q.add(s);
while (q.size() != 0) {
int i = q.poll();
Iterator<Integer> it = g[i].listIterator();
int z = 0;
while (it.hasNext()) {
z = it.next();
if (!b[z]) {
b[z] = true;
// dist--;
dist[z] = dist[i] + 1;
// siz++;
q.add(z);
} else if (z != p) {
siz = 0;
}
}
}
return siz;
}
public static int lower(int a[], int x) { // x is the target value or key
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] >= x)
r = m;
else
l = m;
}
return r;
}
public static int upper(int a[], int x) {// x is the key or target value
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] <= x)
l = m;
else
r = m;
}
return l + 1;
}
public static int lower(ArrayList<Integer> a, int x) { // x is the target value or key
int l = -1, r = a.size();
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a.get(m) >= x)
r = m;
else
l = m;
}
return r;
}
public static int upper(ArrayList<Integer> a, int x) {// x is the key or target value
int l = -1, r = a.size();
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a.get(m) <= x)
l = m;
else
r = m;
}
return l + 1;
}
public static long power(long x, long y, long m) {
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (p * p) % m;
if (y % 2 == 0)
return p;
else
return (x * p) % m;
}
public void yesOrNo(boolean f){
if(f){
w.println("YES");
}
else{
w.println("NO");
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
// code here
int oo = (int) 1e9;
int[] parent;
int[] dist;
int[] height;
boolean[] vis;
// ArrayList<Integer>[] g;
//int[] col;
//HashMap<Long, Boolean>[] dp;
char[][] g;
// boolean[][] v;
//long[] a;
// ArrayList<Integer[]> a;
// int[][] ans;
long[][][] dp;
long mod;
int n;
int m;
int k;
long[][] pre;
// StringBuilder[] a;
// StringBuilder[] b;
//StringBuilder ans;
int[][] col;
int[][] row;
PrintWriter w = new PrintWriter(System.out);
public void run() {
InputReader sc = new InputReader(System.in);
int defaultValue = 0;
mod = 1000000007;
int test = 1;
//test = sc.nextInt();
while (test-- > 0) {
n = sc.nextInt();
m = sc.nextInt();
k = sc.nextInt();
col = new int[n][m-1];
row = new int[n-1][m];
dp = new long[n][m][21];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
Arrays.fill(dp[i][j],oo);
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m-1;j++){
col[i][j] = sc.nextInt();
}
}
for(int i=0;i<n-1;i++){
for(int j=0;j<m;j++){
row[i][j] = sc.nextInt();
}
}
if(k%2!=0){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
w.print(-1+" ");
}
w.println("");
}
}
else{
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
long ans = sol(i,j,k/2);
w.print((ans*2)+" ");
}
w.println("");
}
}
}
w.flush();
w.close();
}
public long sol(int i, int j, int steps){
if(steps == 0)return 0;
else if(dp[i][j][steps]!=oo)return dp[i][j][steps];
else{
long ans = oo;
if(i-1>-1){
ans = Math.min(ans,sol(i-1,j,steps-1)+row[i-1][j]);
}
if(i+1<n){
ans = Math.min(ans,sol(i+1,j,steps-1)+row[i][j]);
}
if(j-1>-1){
ans = Math.min(ans,sol(i,j-1,steps-1)+col[i][j-1]);
}
if(j+1<m){
ans = Math.min(ans,sol(i,j+1,steps-1)+col[i][j]);
}
dp[i][j][steps] = Math.min(dp[i][j][steps],ans);
return dp[i][j][steps];
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int n, exp;
static double arr[][],dp[], dies[][];
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = new Integer(br.readLine());
arr = new double[n][n];
StringTokenizer st;
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < n; j++) {
arr[i][j] = Double.parseDouble(st.nextToken());
}
}
exp = 1<<n;
dp = new double[exp];
dies = new double[n][exp];
for (int all = 0; all < exp; all++) {
dp[all] = -1;
int countAlive = 0;
for (int i = 0; i < n; i++) {
if((all&(1<<i))!=0)
countAlive++;
}
if(countAlive <2)continue;
double x=1.0/(countAlive*(countAlive-1)/2.0);
for(int i=0; i<n; i++){
dies[i][all]=0;
int mask=1<<i;
if((mask&all)>0){
for(int j=0; j<n; j++)
{
int mask2=1<<j;
if((mask2&all)>0)
dies[i][all]+=arr[j][i];
}
dies[i][all]*=x;
}
}
}
for(int myFish=0; myFish<n; myFish++){
if(myFish>0)System.out.printf(" ");
System.out.printf("%.6f",ff(1<<myFish));
}
System.out.println();
}
static double ff(int state){
if(state==exp-1)return 1;
if(dp[state]!=-1)return dp[state];
double ans=0;
for(int i=0; i<n; i++)
{
int mask=1<<i;
if((mask &state)==0)
{
ans+=dies[i][state+mask]*ff(state+mask);
}
}
return dp[state]=ans;
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.BigInteger;
import java.math.BigDecimal;
public class Main {
static class Task {
void solve(int test, FastScanner in, PrintWriter out) throws IOException {
int n = in.nextInt();
int d = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Arrays.sort(a);
int ans = 2;
for (int i = 0; i < n - 1; i++) {
if (a[i + 1] - d > a[i] + d) {
ans += 2;
} else if (a[i + 1] - d >= a[i] + d) {
ans++;
}
}
out.println(ans);
}
}
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
// FastScanner in = new FastScanner("input.txt");
// PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
new Task().solve(1, in, out);
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer token;
public FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String nextToken() {
while (token == null || !token.hasMoreTokens()) {
try {
token = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return token.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.util.*;
public class icpc
{
public static void main(String[] args) throws IOException
{
Reader in = new Reader();
// BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = in.nextInt();
boolean[] A = new boolean[n];
int count = 0;
int[] B = new int[n];
for (int i=0;i<n;i++)
B[i] = in.nextInt();
Arrays.sort(B);
for (int i=0;i<n;i++)
{
if (!A[i])
{
int gcd = B[i];
for (int j=0;j<n;j++)
{
if(!A[j])
{
gcd = gcd(B[j], gcd);
if(gcd == B[i])
{
A[j] = true;
}
else
{
gcd = B[i];
}
}
}
count++;
A[i] = true;
}
}
System.out.println(count);
}
public static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
}
class DSU
{
int[] parent;
int[] size;
//Pass number of total nodes as parameter to the constructor
DSU(int n)
{
this.parent = new int[n];
this.size = new int[n];
Arrays.fill(parent, -1);
}
public void makeSet(int v)
{
parent[v] = v;
size[v] = 1;
}
public int findSet(int v)
{
if (v == parent[v]) return v;
return parent[v] = findSet(parent[v]);
}
public void unionSets(int a, int b)
{
a = findSet(a);
b = findSet(b);
if (a != b)
{
if (size[a] < size[b])
{
int temp = a;
a = b;
b = temp;
}
parent[b] = a;
size[a] += size[b];
}
}
}
class FastFourierTransform
{
private void fft(double[] a, double[] b, boolean invert)
{
int count = a.length;
for (int i = 1, j = 0; i < count; i++)
{
int bit = count >> 1;
for (; j >= bit; bit >>= 1)
j -= bit;
j += bit;
if (i < j)
{
double temp = a[i];
a[i] = a[j];
a[j] = temp;
temp = b[i];
b[i] = b[j];
b[j] = temp;
}
}
for (int len = 2; len <= count; len <<= 1)
{
int halfLen = len >> 1;
double angle = 2 * Math.PI / len;
if (invert)
angle = -angle;
double wLenA = Math.cos(angle);
double wLenB = Math.sin(angle);
for (int i = 0; i < count; i += len)
{
double wA = 1;
double wB = 0;
for (int j = 0; j < halfLen; j++)
{
double uA = a[i + j];
double uB = b[i + j];
double vA = a[i + j + halfLen] * wA - b[i + j + halfLen] * wB;
double vB = a[i + j + halfLen] * wB + b[i + j + halfLen] * wA;
a[i + j] = uA + vA;
b[i + j] = uB + vB;
a[i + j + halfLen] = uA - vA;
b[i + j + halfLen] = uB - vB;
double nextWA = wA * wLenA - wB * wLenB;
wB = wA * wLenB + wB * wLenA;
wA = nextWA;
}
}
}
if (invert)
{
for (int i = 0; i < count; i++)
{
a[i] /= count;
b[i] /= count;
}
}
}
public long[] multiply(long[] a, long[] b)
{
int resultSize = Integer.highestOneBit(Math.max(a.length, b.length) - 1) << 2;
resultSize = Math.max(resultSize, 1);
double[] aReal = new double[resultSize];
double[] aImaginary = new double[resultSize];
double[] bReal = new double[resultSize];
double[] bImaginary = new double[resultSize];
for (int i = 0; i < a.length; i++)
aReal[i] = a[i];
for (int i = 0; i < b.length; i++)
bReal[i] = b[i];
fft(aReal, aImaginary, false);
fft(bReal, bImaginary, false);
for (int i = 0; i < resultSize; i++)
{
double real = aReal[i] * bReal[i] - aImaginary[i] * bImaginary[i];
aImaginary[i] = aImaginary[i] * bReal[i] + bImaginary[i] * aReal[i];
aReal[i] = real;
}
fft(aReal, aImaginary, true);
long[] result = new long[resultSize];
for (int i = 0; i < resultSize; i++)
result[i] = Math.round(aReal[i]);
return result;
}
}
class NumberTheory
{
public boolean isPrime(long n)
{
if(n < 2)
return false;
for(long x = 2;x * x <= n;x++)
{
if(n % x == 0)
return false;
}
return true;
}
public ArrayList<Long> primeFactorisation(long n)
{
ArrayList<Long> f = new ArrayList<>();
for(long x=2;x * x <= n;x++)
{
while(n % x == 0)
{
f.add(x);
n /= x;
}
}
if(n > 1)
f.add(n);
return f;
}
public int[] sieveOfEratosthenes(int n)
{
//Returns an array with the smallest prime factor for each number and primes marked as 0
int[] sieve = new int[n + 1];
for(int x=2;x * x <= n;x++)
{
if(sieve[x] != 0)
continue;
for(int u=x*x;u<=n;u+=x)
{
if(sieve[u] == 0)
{
sieve[u] = x;
}
}
}
return sieve;
}
public long gcd(long a, long b)
{
if(b == 0)
return a;
return gcd(b, a % b);
}
public long phi(long n)
{
double result = n;
for(long p=2;p*p<=n;p++)
{
if(n % p == 0)
{
while (n % p == 0)
n /= p;
result *= (1.0 - (1.0 / (double)p));
}
}
if(n > 1)
result *= (1.0 - (1.0 / (double)n));
return (long)result;
}
public Name extendedEuclid(long a, long b)
{
if(b == 0)
return new Name(a, 1, 0);
Name n1 = extendedEuclid(b, a % b);
Name n2 = new Name(n1.d, n1.y, n1.x - (long)Math.floor((double)a / b) * n1.y);
return n2;
}
public long modularExponentiation(long a, long b, long n)
{
long d = 1L;
String bString = Long.toBinaryString(b);
for(int i=0;i<bString.length();i++)
{
d = (d * d) % n;
if(bString.charAt(i) == '1')
d = (d * a) % n;
}
return d;
}
}
class Name
{
long d;
long x;
long y;
public Name(long d, long x, long y)
{
this.d = d;
this.x = x;
this.y = y;
}
}
class SuffixArray
{
int ALPHABET_SZ = 256, N;
int[] T, lcp, sa, sa2, rank, tmp, c;
public SuffixArray(String str)
{
this(toIntArray(str));
}
private static int[] toIntArray(String s)
{
int[] text = new int[s.length()];
for (int i = 0; i < s.length(); i++) text[i] = s.charAt(i);
return text;
}
public SuffixArray(int[] text)
{
T = text;
N = text.length;
sa = new int[N];
sa2 = new int[N];
rank = new int[N];
c = new int[Math.max(ALPHABET_SZ, N)];
construct();
kasai();
}
private void construct()
{
int i, p, r;
for (i = 0; i < N; ++i) c[rank[i] = T[i]]++;
for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1];
for (i = N - 1; i >= 0; --i) sa[--c[T[i]]] = i;
for (p = 1; p < N; p <<= 1)
{
for (r = 0, i = N - p; i < N; ++i) sa2[r++] = i;
for (i = 0; i < N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p;
Arrays.fill(c, 0, ALPHABET_SZ, 0);
for (i = 0; i < N; ++i) c[rank[i]]++;
for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1];
for (i = N - 1; i >= 0; --i) sa[--c[rank[sa2[i]]]] = sa2[i];
for (sa2[sa[0]] = r = 0, i = 1; i < N; ++i)
{
if (!(rank[sa[i - 1]] == rank[sa[i]]
&& sa[i - 1] + p < N
&& sa[i] + p < N
&& rank[sa[i - 1] + p] == rank[sa[i] + p])) r++;
sa2[sa[i]] = r;
}
tmp = rank;
rank = sa2;
sa2 = tmp;
if (r == N - 1) break;
ALPHABET_SZ = r + 1;
}
}
private void kasai()
{
lcp = new int[N];
int[] inv = new int[N];
for (int i = 0; i < N; i++) inv[sa[i]] = i;
for (int i = 0, len = 0; i < N; i++)
{
if (inv[i] > 0)
{
int k = sa[inv[i] - 1];
while ((i + len < N) && (k + len < N) && T[i + len] == T[k + len]) len++;
lcp[inv[i] - 1] = len;
if (len > 0) len--;
}
}
}
}
class ZAlgorithm
{
public int[] calculateZ(char input[])
{
int Z[] = new int[input.length];
int left = 0;
int right = 0;
for(int k = 1; k < input.length; k++) {
if(k > right) {
left = right = k;
while(right < input.length && input[right] == input[right - left]) {
right++;
}
Z[k] = right - left;
right--;
} else {
//we are operating inside box
int k1 = k - left;
//if value does not stretches till right bound then just copy it.
if(Z[k1] < right - k + 1) {
Z[k] = Z[k1];
} else { //otherwise try to see if there are more matches.
left = k;
while(right < input.length && input[right] == input[right - left]) {
right++;
}
Z[k] = right - left;
right--;
}
}
}
return Z;
}
public ArrayList<Integer> matchPattern(char text[], char pattern[])
{
char newString[] = new char[text.length + pattern.length + 1];
int i = 0;
for(char ch : pattern) {
newString[i] = ch;
i++;
}
newString[i] = '$';
i++;
for(char ch : text) {
newString[i] = ch;
i++;
}
ArrayList<Integer> result = new ArrayList<>();
int Z[] = calculateZ(newString);
for(i = 0; i < Z.length ; i++) {
if(Z[i] == pattern.length) {
result.add(i - pattern.length - 1);
}
}
return result;
}
}
class KMPAlgorithm
{
public int[] computeTemporalArray(char[] pattern)
{
int[] lps = new int[pattern.length];
int index = 0;
for(int i=1;i<pattern.length;)
{
if(pattern[i] == pattern[index])
{
lps[i] = index + 1;
index++;
i++;
}
else
{
if(index != 0)
{
index = lps[index - 1];
}
else
{
lps[i] = 0;
i++;
}
}
}
return lps;
}
public ArrayList<Integer> KMPMatcher(char[] text, char[] pattern)
{
int[] lps = computeTemporalArray(pattern);
int j = 0;
int i = 0;
int n = text.length;
int m = pattern.length;
ArrayList<Integer> indices = new ArrayList<>();
while(i < n)
{
if(pattern[j] == text[i])
{
i++;
j++;
}
if(j == m)
{
indices.add(i - j);
j = lps[j - 1];
}
else if(i < n && pattern[j] != text[i])
{
if(j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
return indices;
}
}
class Hashing
{
public long[] computePowers(long p, int n, long m)
{
long[] powers = new long[n];
powers[0] = 1;
for(int i=1;i<n;i++)
{
powers[i] = (powers[i - 1] * p) % m;
}
return powers;
}
public long computeHash(String s)
{
long p = 31;
long m = 1_000_000_009;
long hashValue = 0L;
long[] powers = computePowers(p, s.length(), m);
for(int i=0;i<s.length();i++)
{
char ch = s.charAt(i);
hashValue = (hashValue + (ch - 'a' + 1) * powers[i]) % m;
}
return hashValue;
}
}
class BasicFunctions
{
public long min(long[] A)
{
long min = Long.MAX_VALUE;
for(int i=0;i<A.length;i++)
{
min = Math.min(min, A[i]);
}
return min;
}
public long max(long[] A)
{
long max = Long.MAX_VALUE;
for(int i=0;i<A.length;i++)
{
max = Math.max(max, A[i]);
}
return max;
}
}
class MergeSortInt
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r) {
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
/*Copy data to temp arrays*/
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r) {
if (l < r) {
// Find the middle point
int m = (l + r) / 2;
// Sort first and second halves
sort(arr, l, m);
sort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
}
class MergeSortLong
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(long arr[], int l, int m, int r) {
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long[n1];
long R[] = new long[n2];
/*Copy data to temp arrays*/
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(long arr[], int l, int r) {
if (l < r) {
// Find the middle point
int m = (l + r) / 2;
// Sort first and second halves
sort(arr, l, m);
sort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
}
class Node
{
String s;
Node(String s)
{
this.s = s;
}
@Override
public boolean equals(Object ob)
{
if(ob == null)
return false;
if(!(ob instanceof Node))
return false;
if(ob == this)
return true;
Node obj = (Node)ob;
if(this.s.equals(obj.s))
return true;
return false;
}
@Override
public int hashCode()
{
return (int)this.s.length();
}
}
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
class FenwickTree
{
public void update(long[] fenwickTree,long delta,int index)
{
index += 1;
while(index < fenwickTree.length)
{
fenwickTree[index] += delta;
index = index + (index & (-index));
}
}
public long prefixSum(long[] fenwickTree,int index)
{
long sum = 0L;
index += 1;
while(index > 0)
{
sum += fenwickTree[index];
index -= (index & (-index));
}
return sum;
}
}
class SegmentTree
{
public int nextPowerOfTwo(int num)
{
if(num == 0)
return 1;
if(num > 0 && (num & (num - 1)) == 0)
return num;
while((num &(num - 1)) > 0)
{
num = num & (num - 1);
}
return num << 1;
}
public int[] createSegmentTree(int[] input)
{
int np2 = nextPowerOfTwo(input.length);
int[] segmentTree = new int[np2 * 2 - 1];
for(int i=0;i<segmentTree.length;i++)
segmentTree[i] = Integer.MIN_VALUE;
constructSegmentTree(segmentTree,input,0,input.length-1,0);
return segmentTree;
}
private void constructSegmentTree(int[] segmentTree,int[] input,int low,int high,int pos)
{
if(low == high)
{
segmentTree[pos] = input[low];
return;
}
int mid = (low + high)/ 2;
constructSegmentTree(segmentTree,input,low,mid,2*pos + 1);
constructSegmentTree(segmentTree,input,mid+1,high,2*pos + 2);
segmentTree[pos] = Math.max(segmentTree[2*pos + 1],segmentTree[2*pos + 2]);
}
public int rangeMinimumQuery(int []segmentTree,int qlow,int qhigh,int len)
{
return rangeMinimumQuery(segmentTree,0,len-1,qlow,qhigh,0);
}
private int rangeMinimumQuery(int segmentTree[],int low,int high,int qlow,int qhigh,int pos)
{
if(qlow <= low && qhigh >= high){
return segmentTree[pos];
}
if(qlow > high || qhigh < low){
return Integer.MIN_VALUE;
}
int mid = (low+high)/2;
return Math.max(rangeMinimumQuery(segmentTree, low, mid, qlow, qhigh, 2 * pos + 1),
rangeMinimumQuery(segmentTree, mid + 1, high, qlow, qhigh, 2 * pos + 2));
}
}
class Trie
{
private class TrieNode
{
Map<Character, TrieNode> children;
boolean endOfWord;
public TrieNode()
{
children = new HashMap<>();
endOfWord = false;
}
}
private final TrieNode root;
public Trie()
{
root = new TrieNode();
}
public void insert(String word)
{
TrieNode current = root;
for (int i = 0; i < word.length(); i++)
{
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null)
{
node = new TrieNode();
current.children.put(ch, node);
}
current = node;
}
current.endOfWord = true;
}
public boolean search(String word)
{
TrieNode current = root;
for (int i = 0; i < word.length(); i++)
{
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null)
{
return false;
}
current = node;
}
return current.endOfWord;
}
public void delete(String word)
{
delete(root, word, 0);
}
private boolean delete(TrieNode current, String word, int index)
{
if (index == word.length())
{
if (!current.endOfWord)
{
return false;
}
current.endOfWord = false;
return current.children.size() == 0;
}
char ch = word.charAt(index);
TrieNode node = current.children.get(ch);
if (node == null)
{
return false;
}
boolean shouldDeleteCurrentNode = delete(node, word, index + 1);
if (shouldDeleteCurrentNode)
{
current.children.remove(ch);
return current.children.size() == 0;
}
return false;
}
}
class SegmentTreeLazy
{
public int nextPowerOfTwo(int num)
{
if(num == 0)
return 1;
if(num > 0 && (num & (num - 1)) == 0)
return num;
while((num &(num - 1)) > 0)
{
num = num & (num - 1);
}
return num << 1;
}
public int[] createSegmentTree(int input[])
{
int nextPowOfTwo = nextPowerOfTwo(input.length);
int segmentTree[] = new int[nextPowOfTwo*2 -1];
for(int i=0; i < segmentTree.length; i++){
segmentTree[i] = Integer.MAX_VALUE;
}
constructMinSegmentTree(segmentTree, input, 0, input.length - 1, 0);
return segmentTree;
}
private void constructMinSegmentTree(int segmentTree[], int input[], int low, int high,int pos)
{
if(low == high)
{
segmentTree[pos] = input[low];
return;
}
int mid = (low + high)/2;
constructMinSegmentTree(segmentTree, input, low, mid, 2 * pos + 1);
constructMinSegmentTree(segmentTree, input, mid + 1, high, 2 * pos + 2);
segmentTree[pos] = Math.min(segmentTree[2*pos+1], segmentTree[2*pos+2]);
}
public void updateSegmentTreeRangeLazy(int input[], int segmentTree[], int lazy[], int startRange, int endRange, int delta)
{
updateSegmentTreeRangeLazy(segmentTree, lazy, startRange, endRange, delta, 0, input.length - 1, 0);
}
private void updateSegmentTreeRangeLazy(int segmentTree[], int lazy[], int startRange, int endRange, int delta, int low, int high, int pos)
{
if(low > high)
{
return;
}
if (lazy[pos] != 0)
{
segmentTree[pos] += lazy[pos];
if (low != high)
{
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if(startRange > high || endRange < low)
{
return;
}
if(startRange <= low && endRange >= high)
{
segmentTree[pos] += delta;
if(low != high) {
lazy[2*pos + 1] += delta;
lazy[2*pos + 2] += delta;
}
return;
}
int mid = (low + high)/2;
updateSegmentTreeRangeLazy(segmentTree, lazy, startRange, endRange, delta, low, mid, 2*pos+1);
updateSegmentTreeRangeLazy(segmentTree, lazy, startRange, endRange, delta, mid+1, high, 2*pos+2);
segmentTree[pos] = Math.min(segmentTree[2*pos + 1], segmentTree[2*pos + 2]);
}
public int rangeMinimumQueryLazy(int segmentTree[], int lazy[], int qlow, int qhigh, int len)
{
return rangeMinimumQueryLazy(segmentTree, lazy, qlow, qhigh, 0, len - 1, 0);
}
private int rangeMinimumQueryLazy(int segmentTree[], int lazy[], int qlow, int qhigh, int low, int high, int pos)
{
if(low > high)
{
return Integer.MAX_VALUE;
}
if (lazy[pos] != 0)
{
segmentTree[pos] += lazy[pos];
if (low != high)
{
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if(qlow > high || qhigh < low)
{
return Integer.MAX_VALUE;
}
if(qlow <= low && qhigh >= high)
{
return segmentTree[pos];
}
int mid = (low+high)/2;
return Math.min(rangeMinimumQueryLazy(segmentTree, lazy, qlow, qhigh, low, mid, 2 * pos + 1), rangeMinimumQueryLazy(segmentTree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2));
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class p7{
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader sc = new FastReader();
//PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int k = sc.nextInt();
long one = (long)Math.pow(2, k) - 1;
long[] arr = new long[n+1];
arr[0] = 0;
for(int i=1;i<=n;i++){
arr[i] = sc.nextLong();
arr[i] ^= arr[i-1];
}
Map<Long, Long> count = new HashMap<>();
for(int i=0;i<=n;i++){
Long key = Math.min(arr[i], (arr[i]^one));
Long val = count.get(key);
if(val==null) val = 0L;
count.put(key, val+1);
}
long num = n;
long ans = num*(num+1)/2;
for(Map.Entry<Long, Long> ent: count.entrySet()){
Long cnt = ent.getValue();
long num1 = cnt/2;
long num2 = (cnt+1)/2;
ans -= ( (num1*(num1-1))/2 );
ans -= ( (num2*(num2-1))/2 );
}
System.out.println(ans);
}
}
|
nlogn
|
1054_D. Changing Array
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigInteger;
public class stacks {
public static void main(String[] args) throws Exception {
FastIO sc = new FastIO(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
long remove = 0;
int[] heights = new int[n+1];
for(int i = 0; i < n; i++) {
heights[i] = sc.nextInt();
remove += heights[i];
}
Arrays.sort(heights);
//System.out.println(Arrays.toString(heights));
long keep = 0;
for(int i = n; i> 0; i--) {
if(heights[i-1] >= heights[i]) {
heights[i-1] = heights[i]-1;
}
keep += heights[i] - heights[i-1];
}
//System.out.println(Arrays.toString(heights));
pw.println(remove - keep);
pw.close();
}
static class FastIO {
//Is your Fast I/O being bad?
InputStream dis;
byte[] buffer = new byte[1 << 17];
int pointer = 0;
public FastIO(String fileName) throws Exception {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws Exception {
dis = is;
}
int nextInt() throws Exception {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
long nextLong() throws Exception {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
byte nextByte() throws Exception {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
String next() throws Exception {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
}
}
|
nlogn
|
1061_B. Views Matter
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class ProblemB {
InputReader in; PrintWriter out;
void solve() {
int n = in.nextInt();
int x = in.nextInt();
int y = in.nextInt();
int c = in.nextInt();
int cur = 1;
for (int k = 1; k <= c; k++) {
// out.println(k + " " + cur);
if (cur >= c) {
out.println(k - 1);
return;
}
//x + i; y + k - i;
int iLess = n - x;
int iMore = y + k - n;
if (iLess > k)
iLess = k;
if (iMore < 0)
iMore = 0;
// out.println("iless == " + iLess + " imore == " + iMore);
int add = iLess - iMore + 1;
if (add < 0)
add = 0;
// out.println("add == " + add);
cur += add;
//x + i; y - k + i;
iLess = n - x;
iMore = 1 + k - y;
if (iLess > k)
iLess = k;
if (iMore < 0)
iMore = 0;
// out.println("iless == " + iLess + " imore == " + iMore);
add = iLess - iMore + 1;
if (add < 0)
add = 0;
// out.println("add == " + add);
cur += add;
//x - i; y - k + i;
iLess = x - 1;
iMore = 1 + k - y;
if (iLess > k)
iLess = k;
if (iMore < 0)
iMore = 0;
// out.println("iless == " + iLess + " imore == " + iMore);
add = iLess - iMore + 1;
if (add < 0)
add = 0;
// out.println("add == " + add);
cur += add;
//x - i; y + k - i;
iLess = x - 1;
iMore = y + k - n;
if (iLess > k)
iLess = k;
if (iMore < 0)
iMore = 0;
// out.println("iless == " + iLess + " imore == " + iMore);
add = iLess - iMore + 1;
if (add < 0)
add = 0;
// out.println("add == " + add);
cur += add;
// out.println("cur == " + cur);
//delete double
if (x + k <= n)
cur--;
if (y - k >= 1)
cur--;
if (x - k >= 1)
cur--;
if (y + k <= n)
cur--;
}
// throw new RuntimeException();
}
ProblemB(){
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
try {
if (oj) {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
else {
Writer w = new FileWriter("output.txt");
in = new InputReader(new FileReader("input.txt"));
out = new PrintWriter(w);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
solve();
out.close();
}
public static void main(String[] args){
new ProblemB();
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public InputReader(FileReader fr) {
reader = new BufferedReader(fr);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
|
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.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);
TaskE2 solver = new TaskE2();
solver.solve(1, in, out);
out.close();
}
static class TaskE2 {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt(), m = in.nextInt();
int[][] a = new int[m][n];
int[] bestMask = new int[1 << n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[j][i] = in.nextInt();
}
}
int[] dp = new int[1 << n];
for (int i = 0; i < m; i++) {
int[] array = a[i];
for (int j = 0; j < n; j++) {
int val = array[j];
for (int mask = 0; mask < 1 << n; mask++) {
if ((mask & (1 << j)) == 0) {
dp[mask | (1 << j)] = Math.max(dp[mask | (1 << j)], dp[mask] + val);
}
}
}
for (int mask = 0; mask < 1 << n; mask++) {
int best = 0;
int cur = mask;
for (int j = 0; j < n; j++) {
best = Math.max(best, dp[cur]);
cur = (cur >> 1) | ((cur & 1) << (n - 1));
}
for (int j = 0; j < n; j++) {
dp[cur] = best;
cur = (cur >> 1) | ((cur & 1) << (n - 1));
}
}
}
out.println(dp[(1 << n) - 1]);
}
}
}
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();
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class D {
static Scanner in = new Scanner(new BufferedInputStream(System.in));
static PrintWriter out = new PrintWriter(System.out);
static double getTime(double v, double a, double l, double r) {
return (-v + Math.sqrt(v * v - 2 * a * (l - r))) / a;
}
static double getVelocity(double v, double t, double l, double r) {
return t == 0 ? v : (2 * (r - l)) / t - v;
}
public static void main(String[] args) throws IOException {
double a = in.nextDouble(), v = in.nextDouble(), l = in.nextDouble(),
d = in.nextDouble(), w = Math.min(v, in.nextDouble());
double x = v * v / (2 * a), y = d - (v * v - w * w) / (2 * a),
z = d + (v * v - w * w) / (2 * a);
//out.println(x + " " + y + " " + z);
double L, R, T = 0, V = 0, t;
//OX
L = 0;
R = x;
if (x > y && x < z) {
R = (x + y) / 2;
} else if (x > l) {
R = l;
}
t = getTime(V, a, L, R);
V = getVelocity(V, t, L, R);
//out.println("l: " + L + ", r: " + R + ", t: " + t + ", v: " + V);
T += t;
//XY
if (x < y) {
T += (y - x) / v;
}
//out.println("t: " + (T - t));
//YD
L = y;
R = d;
if (x > y && x < z) {
L = (x + y) / 2;
} else if (x >= z) {
L = R;
}
t = getTime(V, -a, L, R);
V = getVelocity(V, t, L, R);
T += t;
//out.println("l: " + L + ", r: " + R + ", t: " + t + ", v: " + V);
//DZ
L = d;
R = z;
if (x >= z) {
R = L;
} else if (z > l) {
R = l;
}
t = getTime(V, a, L, R);
V = getVelocity(V, t, L, R);
T += t;
//out.println("l: " + L + ", r: " + R + ", t: " + t + ", v: " + V);
//ZL
L = z;
R = l;
if (x > z) {
L = x;
}
if (L < R) {
T += (R - L) / v;
}
out.format(Locale.US, "%.12f%n", T);
out.close();
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt();
int[] a = in.readIntArray(n);
int swap = 0;
for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] > a[j]) swap ^= 1;
int m = in.readInt();
while (m-- > 0) {
int l = in.readInt();
int r = in.readInt();
int s = (r - l + 1);
s = s * (s - 1) / 2;
swap ^= s;
out.println((swap & 1) == 0 ? "even" : "odd");
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] readIntArray(int size) {
int[] ans = new int[size];
for (int i = 0; i < size; i++) ans[i] = readInt();
return ans;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.*;
import static java.lang.Math.*;
public class Main{
public static void main(String[] args){
new Main().run();
}
void run(){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int t = sc.nextInt() * 2;
H[] tbl = new H[n];
for(int i = 0; i < n; i++)tbl[i] = new H(sc.nextInt()*2, sc.nextInt()*2);
Arrays.sort(tbl);
TreeSet<Integer> cand = new TreeSet<Integer>();
//cand.add(tbl[0].x - tbl[0].len / 2);
for(int i = 0; i < n; i++){
int left = tbl[i].x - tbl[i].len / 2 - t / 2;
if(!cand.contains(left)){
if(i > 0 && tbl[i-1].x + tbl[i-1].len/2 > left - t/2){
}else{
cand.add(left);
}
}
int right = tbl[i].x + tbl[i].len / 2 + t/2;
if(!cand.contains(right)){
if(i < n-1 && tbl[i+1].x - tbl[i+1].len/2 < right + t/2){
}else{
cand.add(right);
}
}
}
System.out.println(cand.size());
}
class H implements Comparable<H>{
int x, len;
H(int a, int b){
x = a;
len = b;
}
public int compareTo(H h){
return this.x - h.x;
}
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
StreamTokenizer in;
PrintWriter out;
public static void main(String[] args) throws Exception {
new Main().run();
}
public void run() throws Exception {
Locale.setDefault(Locale.US);
in = new StreamTokenizer (new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
}
public int nextInt() throws Exception {
in.nextToken();
return (int) in.nval;
}
public String next() throws Exception {
in.nextToken();
return in.sval;
}
class Senator {
int b;
int l;
public Senator (int b,int l) {
this.b=b;
this.l=l;
}
}
int n,k,A;
double max=Integer.MIN_VALUE;
Senator[] a;
public void check (int step,int candy) {
if (step==n)
{
double tmp = 0.0;
for (int mask=0; mask<(1<<n);mask++)
{
double P = 1.0;
int q = 0;
for (int i=0; i<n;i++)
{
if ((mask>>i&1)!=0)
{
P*=a[i].l/100.;
} else
{
P*=1.0-a[i].l/100.;
q+=a[i].b;
}
}
if (Integer.bitCount(mask)>n/2)
{
tmp+=P;
} else
{
tmp+=P*A/(A+q);
}
max=Math.max(tmp,max);
}
} else
{
for (int i=0;i<=Math.min(k,(100-a[step].l)/10);i++)
{
a[step].l+=10*i;
check(step+1,k-i);
a[step].l-=10*i;
}
}
}
public void solve() throws Exception {
n=nextInt();
k=nextInt();
A=nextInt();
a = new Senator [n];
for (int i=0; i<n;i++) {
Senator q = new Senator(nextInt(),nextInt());
a[i]=q;
}
double ans=0;
for(int mask=0;mask<1<<(n+k-1);mask++)
{
if(Integer.bitCount(mask)!=k) continue;
int[] b = new int[n];
int x = mask;
for(int i=0;i<n;i++)
{
b[i] = a[i].l;
while(x%2==1)
{
b[i]+=10;
x/=2;
}
b[i]=Math.min(b[i],100);
x/=2;
}
double tmp=0;
for(int w=0; w<(1<<n);w++)
{
double p = 1.;
double B = 0;
for(int i = 0; i < n; i++)
if((w >> i & 1) != 0) p *= b[i] / 100.;
else
{
p *= 1- b[i]/100.;
B += a[i].b;
}
if(Integer.bitCount(w)> n/2) tmp += p;
else tmp += p * (A / (A + B));
}
ans = Math.max(ans, tmp);
}
out.printf("%.10f\n", ans);
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Equator {
public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static StringTokenizer st;
public static void main(String[] args) throws IOException {
int n = nextInt();
int[] a = intArray(n);
long s = 0;
for (int x : a)
s += x;
long m = 0;
for (int i = 0; i < n; i++) {
m += a[i];
if (m*2 >= s) {
System.out.println(i+1);
return;
}
}
}
public static String nextLine() throws IOException {
return in.readLine();
}
public static String nextString() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
public static long nextLong() throws IOException {
return Long.parseLong(nextString());
}
public static int[] intArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public static int[][] intArray(int n, int m) throws IOException {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = nextInt();
return a;
}
public static long[] longArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
|
linear
|
962_A. Equator
|
CODEFORCES
|
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintStream;
import java.util.Scanner;
public class P35C {
int n, m;
int [][]fire;
public P35C() throws FileNotFoundException {
Scanner in = new Scanner(new FileReader("input.txt"));
n = in.nextInt();
m = in.nextInt();
int k = in.nextInt();
fire = new int[k][2];
for (int i = 0; i < k; i++){
fire[i][0] = in.nextInt();
fire[i][1] = in.nextInt();
}
in.close();
int []last = new int[2];
int lastBurn = -1;
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
int burn = Integer.MAX_VALUE;
for (int l = 0; l < k; l++){
int burnAux = dist(i, j, fire[l][0], fire[l][1]);
burn = Math.min(burn, burnAux);
}
if(burn >= lastBurn){
lastBurn = burn;
last[0] = i;
last[1] = j;
}
}
}
PrintStream out = new java.io.PrintStream( "output.txt" );
out.print(last[0] + " " + last[1]);
out.close();
}
int dist(int x1, int y1, int x2, int y2){
return Math.abs(x2 - x1) + Math.abs(y2 - y1);
}
public static void main (String []args) throws FileNotFoundException{
new P35C();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A
{
String line;
StringTokenizer inputParser;
BufferedReader is;
FileInputStream fstream;
DataInputStream in;
String FInput="";
void openInput(String file)
{
if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
else
{
try{
fstream = new FileInputStream(file);
in = new DataInputStream(fstream);
is = new BufferedReader(new InputStreamReader(in));
}catch(Exception e)
{
System.err.println(e);
}
}
}
void readNextLine()
{
try {
line = is.readLine();
inputParser = new StringTokenizer(line, " ");
//System.err.println("Input: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
catch (NullPointerException e)
{
line=null;
}
}
int NextInt()
{
String n = inputParser.nextToken();
int val = Integer.parseInt(n);
//System.out.println("I read this number: " + val);
return val;
}
long NextLong()
{
String n = inputParser.nextToken();
long val = Long.parseLong(n);
//System.out.println("I read this number: " + val);
return val;
}
String NextString()
{
String n = inputParser.nextToken();
return n;
}
void closeInput()
{
try {
is.close();
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
public static void main(String [] argv)
{
String filePath=null;
if(argv.length>0)filePath=argv[0];
new A(filePath);
}
public void readFInput()
{
for(;;)
{
try
{
readNextLine();
FInput+=line+" ";
}
catch(Exception e)
{
break;
}
}
inputParser = new StringTokenizer(FInput, " ");
}
public A(String inputFile)
{
openInput(inputFile);
readNextLine();
int n=NextInt();
int k=NextInt()-1;
int ret=0;
Team [] t = new Team[n];
for(int i=0; i<n; i++)
{
readNextLine();
t[i]=new Team(NextInt(), NextInt());
}
Arrays.sort(t);
int ti=t[k].t, p=t[k].p;
for(int i=0; i<n; i++)
if(t[i].t==ti&&t[i].p==p)ret++;
System.out.print(ret);
closeInput();
}
private class Team implements Comparable<Team>
{
int p,t;
Team(int p, int t)
{
this.p=p;
this.t=t;
}
public int compareTo(Team d)
{
return 10000*(d.p-p)+t-d.t;
}
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.