src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.awt.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
import java.io.*;
public class Main3 {
static PrintWriter pr;
static Scanner scan;
static BufferedReader br;
static StringTokenizer st;
public static void main(String args[]) throws Exception {
pr = new PrintWriter(System.out);
scan = new Scanner(System.in);
br = new BufferedReader(new InputStreamReader(System.in));
int n = inputInt();
//char[] c = br.readLine().toCharArray();
int[] a = new int[n];
int[] b = new int[n];
st = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(st.nextToken());
//b[i]=Integer.parseInt(st.nextToken());
}
Arrays.sort(a);
int ans=0;
for(int i=0;i<n;i++){
if(b[i]!=1){
ans++;
for(int j=i;j<n;j++){
if(a[j]%a[i]==0){
b[j]=1;
}
}
}
}
System.out.println(ans);
}
public static int inputInt() throws IOException{
return Integer.parseInt(br.readLine());
}
public static long inputLong() throws IOException{
return Long.parseLong(br.readLine());
}
public static String inputString() throws IOException{
return br.readLine();
}
public static int[] intArray(int n) throws IOException{
int a[] = new int[n];
st = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++){
a[i] = Integer.parseInt(st.nextToken());
}
return a;
}
public static long[] longArray(int n) throws IOException{
long a[] = new long[n];
st = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++){
a[i] = Long.parseLong(st.nextToken());
}
return a;
}
public static String[] stringArray(int n) throws IOException{
String a[] = new String[n];
st = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++){
a[i] = st.nextToken();
}
return a;
}
public static long gcd(long a,long b){
if(b==0){
return a;
}
else{
return gcd(b,a%b);
}
}
public long max(long a,long b,long c){
return Math.max(a,Math.max(b,c));
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rishabhdeep Singh
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] cnt = new int[10];
Arrays.fill(cnt, 0);
List<String> a = new ArrayList<>();
for (int i = 0; i < n; i++) {
a.add(in.readLine());
}
List<String> b = new ArrayList<>();
for (int i = 0; i < n; i++) {
String temp = in.readLine();
if (a.contains(temp)) {
a.remove(temp);
} else
b.add(temp);
}
int[] cnta = new int[10];
for (int i = 0; i < a.size(); i++) {
cnta[a.get(i).length()]++;
}
int[] cntb = new int[10];
Arrays.fill(cnta, 0);
Arrays.fill(cntb, 0);
for (int i = 0; i < b.size(); i++) {
cntb[a.get(i).length()]++;
}
int ans = 0;
for (int i = 0; i < 10; i++) {
ans += Math.abs(cnta[i] - cntb[i]);
}
out.println(ans);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.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.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class d {
public static void main(String args[]) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
//BEGIN HERE
int n = in.nextInt();
int perm[] = new int[n];
for(int i = 0; i < n; i++) {
perm[i] = in.nextInt();
}
int q = in.nextInt();
int inv[] = new int[n];
inv[0] = 0;
for(int i = 1; i < n; i++) {
inv[i] = inv[i-1];
for(int j = i - 1; j >= 0; j--) {
if(perm[i] < perm[j]) inv[i]++;
}
}
boolean parity = inv[n-1] % 2 == 0;
for(int i = 0; i < q; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() -1;
if(l == r) {
System.out.println(parity?"even":"odd");
continue;
}
int s = r - l + 1;
s = s * (s-1)/ 2;
if(s % 2 != 0) {
parity = !parity;
}
System.out.println(parity?"even":"odd");
}
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = null;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
if (st == null) {
st = new StringTokenizer(br.readLine());
}
String line = st.nextToken("\n");
st = null;
return line;
}
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 static class combinatorics {
static long modInv(long a, long b) {
return 1 < a ? b - modInv(b % a, a) * b / a : 1;
}
static long factorial[], mod;
combinatorics(int n, long MOD) {
mod = MOD;
factorial = new long[n + 1];
factorial[0] = 1;
for (int i = 1; i <= n; i++) {
factorial[i] = i * factorial[i - 1];
factorial[i] %= mod;
}
}
static long nCr(int n, int r) {
if (r > n)
return 0;
return (factorial[n] * modInv((factorial[n - r] * factorial[r]) % mod, mod)) % mod;
}
}
public static class DisjointSet {
int p[], r[], s[];
int numDisjoint;
DisjointSet(int N) {
numDisjoint = N;
r = new int[N];
s = new int[N];
p = new int[N];
for (int i = 0; i < N; i++)
p[i] = i;
}
int findSet(int i) {
return (p[i] == i) ? i : (p[i] = findSet(p[i]));
}
boolean isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
void unionSet(int i, int j) {
if (!isSameSet(i, j)) // if from different set
{
numDisjoint--;
int x = findSet(i), y = findSet(j);
if (r[x] > r[y]) {
p[y] = x; // rank keeps the tree short
s[x] += s[y];
} else {
p[x] = y;
if (r[x] == r[y])
r[y]++;
s[y] += s[x];
}
}
}
int sizeOfSet(int i) {
return s[findSet(i)];
}
};
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Map.Entry;
import static java.lang.Math.*;
public class G extends PrintWriter {
void run() {
long mod = 1_000_000_000 + 7;
int n = nextInt();
int m = nextInt();
int[] t = new int[n];
int[] g = new int[n];
for (int i = 0; i < n; i++) {
t[i] = nextInt();
g[i] = nextInt() - 1;
}
int k = 1 << n;
long[][] dp = new long[k][n];
for (int i = 0; i < n; i++) {
dp[1 << i][i] = 1;
}
for (int mask = 0; mask < k; mask++) {
if (Integer.bitCount(mask) <= 1) {
continue;
}
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0) {
for (int j = 0; j < n; j++) {
if ((mask & (1 << j)) == 0 || g[i] == g[j]) {
continue;
}
dp[mask][i] = (dp[mask][i] + dp[mask ^ (1 << i)][j]) % mod;
}
}
}
}
long ans = 0;
for (int mask = 0; mask < k; mask++) {
int sum = 0;
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0) {
sum += t[i];
}
}
if (sum == m) {
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0) {
ans = (ans + dp[mask][i]) % mod;
}
}
}
}
println(ans);
}
boolean skip() {
while (hasNext()) {
next();
}
return true;
}
int[][] nextMatrix(int n, int m) {
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
matrix[i][j] = nextInt();
return matrix;
}
String next() {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String line = nextLine();
if (line == null) {
return false;
}
tokenizer = new StringTokenizer(line);
}
return true;
}
int[] nextArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++) {
array[i] = nextLong();
}
return array;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
return reader.readLine();
} catch (IOException err) {
return null;
}
}
public G(OutputStream outputStream) {
super(outputStream);
}
static BufferedReader reader;
static StringTokenizer tokenizer = new StringTokenizer("");
static Random rnd = new Random();
static boolean OJ;
public static void main(String[] args) throws IOException {
OJ = System.getProperty("ONLINE_JUDGE") != null;
G solution = new G(System.out);
if (OJ) {
reader = new BufferedReader(new InputStreamReader(System.in));
solution.run();
} else {
reader = new BufferedReader(new FileReader(new File(G.class.getName() + ".txt")));
long timeout = System.currentTimeMillis();
while (solution.hasNext()) {
solution.run();
solution.println();
solution.println("----------------------------------");
}
solution.println("time: " + (System.currentTimeMillis() - timeout));
}
solution.close();
reader.close();
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.io.*;
public class coins
{
public static void main(String args[])throws IOException
{
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(read);
int i,k,n,v;
String a;
a=in.readLine();
for(i=0;i<a.length();i++)
{
if(a.charAt(i)==' ')
break;
}
n=Integer.parseInt(a.substring(0,i));
v=Integer.parseInt(a.substring(i+1));
k=v%n;
v=v/n;
if(k>0)
v++;
System.out.println(v);
}
}
|
constant
|
1061_A. Coins
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class CottageVillage {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
int counter = 0;
int numbCottages = scan.nextInt();
int t = scan.nextInt();
House[] cottages = new House[numbCottages];
for(int i =0; i<numbCottages; i++){
int centre = scan.nextInt();
int length = scan.nextInt();
double beginning = centre - ((double)length)/2;
double end = centre + ((double)length)/2;
cottages[i]= new House(beginning, end);
}
Arrays.sort(cottages);
//check righthand side of first cottage
/*
if(cottages[0].end + t < cottages[1].beginning)
counter++;
//check lefthand side of last cottage
if(cottages[numbCottages-1].beginning -t > cottages[numbCottages-2].end)
counter++;
*/
for(int i =0; i<numbCottages-1; i++){
if(cottages[i].end + t <= cottages[i+1].beginning){
counter++;
// System.out.println(counter + "left hand");
}
if (cottages[i+1].beginning - t >= cottages[i].end){
counter++;
// System.out.println(counter + "right hand");
}
if (Math.abs((cottages[i].end + t - cottages[i+1].beginning)) < 1e-8){
counter--;
}
}
System.out.println(counter+2);
}
}
static class House implements Comparable<House>{
double beginning;
double end;
House(double _beginning, double _end){
beginning = _beginning;
end = _end;
}
@Override
public int compareTo(House house) {
// if(this.beginning<house.beginning){
// return -1;
// }
// else if(this.beginning==house.beginning){
// return 0;
// }
// else{
// return 1;
// }
return Double.valueOf(beginning).compareTo(house.beginning);
}
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] nums = new int[n];
for(int i = 0; i < n; i++){
nums[i] = scan.nextInt();
}
Arrays.sort(nums);
boolean[] div = new boolean[n];
int count = 0;
for(int i = 0; i < n; i++) {
if (!div[i]) {
count++;
div[i] = true;
for(int j = i+1; j < n; j++) {
if (nums[j] % nums[i] == 0) {
div[j] = true;
}
}
}
}
System.out.println(count);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution {
static MyScanner sc;
private static PrintWriter out;
static long M2 = 1_000_000_000L + 7;
private static HashMap<Long, Long>[] mods;
public static void main(String[] s) throws Exception {
StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append("7 3\n" +
// "1 5 2 6 3 7 4\n" +
// "2 5 3\n" +
// "4 4 1\n" +
// "1 7 3");
//
// Random r = new Random(5);
// stringBuilder.append("100000 5000 ");
// for (int i = 0; i < 100000; i++) {
// stringBuilder.append(" " + (r.nextInt(2000000000) - 1000000000) + " ");
//
// }
// for (int k = 0; k < 5000; k++) {
// stringBuilder.append(" 1 100000 777 ");
// }
if (stringBuilder.length() == 0) {
sc = new MyScanner(System.in);
} else {
sc = new MyScanner(new BufferedReader(new StringReader(stringBuilder.toString())));
}
out = new PrintWriter(new OutputStreamWriter(System.out));
initData();
solve();
out.flush();
}
private static void solve() throws IOException {
int n = sc.nextInt();
boolean[] k = new boolean[n];
for (int r = 0; r < n; r++) {
k[r] = sc.next().charAt(0) == 'f';
}
if (k[n - 1]) {
out.println(0);
return;
}
long[][] res = new long[n + 1][n + 1];
res[0][0] = 1;
for (int t = 0; t < n; t++) {
boolean pl = t != 0 && k[t - 1];
if (pl) {
System.arraycopy(res[t], 0, res[t + 1], 1, n);
} else {
long last = 0;
for (int f = n; f >= 0; f--) {
last += res[t][f];
last %= M2;
res[t + 1][f] = last;
}
}
}
long pp = 0;
for (long kk : res[n]) {
pp += kk;
pp %= M2;
}
out.println(pp);
}
private static void initData() {
}
static char[][] data;
static String cmd;
private static final class STree {
private final Comparator<Integer> comparator;
int[] val1;
int[] from1;
int[] to1;
int[] max1;
public STree(int c, Comparator<Integer> comparator) {
this.comparator = comparator;
int size = Integer.highestOneBit(c);
if (size != c) {
size <<= 1;
}
int rs = size << 1;
val1 = new int[rs];
from1 = new int[rs];
max1 = new int[rs];
to1 = new int[rs];
Arrays.fill(from1, Integer.MAX_VALUE);
for (int r = rs - 1; r > 1; r--) {
if (r >= size) {
from1[r] = r - size;
to1[r] = r - size;
}
from1[r / 2] = Math.min(from1[r / 2], from1[r]);
to1[r / 2] = Math.max(to1[r / 2], to1[r]);
}
}
public int max(int from, int to) {
return max(1, from, to);
}
private int max(int cur, int from, int to) {
if (cur >= val1.length) return -1;
if (from <= from1[cur] && to1[cur] <= to) {
return max1[cur];
}
if (from1[cur] > to || from > to1[cur]) {
return -1;
}
cur <<= 1;
return max0(max(cur, from, to), max(cur + 1, from, to));
}
public void put(int x, int val) {
x += val1.length >> 1;
val1[x] = val;
max1[x] = val;
addToParent(x);
}
private void addToParent(int cur) {
while (cur > 1) {
cur >>= 1;
max1[cur] = max0(max1[cur << 1], max1[1 + (cur << 1)]);
}
}
private int max0(int i, int i1) {
if (i == -1) return i1;
if (i1 == -1) return i;
return comparator.compare(i, i1) > 0 ? i1 : i;
}
}
private static boolean isset(long i, int k) {
return (i & (1 << k)) > 0;
}
private static void solveT() throws IOException {
int t = sc.nextInt();
while (t-- > 0) {
solve();
}
}
private static long gcd(long l, long l1) {
if (l > l1) return gcd(l1, l);
if (l == 0) return l1;
return gcd(l1 % l, l);
}
private static long pow(long a, long b, long m) {
if (b == 0) return 1;
if (b == 1) return a;
long pp = pow(a, b / 2, m);
pp *= pp;
pp %= m;
return (pp * (b % 2 == 0 ? 1 : a)) % m;
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
MyScanner(BufferedReader br) {
this.br = br;
}
public MyScanner(InputStream in) {
this(new BufferedReader(new InputStreamReader(in)));
}
void findToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String next() {
findToken();
return st.nextToken();
}
Integer[] nab(int n) {
Integer[] k = new Integer[n];
for (int i = 0; i < n; i++) {
k[i] = sc.fi();
}
return k;
}
int[] na(int n) {
int[] k = new int[n];
for (int i = 0; i < n; i++) {
k[i] = sc.fi();
}
return k;
}
long[] nl(int n) {
long[] k = new long[n];
for (int i = 0; i < n; i++) {
k[i] = sc.nextLong();
}
return k;
}
int nextInt() {
return Integer.parseInt(next());
}
int fi() {
String t = next();
int cur = 0;
boolean n = t.charAt(0) == '-';
for (int a = n ? 1 : 0; a < t.length(); a++) {
cur = cur * 10 + t.charAt(a) - '0';
}
return n ? -cur : cur;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
public class B {
final int MOD = (int)1e9 + 7;
final double eps = 1e-12;
final int INF = (int)1e9;
public B () {
long N = sc.nextInt();
long X = sc.nextInt() - 1;
long Y = sc.nextInt() - 1;
long C = sc.nextInt();
long [] A1 = new long [] { X, Y };
long [] A2 = new long [] { X, Y };
long [] B1 = new long [] { X, Y };
long [] B2 = new long [] { X, Y };
long [] C1 = new long [] { X, Y };
long [] C2 = new long [] { X, Y };
long [] D1 = new long [] { X, Y };
long [] D2 = new long [] { X, Y };
long cnt = 1, T = 0;
while (cnt < C) {
if (A1[0] > 0) --A1[0]; else --A1[1];
if (A2[0] > 0) --A2[0]; else ++A2[1];
if (B1[1] > 0) --B1[1]; else --B1[0];
if (B2[1] > 0) --B2[1]; else ++B2[0];
if (C1[0] < N-1) ++C1[0]; else --C1[1];
if (C2[0] < N-1) ++C2[0]; else ++C2[1];
if (D1[1] < N-1) ++D1[1]; else --D1[0];
if (D2[1] < N-1) ++D2[1]; else ++D2[0];
long [] Z = { B1[0] - A1[0],
C1[0] - B2[0],
C2[0] - D2[0],
D1[0] - A2[0] };
for (long z : Z)
if (z >= 0)
cnt += (z+1);
if (Arrays.equals(A1, A2)) --cnt;
if (Arrays.equals(B1, B2)) --cnt;
if (Arrays.equals(C1, C2)) --cnt;
if (Arrays.equals(D1, D2)) --cnt;
++T;
}
exit(T);
}
////////////////////////////////////////////////////////////////////////////////////
static MyScanner sc;
static class MyScanner {
public String next() {
newLine();
return line[index++];
}
public char nextChar() {
return next().charAt(0);
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
line = null;
return readLine();
}
public String [] nextStrings() {
line = null;
return readLine().split(" ");
}
public char [] nextChars() {
return next().toCharArray();
}
public Integer [] nextInts() {
String [] L = nextStrings();
Integer [] res = new Integer [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Integer.parseInt(L[i]);
return res;
}
public Long [] nextLongs() {
String [] L = nextStrings();
Long [] res = new Long [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Long.parseLong(L[i]);
return res;
}
public Double [] nextDoubles() {
String [] L = nextStrings();
Double [] res = new Double [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Double.parseDouble(L[i]);
return res;
}
//////////////////////////////////////////////
private boolean eol() {
return index == line.length;
}
private String readLine() {
try {
return r.readLine();
} catch (Exception e) {
throw new Error(e);
}
}
private final BufferedReader r;
MyScanner () {
this(new BufferedReader(new InputStreamReader(System.in)));
}
MyScanner(BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine() {
if (line == null || eol()) {
line = readLine().split(" ");
index = 0;
}
}
}
static void print (Object o, Object... a) {
pw.println(build(o, a));
}
static void exit (Object o, Object... a) {
print(o, a);
exit();
}
static void exit () {
pw.close();
System.out.flush();
System.err.println("------------------");
System.err.println("Time: " + ((millis() - t) / 1000.0));
System.exit(0);
}
void NO() {
throw new Error("NO!");
}
////////////////////////////////////////////////////////////////////////////////////
static String build(Object... a) {
StringBuilder b = new StringBuilder();
for (Object o : a)
append(b, o);
return b.toString().trim();
}
static void append(StringBuilder b, Object o) {
if (o.getClass().isArray()) {
int L = Array.getLength(o);
for (int i = 0; i < L; ++i)
append(b, Array.get(o, i));
} else if (o instanceof Iterable<?>) {
for (Object p : (Iterable<?>)o)
append(b, p);
} else
b.append(" ").append(o);
}
////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
sc = new MyScanner ();
new B();
exit();
}
static void start() {
t = millis();
}
static PrintWriter pw = new PrintWriter(System.out);
static long t;
static long millis() {
return System.currentTimeMillis();
}
}
|
logn
|
256_B. Mr. Bender and Square
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = scn.nextInt();
scn.close();
Arrays.sort(a);
ArrayList<Integer> cyka = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[j] % a[i] == 0) {
boolean add = true;
for (int k : cyka) {
if (a[i] % k == 0) {
add = false;
break;
}
}
if (add) {
cyka.add(a[i]);
}
}
}
}
System.out.println(cyka.size());
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class B {
static long n, k;
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = in.nextLong();
k = in.nextLong();
long ans = n - TernarySearch(0, n);
pw.println(ans);
pw.close();
}
static long cal(long m) {
long x = (m * (m + 1)) / 2;
long y = x - (n - m);
return abs(k - y);
}
static long TernarySearch(long l, long r) {
long m1, m2;
while (r - l > 5) {
m1 = (2 * l + r) / 3;
m2 = (l + 2 * r) / 3;
if (cal(m1) > cal(m2)) l = m1;
else r = m2;
}
long min = cal(l), i = l;
for (; l <= r; l++) {
long t = cal(l);
if (t < min) {
min = t;
i = l;
}
}
return i;
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class MicroWorld {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] temp = new int[1000001];
StringTokenizer st1 = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++){
temp[Integer.parseInt(st1.nextToken())]++;
}
int b = k + 1;
for (int i = 1000000; i > 0; i--){
if (temp[i] > 0){
if (b <= k){
n -= temp[i];
}
b = 1;
}else{
b++;
}
}
System.out.println(n);
}
}
|
nlogn
|
990_B. Micro-World
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* 4 4
* 1 5 3 4
* 1 2
* 1 3
* 2 3
* 3 3
*
*
* @author pttrung
*/
public class A {
public static long Mod = (long) (1e9 + 7);
public static long[][] dp;
public static void main(String[] args) throws FileNotFoundException {
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] data = new int[n];
int[]u = new int[n];
int[]s = new int[n];
HashMap<Integer, Integer> map = new HashMap();
for(int i = 0; i < n; i++){
u[i] = i;
data[i] = in.nextInt();
map.put(data[i], i);
}
boolean ok = true;
boolean[]check = new boolean[n];
for(int i = 0; i < n; i++){
if(map.containsKey(a - data[i])){
u[find(i, u)]= u[find(map.get(a- data[i]), u)];
s[i] |= 1;
}
if(map.containsKey(b - data[i])){
u[find(i, u)]= u[find(map.get(b- data[i]), u)];
s[i] |= 2;
}
}
int[]g = new int[n];
Arrays.fill(g,3);
for(int i = 0; i< n; i++){
if(s[i] == 0){
ok = false;
break;
}
g[find(i, u)] &= s[i];
if(g[find(i,u)] == 0){
ok = false;
break;
}
}
//System.out.println(Arrays.toString(g));
if(ok){
out.println("YES");
for(int i = 0; i < n; i++){
if((g[find(i,u)] & 1) == 0){
out.print(1 + " ");
}else{
out.print(0 + " ");
}
}
}else{
out.println("NO");
}
out.close();
}
static int find(int index, int[]u){
if(index != u[index]){
return u[index] = find(u[index], u);
}
return index;
}
public static long pow(int a, int b, long mod) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long v = pow(a, b / 2, mod);
if (b % 2 == 0) {
return (v * v) % mod;
} else {
return (((v * v) % mod) * a) % mod;
}
}
public static int[][] powSquareMatrix(int[][] A, long p) {
int[][] unit = new int[A.length][A.length];
for (int i = 0; i < unit.length; i++) {
unit[i][i] = 1;
}
if (p == 0) {
return unit;
}
int[][] val = powSquareMatrix(A, p / 2);
if (p % 2 == 0) {
return mulMatrix(val, val);
} else {
return mulMatrix(A, mulMatrix(val, val));
}
}
public static int[][] mulMatrix(int[][] A, int[][] B) {
int[][] result = new int[A.length][B[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
long temp = 0;
for (int k = 0; k < A[0].length; k++) {
temp += ((long) A[i][k] * B[k][j] % Mod);
temp %= Mod;
}
temp %= Mod;
result[i][j] = (int) temp;
}
}
return result;
}
public static 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;
}
static class FT {
int[] data;
FT(int n) {
data = new int[n];
}
void update(int index, int val) {
// System.out.println("UPDATE INDEX " + index);
while (index < data.length) {
data[index] += val;
index += index & (-index);
// System.out.println("NEXT " +index);
}
}
int get(int index) {
// System.out.println("GET INDEX " + index);
int result = 0;
while (index > 0) {
result += data[index];
index -= index & (-index);
// System.out.println("BACK " + index);
}
return result;
}
}
static long gcd(long a, long b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
static long pow(long a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val % Mod;
} else {
return (val * val % Mod) * a % Mod;
}
}
// static Point intersect(Point a, Point b, Point c) {
// double D = cross(a, b);
// if (D != 0) {
// return new Point(cross(c, b) / D, cross(a, c) / D);
// }
// return null;
// }
//
// static Point convert(Point a, double angle) {
// double x = a.x * cos(angle) - a.y * sin(angle);
// double y = a.x * sin(angle) + a.y * cos(angle);
// return new Point(x, y);
// }
static Point minus(Point a, Point b) {
return new Point(a.x - b.x, a.y - b.y);
}
//
// static Point add(Point a, Point b) {
// return new Point(a.x + b.x, a.y + b.y);
// }
//
/**
* Cross product ab*ac
*
* @param a
* @param b
* @param c
* @return
*/
static double cross(Point a, Point b, Point c) {
Point ab = new Point(b.x - a.x, b.y - a.y);
Point ac = new Point(c.x - a.x, c.y - a.y);
return cross(ab, ac);
}
static double cross(Point a, Point b) {
return a.x * b.y - a.y * b.x;
}
/**
* Dot product ab*ac;
*
* @param a
* @param b
* @param c
* @return
*/
static long dot(Point a, Point b, Point c) {
Point ab = new Point(b.x - a.x, b.y - a.y);
Point ac = new Point(c.x - a.x, c.y - a.y);
return dot(ab, ac);
}
static long dot(Point a, Point b) {
long total = a.x * b.x;
total += a.y * b.y;
return total;
}
static double dist(Point a, Point b) {
long total = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
return Math.sqrt(total);
}
static long norm(Point a) {
long result = a.x * a.x;
result += a.y * a.y;
return result;
}
static double dist(Point a, Point b, Point x, boolean isSegment) {
double dist = cross(a, b, x) / dist(a, b);
// System.out.println("DIST " + dist);
if (isSegment) {
Point ab = new Point(b.x - a.x, b.y - a.y);
long dot1 = dot(a, b, x);
long norm = norm(ab);
double u = (double) dot1 / norm;
if (u < 0) {
return dist(a, x);
}
if (u > 1) {
return dist(b, x);
}
}
return Math.abs(dist);
}
static long squareDist(Point a, Point b) {
long x = a.x - b.x;
long y = a.y - b.y;
return x * x + y * y;
}
static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point{" + "x=" + x + ", y=" + y + '}';
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
//System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new FileReader(new File("A-large (2).in")));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class CF_1029E_Tree_with_Small_Distances {
static ArrayList<Integer> adj[];
static int dist[];
static boolean visitParent[];
static int ans=0;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
adj=new ArrayList[n+1];
dist = new int[n+1];
visitParent = new boolean[n+1];
for(int i=0;i<=n;i++) adj[i]=new ArrayList<Integer>();
int max=0;
//first contribution
for(int i=1;i<n;i++){
int u = sc.nextInt(),v=sc.nextInt();
adj[u].add(v);
adj[v].add(u);
}
dist[1]=0;
dfs(1,1);
System.out.println(ans);
}
private static void dfs(int i , int j) {
// TODO Auto-generated method stub
boolean f = false;
for(int k=0;k<adj[i].size();k++){
int x = adj[i].get(k);
if(x!=j){
dist[x]=dist[i]+1;
dfs(x,i);
if(visitParent[x])
f=true;
}
}
//System.out.println(Arrays.toString(dist));
if(dist[i]>2&&!visitParent[j]&&!f&&!visitParent[i]){
visitParent[j]=true;
ans++;
for(int v=0;v<adj[i].size();v++){
}
}
}
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 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 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 boolean ready() throws IOException {return br.ready(); }
}
}
|
linear
|
1029_E. Tree with Small Distances
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Solution {
private static int[] dx = {
-1, -1, -1,
0, 0,
1, 1, 1};
private static int[] dy = {
-1, 0, 1,
-1, 1,
-1, 0, 1};
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int r = in.nextInt();
int c = in.nextInt();
boolean[][] m = new boolean[r + 1][c + 1];
boolean[][] inp = new boolean[r + 1][c + 1];
for (int i = 0; i < r; i++) {
String s = in.next();
//System.out.println(m[i]);
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == '#') {
m[i][j] = true;
inp[i][j] = true;
}
}
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (canPress(i, j, r, c, inp)) {
// make press
for (int k = 0; k < 8; k++) {
int xi = i + dx[k];
int yi = j + dy[k];
m[xi][yi] = false;
}
}
}
}
boolean isLeftAny = false;
for (int i = 0; i < r && !isLeftAny; i++) {
for (int j = 0; j < c && !isLeftAny; j++) {
if (m[i][j]) {
isLeftAny = true;
break;
}
}
}
if(isLeftAny){
System.out.println("NO");
}else{
System.out.println("YES");
}
}
private static boolean canPress(int x, int y, int r, int c, boolean[][] inp) {
for (int i = 0; i < 8; i++) {
int xi = x + dx[i];
int yi = y + dy[i];
if (xi < 0 || yi < 0) {
return false;
}
if (xi >= r || yi >= c) {
return false;
}
if(!inp[xi][yi]){
return false;
}
}
return true;
}
}
|
quadratic
|
1059_B. Forgery
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Scanner;
public class A {
public static void main (String[] args){
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
out.printf(Locale.US, "%d", n/2*3);
out.close();
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
new A().run();
}
private void run() {
Scanner sc =new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
sc.close();
boolean[] isp = new boolean[n + 1];
Arrays.fill(isp, true);
isp[1] = false;
int[] primes = new int[n];
int pc = 0;
for (int i = 2; i <= n; i++) {
if (isp[i]) {
primes[pc++] = i;
for (int j = i * i; j <= n; j+= i) {
isp[j] = false;
}
}
}
int res = 0;
for (int i = 0; i < pc; i++) {
for (int j = 1; j < i; j++)
if (primes[i] == primes[j] + primes[j - 1] + 1)
res++;
}
System.out.println(res >= k ? "YES" : "NO");
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.List;
import java.util.*;
public class realfast implements Runnable
{
private static final int INF = (int) 1e9;
long in= 1000000007;
long fac[]= new long[1000001];
long inv[]=new long[1000001];
public void solve() throws IOException
{
//int t = readInt();
int n = readInt();
long m = readInt();
long method[][]=new long [n+1][n+1];
for(int i=0;i<=n;i++)
{
method[0][i]=1;
method[i][0]=1;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
for(int k=i;k>=0;k--)
{
method[i][j]= (method[i][j]%m+method[k][j-1]%m)%m;
}
}
}
// index , total , cont
//long dp[][][]=new long[n+2][n+2][n+2];
long sum[][]=new long[n+2][n+2];
sum[0][0]=1;
// dp[0][0][0]=1;
long len[][]=new long[n+1][n+1];
for(int i=0;i<=n;i++)
{
len[i][0]=1;
len[0][i]=1;
}
for(int i=2;i<=n;i++)
{
for(int j=1;j<i;j++)
{
len[j][i-j]= (len[j-1][i-j]%m+len[j][i-j-1]%m)%m;
}
}
long gal[]=new long[2*n+1];
for(int i=0;i<=n;i++)
{
for(int j=0;j<=n;j++)
{
gal[i+j]= (gal[i+j]+ len[i][j])%m;
}
}
for(int i=1;i<=n;i++)
{
if(i==n-1)
continue;
for(int j=1;j<=i;j++)
{
for(int k=1;k<=j;k++)
{
long val =sum[i-k][j-k];
val = (val*method[j-k][k])%m;
val =(val*gal[k-1])%m;
sum[i+1][j]= (sum[i+1][j]+val)%m;
}
}
}
long ans =0;
for(int i=1;i<=n;i++)
{
ans = (ans + sum[n+1][i])%m;
}
out.println(ans);
}
public int value (int seg[], int left , int right ,int index, int l, int r)
{
if(left>right)
{
return -100000000;
}
if(right<l||left>r)
return -100000000;
if(left>=l&&right<=r)
return seg[index];
int mid = left+(right-left)/2;
int val = value(seg,left,mid,2*index+1,l,r);
int val2 = value(seg,mid+1,right,2*index+2,l,r);
return Math.max(val,val2);
}
public int gcd(int a , int b )
{
if(a<b)
{
int t =a;
a=b;
b=t;
}
if(a%b==0)
return b ;
return gcd(b,a%b);
}
public long pow(long n , long p,long m)
{
if(p==0)
return 1;
long val = pow(n,p/2,m);;
val= (val*val)%m;
if(p%2==0)
return val;
else
return (val*n)%m;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
new Thread(null, new realfast(), "", 128 * (1L << 20)).start();
}
private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private BufferedReader reader;
private StringTokenizer tokenizer;
private PrintWriter out;
@Override
public void run() {
try {
if (ONLINE_JUDGE || !new File("input.txt").exists()) {
reader = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
reader = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
solve();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
reader.close();
} catch (IOException e) {
// nothing
}
out.close();
}
}
private String readString() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
@SuppressWarnings("unused")
private int readInt() throws IOException {
return Integer.parseInt(readString());
}
@SuppressWarnings("unused")
private long readLong() throws IOException {
return Long.parseLong(readString());
}
@SuppressWarnings("unused")
private double readDouble() throws IOException {
return Double.parseDouble(readString());
}
}
class edge implements Comparable<edge>{
int u ;
int v;
edge(int u, int v)
{
this.u=u;
this.v=v;
}
public int compareTo(edge e)
{
return this.v-e.v;
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class B {
int n, k, a;
int[] b, l;
double best;
double calc(int i, int r, int c, double p) {
if (i == n) {
if (c <= n / 2) {
p *= 1.0 * a / (a + r);
}
return p;
} else {
return calc(i + 1, r, c + 1, p * l[i] / 10.0) + calc(i + 1, r + b[i], c, p * (10 - l[i]) / 10.0);
}
}
void go(int i, int k) {
if (i == n) {
double p = calc(0, 0, 0, 1.0);
if (p > best) best = p;
} else {
for (int c = 0; c <= k && l[i] + c <= 10; ++c) {
l[i] += c;
go(i + 1, k - c);
l[i] -= c;
}
}
}
void solve() throws IOException {
in("__std"); out("__std");
n = readInt();
k = readInt();
a = readInt();
b = new int[n];
l = new int[n];
for (int i = 0; i < n; ++i) {
b[i] = readInt();
l[i] = readInt() / 10;
}
go(0, k);
println("%.10f", best);
exit();
}
void in(String name) throws IOException {
if (name.equals("__std")) {
in = new BufferedReader(new InputStreamReader(System.in));
} else {
in = new BufferedReader(new FileReader(name));
}
}
void out(String name) throws IOException {
if (name.equals("__std")) {
out = new PrintWriter(System.out);
} else {
out = new PrintWriter(name);
}
}
void exit() {
out.close();
System.exit(0);
}
int readInt() throws IOException {
return Integer.parseInt(readToken());
}
long readLong() throws IOException {
return Long.parseLong(readToken());
}
double readDouble() throws IOException {
return Double.parseDouble(readToken());
}
String readLine() throws IOException {
st = null;
return in.readLine();
}
String readToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
boolean eof() throws IOException {
return !in.ready();
}
void print(String format, Object ... args) {
out.println(new Formatter().format(format, args));
}
void println(String format, Object ... args) {
out.println(new Formatter().format(format, args));
}
void print(Object value) {
out.print(value);
}
void println(Object value) {
out.println(value);
}
void println() {
out.println();
}
StringTokenizer st;
BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws IOException {
new B().solve();
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class C{
public static void main(String[] args) throws IOException {
// br = new BufferedReader(new FileReader(".in"));
// out = new PrintWriter(new FileWriter(".out"));
//new Thread(null, new (), "peepee", 1<<28).start();
read();
int t= RI();
while(t-->0) {
read();
int n = RI();
List<Integer> cur = new ArrayList<Integer>();
int[] lvl = new int[n+10];
while(n-->0) {
read();
int x = RI();
if (cur.size() == 0) {
cur.add(x);
lvl[cur.size()]=x;
}
else {
while (!cur.isEmpty()) {
if (x == 1+lvl[cur.size()]) {
int size = cur.size();
cur.remove(size-1);
cur.add(1+lvl[size]);
lvl[size] = x;
break;
}
else {
// Either add to a new level or go to existing one.
if (x == 1) {
// add
cur.add(x);
lvl[cur.size()] = x;
break;
}
else {
lvl[cur.size()] = 0;
cur.remove(cur.size()-1);
}
}
}
if (cur.size() == 0) {
cur.add(x);
lvl[cur.size()]=x;
}
}
for (int i = 0; i < cur.size(); i++) {
out.print(cur.get(i));
if (i != cur.size()-1) out.print(".");
}
out.println();
}
}
out.close();
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static StringTokenizer st;
static void read() throws IOException{st = new StringTokenizer(br.readLine());}
static int RI() throws IOException{return Integer.parseInt(st.nextToken());}
static long RL() throws IOException{return Long.parseLong(st.nextToken());}
static double RD() throws IOException{return Double.parseDouble(st.nextToken());}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.*;
public class a {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n = input.nextInt();
if(n%2 == 0) System.out.println(4+" "+(n-4));
else System.out.println(9+" " +(n-9));
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
private static HashMap<String, Integer> nodes;
private static void dfs(String cur, PrintWriter out) {
if(cur.length() > 0) {
out.println(cur.substring(1));
}
int children = nodes.get(cur);
for(int i = 1; i <= children; i++) {
dfs(cur+"."+i, out);
}
}
public static void main(String[] args) throws IOException {
//Scanner f = new Scanner(new File("uva.in"));
//Scanner f = new Scanner(System.in);
//BufferedReader f = new BufferedReader(new FileReader("uva.in"));
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int t = Integer.parseInt(f.readLine());
while(t-- > 0) {
int n = Integer.parseInt(f.readLine());
nodes = new HashMap<>();
nodes.put("", 0);
String cur = "";
for(int i = 0; i < n; i++) {
int a = Integer.parseInt(f.readLine());
while(nodes.get(cur) != a-1) {
cur = cur.substring(0, cur.lastIndexOf("."));
}
nodes.put(cur, a);
cur = cur+"."+a;
nodes.put(cur, 0);
}
dfs("", out);
}
f.close();
out.close();
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
final int P = (int) 1e9 + 7;
int n;
char[] commands;
int[][] memo;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
commands = new char[n];
memo = new int[n][12345];
for (int i = 0; i < n; i++) {
commands[i] = in.next().charAt(0);
for (int j = 0; j < 12345; j++) {
memo[i][j] = -1;
}
}
out.print(solve(1, 0));
}
int add(int a, int b) {
return ((a % P) + (b % P)) % P;
}
int solve(int i, int indents) {
if (i == n) return 1;
if (memo[i][indents] != -1) return memo[i][indents];
int answer;
if (commands[i - 1] == 'f') {
answer = solve(i + 1, indents + 1);
} else {
if (indents == 0) {
answer = solve(i + 1, indents);
} else {
answer = add(solve(i, indents - 1), solve(i + 1, indents));
}
}
return memo[i][indents] = answer;
}
}
static class InputReader {
private StringTokenizer tokenizer;
private BufferedReader reader;
public InputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
private void fillTokenizer() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public String next() {
fillTokenizer();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.Map.Entry;
public class Solution implements Runnable {
public static void main(String[] args) {
(new Thread(new Solution())).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String r = in.readLine();
if (r == null) return null;
st = new StringTokenizer(r);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
int n;
int[] b, l;
double ans;
int[] sw;
int a;
void sol() {
for (int i = 0; i < n; i++) l[i] += sw[i] * 10;
double yes = 0;
for (int q = 0; q < (1 << n); q++) {
double p = 1;
int bb = 0;
int cnt = 0;
for (int i = 0; i < n; i++) {
if ((q & (1 << i)) == 0) {
p *= (1.0 - (double)l[i] / 100);
bb += b[i];
} else {
p *= 1.0 * (double)l[i] / 100;
cnt++;
}
}
if (cnt > n / 2) {
yes += p;
} else {
yes += p * (double)a / (double)(a + bb);
}
}
if (ans < yes) ans = yes;
for (int i = 0; i < n; i++) l[i] -= sw[i] * 10;
}
void rek(int i, int k) {
if (i == n) sol(); else {
for (int q = 0; q <= k && l[i] + q * 10 <= 100; q++) {
sw[i] = q;
rek(i + 1, k - q);
}
}
}
void solve() throws Exception {
n = nextInt();
int k = nextInt();
a = nextInt();
b = new int[n];
l = new int[n];
sw = new int[n];
for (int i = 0; i < n; i++) {
b[i] = nextInt();
l[i] = nextInt();
}
rek(0, k);
out.printf("%.10f", ans);
}
public void run() {
Locale.setDefault(Locale.UK);
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
// in = new BufferedReader(new FileReader("knights.in"));
// out = new PrintWriter("knights.out");
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
out.flush();
}
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
public class test {
public static void main(String[] args) throws InterruptedException {
//new careercup().run();
//new CC().run();
//System.out.println(Integer.MAX_VALUE);
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
System.out.println(25);
}catch(IOException io){
io.printStackTrace();
}
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.util.*;
public class ques1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int b = sc.nextInt();
ArrayList<Integer> ar=new ArrayList<>();
for(int i=0;i<b;i++){
ar.add(sc.nextInt());
}
Collections.sort(ar);
int count=0;
int i=0;
while(ar.size()!=0)
{
int tmep=ar.get(i);
int v=ar.remove(i);
count++;
int j=0;
while(j<ar.size()){
if(ar.get(j)%tmep==0){
int a=ar.remove(j);
}
else
j++;
}
}
System.out.println(count);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tok;
static boolean hasNext()
{
while(tok==null||!tok.hasMoreTokens())
try{
tok=new StringTokenizer(in.readLine());
}
catch(Exception e){
return false;
}
return true;
}
static String next()
{
hasNext();
return tok.nextToken();
}
static long nextLong()
{
return Long.parseLong(next());
}
static int nextInt()
{
return Integer.parseInt(next());
}
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
public static void main(String args []){
long x = nextLong();
long a = 2, b = nextLong(), c = 1000000000+7;
long res = 1;
a %= c;
if (x==0){
out.println(0);
out.flush();
return;
}
for (; b != 0; b /= 2) {
if (b % 2 == 1)
res = (res * a) % c;
a = (a * a) % c;
}
BigInteger r = new BigInteger(String.valueOf(res));
BigInteger y = new BigInteger(String.valueOf(x));
BigInteger ans = y.multiply(new BigInteger("2")).subtract(new BigInteger("1")).multiply(r).add(new BigInteger("1")).mod(new BigInteger(String.valueOf(c)));
out.println(ans);
out.flush();
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.Scanner;
public class ReallyBigNumbers1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long s = sc.nextLong();
int r = 0 ;
long l = 0L ;
long u = n ;
if( (l-sumDigits(l)< s ) && (u-sumDigits(u)< s ) )
{
System.out.println(0);
return ;
}
long specified = 0L ;
while( true )
{
long m = (l + u) / 2L ;
if( ( m - sumDigits(m) ) >= s && ( (m-1) - sumDigits(m-1) ) < s )
{
specified = m ;
break ;
}
if( l > u )
break ;
else
{
if( ( m - sumDigits(m) ) >= s )
u = m-1 ;
else
l = m+1 ;
}
}
System.out.println( n-specified+1 );
}
public static int sumDigits(long n)
{
char [] a = (n+"").toCharArray();
int sum = 0 ;
for(int k = 0 ; k < a.length ; k++)
{
sum += Integer.parseInt(a[k]+"") ;
}
return sum ;
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
int[] h = new int[n];
for (int i = 0; i < n; i++)
h[i] = sc.nextInt();
Arrays.sort(h);
pw.print(h[b]-h[b-1]);
pw.close();
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class B {
private Scanner in;
private PrintWriter out;
public void solve()
{
String str = in.next();
List<String> sp = new ArrayList<String>();
StringBuilder sb = null;
int kind = -1;
for(int i = 0;i < str.length();i++){
char c = str.charAt(i);
if(c >= 'A' && c <= 'Z' && kind != 0){
if(sb != null){
sp.add(sb.toString());
}
sb = new StringBuilder();
kind = 0;
}
if(c >= '0' && c <= '9' && kind != 1){
if(sb != null){
sp.add(sb.toString());
}
sb = new StringBuilder();
kind = 1;
}
sb.append(c);
}
sp.add(sb.toString());
if(sp.size() == 2){
// BC23
String bc = sp.get(0);
int v = 0;
for(int i = 0;i < bc.length();i++){
v = 26 * v + (bc.charAt(i) - 'A' + 1);
}
out.println("R" + sp.get(1) + "C" + Integer.toString(v));
}else{
// R23C55
int v = Integer.parseInt(sp.get(3));
StringBuilder sbb = new StringBuilder();
for(;v > 0;v/=26){
v--;
sbb.append((char)((v % 26) + 'A'));
}
sbb.reverse();
out.println(sbb.toString() + sp.get(1));
}
out.flush();
}
public void run() throws Exception
{
// in = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))));
// out = new PrintWriter(new FileWriter(new File("output.txt")));
// in = new Scanner(new StringReader("2\nR23C55\nR26C26\nZ26"));
in = new Scanner(System.in);
// System.setOut(new PrintStream(new BufferedOutputStream(System.out)));
out = new PrintWriter(System.out);
int n = in.nextInt();
// int n = 1;
for(int i = 1;i <= n;i++){
long t = System.currentTimeMillis();
solve();
// System.err.printf("%04d/%04d %7d%n", i, n, System.currentTimeMillis() - t);
}
}
public static void main(String[] args) throws Exception
{
new B().run();
}
private int ni() { return Integer.parseInt(in.next()); }
private static void tr(Object... o) { System.out.println(o.length == 1 ? o[0] : Arrays.toString(o)); }
private void tra(int[] a) {System.out.println(Arrays.toString(a));}
private void tra(int[][] a)
{
for(int[] e : a){
System.out.println(Arrays.toString(e));
}
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class A {
/**
* @param args
*/
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt()-1;
team[] t = new team[n];
for(int i = 0 ;i < n ; i++)
t[i] = new team(scan.nextInt(), scan.nextInt());
Arrays.sort(t);
int a =0;
int b = 0;
while(k+a < t.length-1 && t[k+a+1].compareTo(t[k]) == 0)
a++;
while(k-b > 0 && t[k-b-1].compareTo(t[k]) == 0)
b++;
System.out.println(a+b+1);
}
}
class team implements Comparable<team>
{
int p;
int t;
public team(int pp , int tt)
{
p = pp;
t= tt;
}
@Override
public String toString()
{
return p+" "+t;
}
@Override
public int compareTo(team e)
{
int a = e.p-p;
if(a == 0)
{
return t-e.t;
}else
return a;
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class practice {
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 scn=new Reader("input.txt");
PrintWriter out = new PrintWriter(new File("output.txt"));
int n=scn.nextInt(),m=scn.nextInt(),k=scn.nextInt();
int[][] inf=new int[k][2];
for(int i=0;i<k;i++){
inf[i][0]=scn.nextInt();inf[i][1]=scn.nextInt();
}
int ans=0,x=1,y=1;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
int temp=Integer.MAX_VALUE;
for(int l=0;l<k;l++){
temp=Math.min(temp, Math.abs(i-inf[l][0])+Math.abs(j-inf[l][1]));
}
if(temp>ans){
ans=temp;x=i;y=j;
}
}
}
out.print(x + " " + y);
out.close();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class C {
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
int[] x = new int[n];
int max=0, pos=-1;
for(int i=0; i<n; i++) {
x[i]=sc.nextInt();
if (max<x[i]) {
max=x[i];
pos=i;
}
}
x[pos] = (max==1) ? 2 : 1;
Arrays.sort(x);
for(int i=0; i<n; i++)
System.out.print(x[i]+" ");
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.util.* ;
import java.io.* ;
public class PythonIndentation
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in) ;
int n = in.nextInt() ;
boolean[] lst = new boolean[n] ;
for(int i=0;i<n;i++)
{
lst[i] = (in.next().equals("s"))?false:true ;
}
System.out.println(dp(lst)) ;
}
// static void arrayPrinter(int[][] dp)
// {
// System.out.println(":::") ;
// for(int i=0;i<dp.length;i++)
// {
// for(int j=0;j<dp[0].length;j++)
// {
// System.out.print(dp[i][j]+" ") ;
// }
// System.out.println() ;
// }
// }
static long dp(boolean[] lst)
{//false in lst means an "s" (simple statement), and true a "f"(for loop)
long[][] dp = new long[lst.length][lst.length] ;
dp[0][0] = 1 ;
for(int i=1;i<lst.length;i++)
{
// int sum_i = 0;
// for(int j=0;j<lst.length;j++)
// sum_i = (sum_i+dp[i-1][j])%1000000007 ;
for(int j=0;j<lst.length;j++)
{
if(lst[i-1])//(i-1)st statement is a for loop
{
if(j==0)
dp[i][j] = 0 ;
else
dp[i][j] = dp[i-1][j-1] ;
}
else//i-1 st statement is a simple statement
{
if(j==0)
{
for(int k=0;k<lst.length;k++)
dp[i][j] = (dp[i][j]+dp[i-1][k])%1000000007 ;
}
else
dp[i][j] = (dp[i][j-1]-dp[i-1][j-1])%1000000007 ;
// if(j==lst.length-1)
// dp[i][j] = dp[i][j-1] ;
// else
// dp[i][j] = (dp[i-1][j]+dp[i][j+1])%1000000007 ;
}
}
}
// for(int i=0;i<lst.length;i++)
// System.out.print(dp[lst.length-1][i]+" ") ;
// System.out.println() ;
long ans = 0 ;
for(int i=0;i<lst.length;i++)
{
ans = (ans + dp[lst.length-1][i])%1000000007 ;
}
if(ans<0)
ans = ans + 1000000007 ;
return ans ;
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class default_dst {
public static void main(String[] args) {
in = new FastReader();
int n=ni();
int[] arr=takeIntegerArrayInput(n);
HashMap<Long,ArrayList<pair>> hm=new HashMap<>();
int max_size=0;
long S=-1;
for (int i=0;i<arr.length;i++){
long sum=0;
for (int j=i;j>=0;j--){
sum+=arr[j];
if (!hm.containsKey(sum)){
hm.put(sum,new ArrayList<>());
}
if (hm.get(sum).size()==0||hm.get(sum).get(hm.get(sum).size()-1).y<j){
hm.get(sum).add(new pair(j,i));
}
if (hm.get(sum).size()>max_size){
max_size=hm.get(sum).size();
S=sum;
}
}
}
System.out.println(max_size);
StringBuilder sb=new StringBuilder();
for (int i=0;i<hm.get(S).size();i++){
sb.append(hm.get(S).get(i)).append("\n");
}
System.out.print(sb.toString());
}
static class pair{
int x;
int y;
pair(int x,int y){
this.x=x;
this.y=y;
}
@Override
public String toString(){
return (this.x+1)+" "+(this.y+1);
}
}
public static long binarySearch(long low, long high) {
while (high - low > 1) {
long mid = (high - low)/2 + low;
//System.out.println(mid);
if (works(mid)) {
high = mid;
} else {
low = mid;
}
}
return (works(low) ? low : high);
}
static long fast_exp_with_mod(long base, long exp) {
long MOD=1000000000+7;
long res=1;
while(exp>0) {
if(exp%2==1) res=(res*base)%MOD;
base=(base*base)%MOD;
exp/=2;
}
return res%MOD;
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class my_no{
long num;
long denom;
@Override
public String toString() {
if (denom<0){
this.num=-this.num;
this.denom=-this.denom;
}
if (num==0)return "0";
return (num+"/"+denom);
}
my_no(int no){
this.num=no;
this.denom=1;
}
my_no(long num,long denom){
this.num=num;
this.denom=denom;
}
my_no multiply(my_no obj){
long num1=obj.num;
long denom1=obj.denom;
long n=num1*num;
long d=denom1*denom;
long gcd=gcd(n,d);
n/=gcd;
d/=gcd;
return new my_no(n,d);
}
// my_no multiply(my_no obj){
// long num1=obj.num;
// long denom1=obj.denom;
// long num2=this.num;
// long denom2=this.denom;
//
// }
my_no multiply(int no){
long n=num*no;
long d=denom;
long gcd=gcd(n,d);
n/=gcd;
d/=gcd;
return new my_no(n,d);
}
}
static void memset(int[][] arr,int val){
for (int i=0;i<arr.length;i++){
for (int j=0;j<arr[i].length;j++){
arr[i][j]=val;
}
}
}
static void memset(int[] arr,int val){
for (int i=0;i<arr.length;i++){
arr[i]=val;
}
}
static void memset(long[][] arr,long val){
for (int i=0;i<arr.length;i++){
for (int j=0;j<arr[i].length;j++){
arr[i][j]=val;
}
}
}
static void memset(long[] arr,long val){
for (int i=0;i<arr.length;i++){
arr[i]=val;
}
}
static private boolean works(long test){
return true;
}
static void reverse(char[] arr ,int i,int j){
if (i==j)
return;
while (i<j){
char temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
++i;
--j;
}
}
static int[] takeIntegerArrayInput(int no){
int[] arr=new int[no];
for (int i=0;i<no;++i){
arr[i]=ni();
}
return arr;
}
static long fast_Multiply(long no , long pow){
long result=1;
while (pow>0){
if ((pow&1)==1){
result=result*no;
}
no=no*no;
pow>>=1;
}
return result;
}
static long[] takeLongArrayInput(int no){
long[] arr=new long[no];
for (int i=0;i<no;++i){
arr[i]=ni();
}
return arr;
}
static final long MOD = (long)1e9+7;
static FastReader in;
static void p(Object o){
System.out.print(o);
}
static void pn(Object o){
System.out.println(o);
}
static String n(){
return in.next();
}
static String nln(){
return in.nextLine();
}
static int ni(){
return Integer.parseInt(in.next());
}
static int[] ia(int N){
int[] a = new int[N];
for(int i = 0; i<N; i++)a[i] = ni();
return a;
}
static long[] la(int N){
long[] a = new long[N];
for(int i = 0; i<N; i++)a[i] = nl();
return a;
}
static long nl(){
return Long.parseLong(in.next());
}
static double nd(){
return Double.parseDouble(in.next());
}
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();
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
}
static void println(String[] arr){
for (int i=0;i<arr.length;++i){
System.out.println(arr[i]);
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
/**
* @author grozhd
*/
public class P3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = "";
while (s.length() == 0) {
s = sc.nextLine();
}
char[] pokemons = s.toCharArray();
Set<Character> pokemonTypes = new HashSet<>();
for (int i = 0; i < n; i++) {
pokemonTypes.add(pokemons[i]);
}
int types = pokemonTypes.size();
int l = 0;
int r = 0;
int min = n;
Map<Character, Integer> currentPokemons = new HashMap<>();
while (r < n) {
while (currentPokemons.size() < types && r < n) {
char pokemon = pokemons[r++];
currentPokemons.merge(pokemon, 1, (a, b) -> a + b);
}
min = Math.min(r - l, min);
while (currentPokemons.size() == types) {
char pokemon = pokemons[l++];
if (currentPokemons.get(pokemon) == 1) {
currentPokemons.remove(pokemon);
} else {
min = Math.min(r - l, min);
currentPokemons.put(pokemon, currentPokemons.get(pokemon) - 1);
}
}
}
min = Math.min(min, r - l + 1);
min = Math.max(min, types);
System.out.println(min);
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class A {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer st;
static Random rnd;
void solve() throws IOException {
int n = nextInt();
int[] arr = new int[n];
Integer[] arrCopy = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = arrCopy[i] = nextInt();
Arrays.sort(arrCopy);
int bad = 0;
for (int i = 0; i < n; i++)
if (arr[i] != arrCopy[i])
++bad;
boolean fail = bad > 2;
out.println(!fail ? "YES" : "NO");
}
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
rnd = new Random();
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(42);
}
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class p472a {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n % 2 == 0) {
System.out.println("8 " + (n - 8));
} else {
System.out.println("9 " + (n - 9));
}
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
out.println(n+" 0 0");
in.close();
out.close();
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.awt.Point;
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import static java.lang.Integer.*;
import static java.lang.Math.*;
@SuppressWarnings("unused")
public class round35C {
static class state{
int x, y, time;
public state(int xx, int yy, int t){
x = xx;
y = yy;
time = t;
}
}
static int N,M;
static int [] dx = new int [] {1,-1,0,0};
static int [] dy = new int [] {0,0,1,-1};
static Queue<state> bfs = new LinkedList<round35C.state>();
public static Point runBFS(){
boolean [][] vis = new boolean [N + 1][M + 1];
int max = -(int)1e9;
int bestx = -1;
int besty = -1;
while(!bfs.isEmpty()){
state p = bfs.poll();
int x = p.x;
int y = p.y;
int time = p.time;
if(vis[x][y])
continue;
vis[x][y] = true;
if(time > max){
max = time;
bestx = x + 1;
besty = y + 1;
}
for(int i = 0 ; i < 4 ; ++i){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx < 0 || ny < 0 || nx >= N || ny >= M)
continue;
if(vis[nx][ny] == false)
bfs.offer(new state(nx, ny, time + 1));
}
}
return new Point(bestx, besty);
}
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter("output.txt");
String [] use = null;
use = br.readLine().split(" ");
N = parseInt(use[0]);
M = parseInt(use[1]);
int K = parseInt(br.readLine());
use = br.readLine().split(" ");
for(int i = 0 ; i < 2 * K ; i += 2){
int f = parseInt(use[i]) - 1;
int t = parseInt(use[i + 1]) - 1;
bfs.offer(new state(f, t, 0));
}
Point ans = runBFS();
out.println(ans.x + " " + ans.y);
out.flush();
out.close();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
public class P1517D {
// author: Nagabhushan S Baddi
// PRIMARY VARIABLES
private static int n, m, k;
private static int[][] hor, ver, a, b;
private static long ans;
private static int[][] id;
private static Integer[][][] dp;
private static int idf;
private static String s, t;
private static HashMap<Integer, ArrayList<Integer>> g;
// CONSTANTS
private static final int MOD = (int) 1e9 + 7;
public static void main(String[] args) {
n = ini();
m = ini();
k = ini();
if (k%2!=0) {
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
print(-1+" ");
}
println();
}
out.flush();
return;
}
hor = new int[n][m-1];
ver = new int[n-1][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m-1; j++) {
hor[i][j] = ini();
}
}
for(int i=0; i<n-1; i++) {
for(int j=0; j<m; j++) {
ver[i][j] = ini();
}
}
dp = new Integer[n][m][k+1];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
print(2*solve(i, j, k/2)+" ");
}
println();
}
out.flush();
out.close();
}
private static int solve(int i, int j, int kLeft) {
if (i<0 || i>=n || j<0 || j>=m) {
return (int)1e9;
} else if (kLeft==0) {
return 0;
}
if (dp[i][j][kLeft]!=null) {
return dp[i][j][kLeft];
}
int ans = (int)1e9;
final int[] dx = {-1, 1, 0, 0};
final int[] dy = {0, 0, -1, 1};
for(int type=0; type<4; type++) {
int ni = i+dx[type];
int nj = j+dy[type];
if (ni<0 || ni>=n || nj<0 || nj>=m) continue;
int inhibit = 0;
if (type==0) {
inhibit = ver[ni][nj];
} else if (type==1) {
inhibit = ver[i][j];
} else if (type==2) {
inhibit = hor[ni][nj];
} else {
inhibit = hor[i][j];
}
ans = Math.min(ans, inhibit+solve(ni, nj, kLeft-1));
}
return dp[i][j][kLeft]=ans;
}
// INIT
private static void initCase(int z) {
idf = z;
ans = 0;
}
// PRINT ANSWER
private static void printAns(Object o) {
out.println(o);
}
private static void printAns(Object o, int testCaseNo) {
out.println("Case #" + testCaseNo + ": " + o);
}
private static void printArray(Object[] a) {
for (int i = 0; i < a.length; i++) {
out.print(a[i] + " ");
}
out.println();
}
// SORT SHORTCUTS - QUICK SORT TO MERGE SORT
private static void sort(int[] a) {
int n = a.length;
Integer[] b = new Integer[n];
for (int i = 0; i < n; i++) {
b[i] = a[i];
}
Arrays.sort(b);
for (int i = 0; i < n; i++) {
a[i] = b[i];
}
}
private static void sort(long[] a) {
int n = a.length;
Long[] b = new Long[n];
for (int i = 0; i < n; i++) {
b[i] = a[i];
}
Arrays.sort(b);
for (int i = 0; i < n; i++) {
a[i] = b[i];
}
}
// INPUT SHORTCUTS
private static int[] ina(int n) {
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
temp[i] = in.nextInt();
}
return temp;
}
private static int[][] ina2d(int n, int m) {
int[][] temp = new int[n][m];
for (int i = 0; i < n; i++) {
temp[i] = ina(m);
}
return temp;
}
private static int ini() {
return in.nextInt();
}
private static long inl() {
return in.nextLong();
}
private static double ind() {
return Double.parseDouble(ins());
}
private static String ins() {
return in.readString();
}
// PRINT SHORTCUTS
private static void println(Object... o) {
for (Object x : o) {
out.write(x + "");
}
out.write("\n");
}
private static void pd(Object... o) {
for (Object x : o) {
out.write(x + "");
}
out.flush();
out.write("\n");
}
private static void print(Object... o) {
for (Object x : o) {
out.write(x + "");
}
}
// GRAPH SHORTCUTS
private static HashMap<Integer, ArrayList<Integer>> intree(int n) {
HashMap<Integer, ArrayList<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
int u = ini() - 1;
int v = ini() - 1;
g.get(u).add(v);
g.get(v).add(u);
}
return g;
}
private static HashMap<Integer, ArrayList<Integer>> ingraph(int n, int m) {
HashMap<Integer, ArrayList<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = ini() - 1;
int v = ini() - 1;
g.get(u).add(v);
g.get(v).add(u);
}
return g;
}
private static HashMap<Integer, ArrayList<Integer>> indirectedgraph(int n, int m) {
HashMap<Integer, ArrayList<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = ini() - 1;
int v = ini() - 1;
g.get(u).add(v);
}
return g;
}
private static HashMap<Integer, ArrayList<Edge>> inweightedgraph(int n, int m) {
HashMap<Integer, ArrayList<Edge>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = ini() - 1;
int v = ini() - 1;
int w = ini();
Edge edge = new Edge(u, v, w);
g.get(u).add(edge);
g.get(v).add(edge);
}
return g;
}
private static class Edge implements Comparable<Edge> {
private int u, v;
private long w;
public Edge(int a, int b, long c) {
u = a;
v = b;
w = c;
}
public int other(int x) {
return (x == u ? v : u);
}
public int compareTo(Edge edge) {
return Long.compare(w, edge.w);
}
}
private static class Pair {
private int u, v;
public Pair(int a, int b) {
u = a;
v = b;
}
public int hashCode() {
return u + v + u * v;
}
public boolean equals(Object object) {
Pair pair = (Pair) object;
return u == pair.u && v == pair.v;
}
}
private static class Node implements Comparable<Node> {
private int u;
private long dist;
public Node(int a, long b) {
u = a;
dist = b;
}
public int compareTo(Node node) {
return Long.compare(dist, node.dist);
}
}
// MATHS AND NUMBER THEORY SHORTCUTS
private static int gcd(int a, int b) {
// O(log(min(a,b)))
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long modExp(long a, long b) {
if (b == 0)
return 1;
a %= MOD;
long exp = modExp(a, b / 2);
if (b % 2 == 0) {
return (exp * exp) % MOD;
} else {
return (a * ((exp * exp) % MOD)) % MOD;
}
}
private long mul(int a, int b) {
return a * 1L * b;
}
// Segment Tree
private static class SegmentTree<T extends Comparable<T>> {
private int n, m;
private T[] a;
private T[] seg;
private T NULLVALUE;
public SegmentTree(int n, T NULLVALUE) {
this.NULLVALUE = NULLVALUE;
this.n = n;
m = 4 * n;
seg = (T[]) new Object[m];
}
public SegmentTree(T[] a, int n, T NULLVALUE) {
this.NULLVALUE = NULLVALUE;
this.a = a;
this.n = n;
m = 4 * n;
seg = (T[]) new Object[m];
construct(0, n - 1, 0);
}
private void update(int pos) {
// Range Sum
// seg[pos] = seg[2*pos+1]+seg[2*pos+2];
// Range Min
if (seg[2 * pos + 1].compareTo(seg[2 * pos + 2]) <= 0) {
seg[pos] = seg[2 * pos + 1];
} else {
seg[pos] = seg[2 * pos + 2];
}
}
private T optimum(T leftValue, T rightValue) {
// Range Sum
// return leftValue+rightValue;
// Range Min
if (leftValue.compareTo(rightValue) <= 0) {
return leftValue;
} else {
return rightValue;
}
}
public void construct(int low, int high, int pos) {
if (low == high) {
seg[pos] = a[low];
return;
}
int mid = (low + high) / 2;
construct(low, mid, 2 * pos + 1);
construct(mid + 1, high, 2 * pos + 2);
update(pos);
}
public void add(int index, T value) {
add(index, value, 0, n - 1, 0);
}
private void add(int index, T value, int low, int high, int pos) {
if (low == high) {
seg[pos] = value;
return;
}
int mid = (low + high) / 2;
if (index <= mid) {
add(index, value, low, mid, 2 * pos + 1);
} else {
add(index, value, mid + 1, high, 2 * pos + 2);
}
update(pos);
}
public T get(int qlow, int qhigh) {
return get(qlow, qhigh, 0, n - 1, 0);
}
public T get(int qlow, int qhigh, int low, int high, int pos) {
if (qlow > low || low > qhigh) {
return NULLVALUE;
} else if (qlow <= low || qhigh >= high) {
return seg[pos];
} else {
int mid = (low + high) / 2;
T leftValue = get(qlow, qhigh, low, mid, 2 * pos + 1);
T rightValue = get(qlow, qhigh, mid + 1, high, 2 * pos + 2);
return optimum(leftValue, rightValue);
}
}
}
// DSU
private static class DSU {
private int[] id;
private int[] size;
private int n;
public DSU(int n) {
this.n = n;
id = new int[n];
for (int i = 0; i < n; i++) {
id[i] = i;
}
size = new int[n];
Arrays.fill(size, 1);
}
private int root(int u) {
while (u != id[u]) {
id[u] = id[id[u]];
u = id[u];
}
return u;
}
public boolean connected(int u, int v) {
return root(u) == root(v);
}
public void union(int u, int v) {
int p = root(u);
int q = root(v);
if (size[p] >= size[q]) {
id[q] = p;
size[p] += size[q];
} else {
id[p] = q;
size[q] += size[p];
}
}
}
// KMP
private static int countSearch(String s, String p) {
int n = s.length();
int m = p.length();
int[] b = backTable(p);
int j = 0;
int count = 0;
for (int i = 0; i < n; i++) {
if (j == m) {
j = b[j - 1];
count++;
}
while (j != 0 && s.charAt(i) != p.charAt(j)) {
j = b[j - 1];
}
if (s.charAt(i) == p.charAt(j)) {
j++;
}
}
if (j == m)
count++;
return count;
}
private static int[] backTable(String p) {
int m = p.length();
int j = 0;
int[] b = new int[m];
for (int i = 1; i < m; i++) {
while (j != 0 && p.charAt(i) != p.charAt(j)) {
j = b[j - 1];
}
if (p.charAt(i) == p.charAt(j)) {
b[i] = ++j;
}
}
return b;
}
private static class LCA {
private HashMap<Integer, ArrayList<Integer>> g;
private int[] level;
private int[] a;
private int[][] P;
private int n, m;
private int[] xor;
public LCA(HashMap<Integer, ArrayList<Integer>> g, int[] a) {
this.g = g;
this.a = a;
n = g.size();
m = (int) (Math.log(n) / Math.log(2)) + 5;
P = new int[n][m];
xor = new int[n];
level = new int[n];
preprocess();
}
private void preprocess() {
dfs(0, -1);
for (int j = 1; j < m; j++) {
for (int i = 0; i < n; i++) {
if (P[i][j - 1] != -1) {
P[i][j] = P[P[i][j - 1]][j - 1];
}
}
}
}
private void dfs(int u, int p) {
P[u][0] = p;
xor[u] = a[u] ^ (p == -1 ? 0 : xor[p]);
level[u] = (p == -1 ? 0 : level[p] + 1);
for (int v : g.get(u)) {
if (v == p)
continue;
dfs(v, u);
}
}
public int lca(int u, int v) {
if (level[v] > level[u]) {
int temp = v;
v = u;
u = temp;
}
for (int j = m; j >= 0; j--) {
if (level[u] - (1 << j) < level[v]) {
continue;
} else {
u = P[u][j];
}
}
if (u == v)
return u;
for (int j = m - 1; j >= 0; j--) {
if (P[u][j] == -1 || P[u][j] == P[v][j]) {
continue;
} else {
u = P[u][j];
v = P[v][j];
}
}
return P[u][0];
}
private int xor(int u, int v) {
int l = lca(u, v);
return xor[u] ^ xor[v] ^ a[l];
}
}
// FAST INPUT OUTPUT LIBRARY
private static InputReader in = new InputReader(System.in);
private static PrintWriter out = new PrintWriter(System.out);
private static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* 111118315581
*
* @author pttrung
*/
public class C {
static Point hand;
static int n;
static Point[] data;
static int[] next;
static int[] dp;
static int[][] pre;
public static void main(String[] args) {
Scanner in = new Scanner();
PrintWriter out = new PrintWriter(System.out);
// System.out.println(1 << 24);
hand = new Point(in.nextInt(), in.nextInt());
n = in.nextInt();
data = new Point[n];
for (int i = 0; i < n; i++) {
data[i] = new Point(in.nextInt(), in.nextInt());
}
pre = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
pre[i][j] = distance(data[i], data[j]);
}
}
next = new int[1 << n];
dp = new int[1 << n];
Arrays.fill(dp, -1);
out.println(cal(0));
int start = 0;
do {
int m = next[start];
int val = m - start;
out.print(0 + " ");
for (int i = 0; i < n; i++) {
if (((1 << i) & val) != 0) {
out.print((i + 1) + " ");
}
}
// out.print(0 + " ") ;
start = m;
} while (start != (1 << n) - 1);
out.println(0);
out.close();
}
public static int cal(int mask) {
if ((1 << n) - 1 == mask) {
// System.out.println(mask);
return 0;
}
if (dp[mask] != -1) {
return dp[mask];
}
int result = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (((1 << i) & mask) == 0) {
int dist = distance(hand, data[i]);
for (int j = i + 1; j < n; j++) {
if (((1 << j) & mask) == 0) {
//System.out.println(i + " " + j);
int temp = dist + distance(hand, data[j]) + pre[i][j] + cal(mask | (1 << i) | (1 << j));
//System.out.println(temp);
if (temp < result) {
result = temp;
next[mask] = (mask | (1 << i) | (1 << j));
}
}
}
int temp = 2 * dist + cal(mask | (1 << i));
if (temp < result) {
result = temp;
next[mask] = (mask | (1 << i));
}
break;
}
}
dp[mask] = result;
return result;
}
static int distance(Point a, Point b) {
int total = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
return total;
}
static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
public class ehab4 {
public static void main( String[] args ) {
Scanner in = new Scanner( System.in );
int a = 0, b = 0;
System.out.println( "? 0 0 " );
System.out.flush();
int c = in.nextInt();
for ( int i = 29; i >= 0; i-- ) {
System.out.println( "? " + ( a + ( 1 << i ) ) + " " + b );
System.out.flush();
int q1 = in.nextInt();
System.out.println( "? " + a + " " + ( b + ( 1 << i ) ) );
System.out.flush();
int q2 = in.nextInt();
if ( q1 == q2 ) {
if ( c == 1 )
a += ( 1 << i );
else if ( c == -1 )
b += ( 1 << i );
c = q1;
}
else if ( q1 == -1 ) {
a += ( 1 << i );
b += ( 1 << i );
}
else if ( q1 == -2 )
return;
}
System.out.println( "! " + a + " " + b );
System.out.flush();
}
}
|
logn
|
1088_D. Ehab and another another xor problem
|
CODEFORCES
|
import java.util.*;
public class Main {
private static Scanner in = new Scanner(System.in);
public static void main(String args[]){
int n = in.nextInt();
String s = in.next();
if(n==1)
System.out.println("1");
else{
int j=0,i=1,ans=s.length();
int h[]=new int[128];
h[(int)s.charAt(0)]=1;
while(i<n){
if(h[(int)s.charAt(i)]==0)
ans = i-j+1;
h[(int) s.charAt(i)]++;
while(j<i && h[(int)s.charAt(j)]>1){
h[(int)s.charAt(j)]--;
j++;
ans = Math.min(ans, i-j+1);
}
i++;
}
System.out.println(ans);
}
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.util.*;
public class cf11d {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
boolean[][] g = new boolean[n][n];
boolean[] ok = new boolean[1<<n];
int[] f = new int[1<<n];
for(int i=1; i<(1<<n); i++) {
ok[i] = Integer.bitCount(i)>=3;
f[i] = first(i);
}
for(int i=0; i<m; i++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
g[a][b] = g[b][a] = true;
}
long[][] dp = new long[n][1<<n];
for(int i=0; i<n; i++)
dp[i][1<<i] = 1;
for(int i=1; i<(1<<n); i++)
for(int j=0; j<n; j++)
for(int k=f[i]+1; k<n; k++)
if((i&(1<<k)) == 0 && g[j][k])
dp[k][i^(1<<k)] += dp[j][i];
long ret = 0;
for(int i=1; i<(1<<n); i++)
for(int j=0; j<n; j++)
if(ok[i] && j != f[i])
ret += g[j][f[i]]?dp[j][i]:0;
System.out.println(ret/2);
}
static int first(int x) {
int ret = 0;
while(x%2==0) {
x/=2;
ret++;
}
return ret;
}
}
/*
19 171
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
1 11
1 12
1 13
1 14
1 15
1 16
1 17
1 18
1 19
2 3
2 4
2 5
2 6
2 7
2 8
2 9
2 10
2 11
2 12
2 13
2 14
2 15
2 16
2 17
2 18
2 19
3 4
3 5
3 6
3 7
3 8
3 9
3 10
3 11
3 12
3 13
3 14
3 15
3 16
3 17
3 18
3 19
4 5
4 6
4 7
4 8
4 9
4 10
4 11
4 12
4 13
4 14
4 15
4 16
4 17
4 18
4 19
5 6
5 7
5 8
5 9
5 10
5 11
5 12
5 13
5 14
5 15
5 16
5 17
5 18
5 19
6 7
6 8
6 9
6 10
6 11
6 12
6 13
6 14
6 15
6 16
6 17
6 18
6 19
7 8
7 9
7 10
7 11
7 12
7 13
7 14
7 15
7 16
7 17
7 18
7 19
8 9
8 10
8 11
8 12
8 13
8 14
8 15
8 16
8 17
8 18
8 19
9 10
9 11
9 12
9 13
9 14
9 15
9 16
9 17
9 18
9 19
10 11
10 12
10 13
10 14
10 15
10 16
10 17
10 18
10 19
11 12
11 13
11 14
11 15
11 16
11 17
11 18
11 19
12 13
12 14
12 15
12 16
12 17
12 18
12 19
13 14
13 15
13 16
13 17
13 18
13 19
14 15
14 16
14 17
14 18
14 19
15 16
15 17
15 18
15 19
16 17
16 18
16 19
17 18
17 19
18 19
*/
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.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;
FastReader in = new FastReader(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, FastReader in, PrintWriter out) {
int n = in.nextInt();
TaskD.Pair[] p = new TaskD.Pair[n];
for (int i = 0; i < n; ++i) {
p[i] = new TaskD.Pair(in.nextLong(), in.nextLong());
}
Arrays.sort(p);
int last = 0;
int ans = 1;
for (int i = 1; i < n; ++i) {
if (p[i].x - p[i].w >= p[last].x + p[last].w) {
last = i;
++ans;
}
}
out.println(ans);
}
static class Pair implements Comparable<TaskD.Pair> {
long x;
long w;
public Pair(long x, long w) {
this.x = x;
this.w = w;
}
public int compareTo(TaskD.Pair o) {
return Long.compare(x + w, o.x + o.w);
}
public String toString() {
return x + " " + w;
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
nlogn
|
528_B. Clique Problem
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
BSearchingRectangles solver = new BSearchingRectangles();
solver.solve(1, in, out);
out.close();
}
}
static class BSearchingRectangles {
FastInput in;
FastOutput out;
int n;
public void solve(int testNumber, FastInput in, FastOutput out) {
this.in = in;
this.out = out;
n = in.readInt();
IntBinarySearch upDown = new IntBinarySearch() {
public boolean check(int mid) {
return query(1, n, 1, mid) >= 1;
}
};
IntBinarySearch leftRight = new IntBinarySearch() {
public boolean check(int mid) {
return query(1, mid, 1, n) >= 1;
}
};
int threshold = upDown.binarySearch(1, n);
int[] r1;
int[] r2;
if (query(1, n, 1, threshold) == 1 &&
query(1, n, threshold + 1, n) == 1) {
r1 = find(1, n, 1, threshold);
r2 = find(1, n, threshold + 1, n);
} else {
threshold = leftRight.binarySearch(1, n);
r1 = find(1, threshold, 1, n);
r2 = find(threshold + 1, n, 1, n);
}
out.append("! ");
output(r1);
output(r2);
out.flush();
}
public void output(int[] ans) {
for (int x : ans) {
out.append(x).append(' ');
}
}
public int[] find(int l, int r, int d, int u) {
IntBinarySearch downIBS = new IntBinarySearch() {
public boolean check(int mid) {
return query(l, r, mid, u) == 0;
}
};
int y1 = downIBS.binarySearch(d, u);
if (query(l, r, y1, u) == 0) {
y1--;
}
IntBinarySearch upIBS = new IntBinarySearch() {
public boolean check(int mid) {
return query(l, r, d, mid) >= 1;
}
};
int y2 = upIBS.binarySearch(d, u);
IntBinarySearch leftIBS = new IntBinarySearch() {
public boolean check(int mid) {
return query(mid, r, d, u) == 0;
}
};
int x1 = leftIBS.binarySearch(l, r);
if (query(x1, r, d, u) == 0) {
x1--;
}
IntBinarySearch rightIBS = new IntBinarySearch() {
public boolean check(int mid) {
return query(l, mid, d, u) >= 1;
}
};
int x2 = rightIBS.binarySearch(l, r);
return new int[]{x1, y1, x2, y2};
}
public int query(int l, int r, int d, int u) {
if (l > r || d > u) {
return 0;
}
out.printf("? %d %d %d %d", l, d, r, u).println().flush();
return in.readInt();
}
}
static class DigitUtils {
private DigitUtils() {
}
public static int floorAverage(int x, int y) {
return (x & y) + ((x ^ y) >> 1);
}
}
static abstract class IntBinarySearch {
public abstract boolean check(int mid);
public int binarySearch(int l, int r) {
if (l > r) {
throw new IllegalArgumentException();
}
while (l < r) {
int mid = DigitUtils.floorAverage(l, r);
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput append(CharSequence csq) {
cache.append(csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append(csq, start, end);
return this;
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
return this;
}
public FastOutput append(int c) {
cache.append(c);
return this;
}
public FastOutput append(String c) {
cache.append(c);
return this;
}
public FastOutput printf(String format, Object... args) {
cache.append(String.format(format, args));
return this;
}
public FastOutput println() {
cache.append(System.lineSeparator());
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
/*
* PDPM IIITDM Jabalpur
* Asutosh Rana
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
long MOD = 1000000007;
InputReader in;
BufferedReader br;
PrintWriter out;
public static void main(String[] args) throws java.lang.Exception {
Main solver = new Main();
solver.in = new InputReader(System.in);
solver.br = new BufferedReader(new InputStreamReader(System.in));
solver.out = new PrintWriter(System.out);
solver.solve();
solver.out.flush();
solver.out.close();
}
public void solve() {
int tc = 1;//in.readInt();
for (int cas = 1; cas <= tc; cas++) {
int N = in.readInt();
int[] A = new int[N];
in.readInt(A);
int res = 0;
for(int i=0;i<N;i++){
for(int j=i+1;j<N;j++){
if(A[i]>A[j])
res++;
}
}
res = res % 2;
int Q = in.readInt();
while(Q-->0){
int l = in.readInt();
int r = in.readInt();
int add = (r-l+1)/2;
res = res + add;
res%=2;
out.println(res%2==0?"even":"odd");
}
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public void readInt(int[] A) {
for (int i = 0; i < A.length; i++)
A[i] = readInt();
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public void readLong(long[] A) {
for (int i = 0; i < A.length; i++)
A[i] = readLong();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
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, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public char[] readCharA() {
return readString().toCharArray();
}
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);
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.ArrayDeque;
import java.util.Arrays;
public class Main {
private static StreamTokenizer in;
private static PrintWriter out;
private static BufferedReader inB;
private static int nextInt() throws Exception{
in.nextToken();
return (int)in.nval;
}
private static String nextString() throws Exception{
in.nextToken();
return in.sval;
}
static{
/*
inB = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
/**/
//*
try {
inB = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
out = new PrintWriter(new FileOutputStream("output.txt"));
} catch(Exception e) {}
/**/
in = new StreamTokenizer(inB);
}
private static int[][] mind;
private static boolean[][] used;
private static int n,m;
public static void main(String[] args)throws Exception {
n = nextInt();
m = nextInt();
int k = nextInt();
int[][] mas = new int[k][2];
for(int i = 0; i<k; i++) {
mas[i][0] = nextInt()-1;
mas[i][1] = nextInt()-1;
}
mind = new int[n][m];
used = new boolean[n][m];
for(int i = 0; i<n; i++) {
Arrays.fill(mind[i], Integer.MAX_VALUE);
}
ArrayDeque<int[]> ad = new ArrayDeque<int[]>();
for(int i = 0; i<k; i++) {
ad.add(new int[] {mas[i][0], mas[i][1], 0});
}
while(!ad.isEmpty()) {
int[] cur = ad.remove();
if(used[cur[0]][cur[1]])continue;
int x = cur[0]; int y = cur[1]; int d = cur[2];
mind[x][y] = ++d;
used[x][y] = true;
//if(isValid(x+1,y+1) && !used[x+1][y+1]) ad.add(new int[] {x+1, y+1, d});
if(isValid(x+1,y) && !used[x+1][y]) ad.add(new int[] {x+1, y, d});
//if(isValid(x+1,y-1) && !used[x+1][y-1]) ad.add(new int[] {x+1, y-1, d});
if(isValid(x,y+1) && !used[x][y+1]) ad.add(new int[] {x, y+1, d});
if(isValid(x,y-1) && !used[x][y-1]) ad.add(new int[] {x, y-1, d});
//if(isValid(x-1,y+1) && !used[x-1][y+1]) ad.add(new int[] {x-1, y+1, d});
if(isValid(x-1,y) && !used[x-1][y]) ad.add(new int[] {x-1, y, d});
//if(isValid(x-1,y-1) && !used[x-1][y-1]) ad.add(new int[] {x-1, y-1, d});
}
int max = Integer.MIN_VALUE;
int maxx = 0, maxy = 0;
for(int i = 0; i<n; i++) {
for(int j = 0; j<m; j++) {
if(mind[i][j] > max) {
max = mind[i][j];
maxx = i+1;
maxy = j+1;
}
}
}
out.println(maxx + " " + maxy);
out.flush();
}
private static boolean isValid(int x, int y) {
return x>=0 && x<n && y>=0 && y<m;
}
/////////////////////////////////////////////////
// pre - written
/////////////////////////////////////////////////
private static void println(Object o) throws Exception {
System.out.println(o);
}
private static void exit(Object o) throws Exception {
println(o);
exit();
}
private static void exit() {
System.exit(0);
}
/////////////////////////////////
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class loser
{
static class InputReader {
public BufferedReader br;
public StringTokenizer token;
public InputReader(InputStream stream)
{
br=new BufferedReader(new InputStreamReader(stream),32768);
token=null;
}
public String next()
{
while(token==null || !token.hasMoreTokens())
{
try
{
token=new StringTokenizer(br.readLine());
}
catch(IOException e)
{
throw new RuntimeException(e);
}
}
return token.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
static class card{
long a;
int i;
public card(long a,int i)
{
this.a=a;
this.i=i;
}
}
static class sort implements Comparator<pair>
{
public int compare(pair o1,pair o2)
{
if(o1.a!=o2.a)
return (int)(o1.a-o2.a);
else
return (int)(o1.b-o2.b);
}
}
static void shuffle(long a[])
{
List<Long> l=new ArrayList<>();
for(int i=0;i<a.length;i++)
l.add(a[i]);
Collections.shuffle(l);
for(int i=0;i<a.length;i++)
a[i]=l.get(i);
}
/*static long gcd(long a,long b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}*/
/*static boolean valid(int i,int j)
{
if(i<4 && i>=0 && j<4 && j>=0)
return true;
else
return false;
}*/
static class pair{
int a,b;
public pair(int a,int b)
{
this.a=a;
this.b=b;
}
}
public static void main(String[] args)
{
InputReader sc=new InputReader(System.in);
int k=sc.nextInt();
int n=sc.nextInt();
int s=sc.nextInt();
int p=sc.nextInt();
long d=(long)Math.ceil((double)n/s);
if(d==0)
d=1;
d=k*d;
long ans=(long)Math.ceil((double)d/p);
System.out.println(ans);
}
}
|
constant
|
965_A. Paper Airplanes
|
CODEFORCES
|
import java.io.*;
import java.util.StringTokenizer;
public class Main {
static int[] a;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
a = sc.nextIntArray(n);
long inversions = divide(0, n - 1);
// out.println(inversions);
// System.err.println(Arrays.toString(a));
if (n == 5) out.println("Petr");
else {
if (n % 2 == 0) out.println(inversions % 2 == 0 ? "Petr" : "Um_nik");
else out.println(inversions % 2 != 0 ? "Petr" : "Um_nik");
}
out.flush();
out.close();
}
static long divide(int b, int e) {
if (b == e) return 0;
long cnt = 0;
int mid = b + e >> 1;
cnt += divide(b, mid);
cnt += divide(mid + 1, e);
cnt += merge(b, mid, e);
return cnt;
}
static long merge(int b, int mid, int e) {
long cnt = 0;
int len = e - b + 1;
int[] tmp = new int[len];
int i = b, j = mid + 1;
for (int k = 0; k < len; k++) {
if (i == mid + 1 || (j != e + 1 && a[i] > a[j])) {
tmp[k] = a[j++];
cnt += (mid + 1 - i);
} else tmp[k] = a[i++];
}
for (int k = 0; k < len; k++)
a[b + k] = tmp[k];
return cnt;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public 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 Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] ans = new double[n];
for (int i = 0; i < n; i++)
ans[i] = nextDouble();
return ans;
}
public short nextShort() throws IOException {
return Short.parseShort(next());
}
}
}
|
nlogn
|
986_B. Petr and Permutations
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main implements Runnable {
int n;
long[][] f;
boolean[][] e;
int bit(int value) {
return (1<<value);
}
void solve() throws IOException {
n = nextInt();
int m = nextInt();
f = new long[1<<n][n];
e = new boolean[n][n];
for (int i = 0; i < (1<<n); ++i) {
for (int j = 0; j < n; ++j) {
f[i][j] = -1;
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
f[bit(i)|bit(j)][j] = 0;
e[i][j] = false;
}
}
for (int i = 0; i < m; ++i) {
int u = nextInt()-1;
int v = nextInt()-1;
e[u][v] = true;
e[v][u] = true;
if (u < v) {
f[bit(u)|bit(v)][v] = 1;
}
else {
f[bit(v)|bit(u)][u] = 1;
}
}
long answer = 0;
for (int i = 1; i < (1<<n); ++i) {
int start = 0;
while (((1<<start)&i) == 0) {
++start;
}
int s = bit(start);
for (int nxt = start+1; nxt < n; ++nxt) {
int b = bit(nxt);
if ((b&i) > 0 && (b|s) != i) {
if (e[start][nxt]) {
answer += clc(i, nxt);
}
}
}
}
writer.print(answer>>1);
}
long clc(int maska, int last) {
if (f[maska][last] == -1) {
int first = 0;
while (((1<<first)&maska) == 0) {
++first;
}
f[maska][last] = 0;
for (int b = first+1; b < n; ++b) {
if ((bit(b)&maska)>0) {
if (e[b][last]) {
f[maska][last] += clc(maska^bit(last), b);
}
}
}
}
return f[maska][last];
}
public static void main(String[] args) throws InterruptedException {
new Thread(null, new Runnable() {
public void run() {
new Main().run();
}
},
"1",
1 << 25).start();
}
@Override
public void run() {
try {
boolean fromStandart = true;
reader = new BufferedReader(fromStandart ? new InputStreamReader(System.in) : new FileReader(INFILE));
writer = new PrintWriter(new BufferedWriter(fromStandart ? new OutputStreamWriter(System.out) : new FileWriter(OUTFILE)));
tokenizer = null;
solve();
writer.flush();
} catch (Exception error) {
error.printStackTrace();
System.exit(1);
}
}
static final String INFILE = "input.txt";
static final String OUTFILE = "output.txt";
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
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 nextString() throws IOException {
return reader.readLine();
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A558 {
static BufferedReader in = null;
static PrintWriter out = null;
static StringTokenizer st = new StringTokenizer("");
public static void main(String[] args) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String readString() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine(), " \n\r\t:");
} catch (Exception e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public static int readInt() {
return Integer.parseInt(readString());
}
public static long readLong() {
return Long.parseLong(readString());
}
private static int MAX_VALUE = Integer.MAX_VALUE - 10000000;
private static int[] dp;
private static int[] parents;
private static int[] powers;
private static int[] x;
private static int[] y;
private static int[][] dist;
private static int[] distFrom0;
private static void solve() throws IOException {
int x0 = readInt();
int y0 = readInt();
int n = readInt();
long time = System.currentTimeMillis();
x = new int[n];
y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = readInt() - x0;
y[i] = readInt() - y0;
}
dist = new int[n][n];
distFrom0 = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
}
}
for (int i = 0; i < n; i++) {
distFrom0[i] = x[i] * x[i] + y[i] * y[i];
}
powers = new int[n + 1];
powers[0] = 1;
for (int i = 1; i < n + 1; i++) {
powers[i] = powers[i - 1] * 2;
}
int maxMask = 1 << n;
dp = new int[maxMask];
parents = new int[maxMask];
Arrays.fill(dp, MAX_VALUE);
dp[0] = 0;
for (int i = 0; i < maxMask; i++) {
if (dp[i] != MAX_VALUE) {
int curMask = i;
int notUsed = 0;
for (int j = 0; j < n; j++) {
if ((curMask & powers[j]) == 0) {
notUsed = j;
break;
}
}
int mask = curMask | powers[notUsed];
for (int j = notUsed; j < n; j++) {
if ((powers[j] & curMask) == 0 || j == notUsed) {
int nextMask = mask | powers[j];
int minDist = dp[curMask] + distFrom0[notUsed] + dist[notUsed][j] + distFrom0[j];
if (dp[nextMask] > minDist) {
dp[nextMask] = minDist;
parents[nextMask] = curMask;
}
}
}
}
}
// System.err.println(((System.currentTimeMillis() - time)));
// brute(n, 0)
maxMask--;
out.println(dp[maxMask]);
while (maxMask != 0) {
out.print("0 ");
int[] diffBits = getBits(n, maxMask, parents[maxMask]);
for (int i = 1; i <= diffBits[0]; i++) {
out.print(diffBits[i] + 1 + " ");
}
maxMask = parents[maxMask];
}
out.print(0);
//System.err.println((System.currentTimeMillis() - time));
}
private static boolean hasBit(int x, int index) {
return (powers[index] & x) != 0;
}
private static int setBit(int x, int index) {
return (x | powers[index]);
}
private static int getDist(int xFrom, int yFrom, int xTo, int yTo) {
return (xTo - xFrom) * (xTo - xFrom) + (yTo - yFrom) * (yTo - yFrom);
}
private static int[] getBits(int n, int nextMask, int curMask) {
int[] res = new int[3];
for (int i = 0; i < n; i++) {
if (hasBit(nextMask, i) ^ hasBit(curMask, i)) {
res[++res[0]] = i;
}
}
return res;
}
private static void brute(int n, int mask) {
List<Integer> listNotTaken = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (!hasBit(mask, i)) {
listNotTaken.add(i);
}
}
for (int first : listNotTaken) {
int temp = setBit(mask, first);
for (int second : listNotTaken) {
int nextMask = setBit(temp, second);
int minDist = dp[mask] + getDist(0, 0, x[first], y[first]) + getDist(x[first], y[first], x[second], y[second]) + getDist(x[second], y[second], 0, 0);
if (dp[nextMask] > minDist) {
dp[nextMask] = minDist;
parents[nextMask] = mask;
brute(n, nextMask);
}
}
}
}
}
|
np
|
8_C. Looking for Order
|
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 B {
final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
final PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer tokenizer;
final int[][] d;
final int n;
final int[] time;
final Action[] actions;
private static final class Action {
int a;
int b;
public Action(int a) {
this.a = this.b = a;
}
public Action(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public String toString() {
if (a == b)
return " " + (a+1);
return " " + (a+1) + " " + (b+1);
}
}
private static final int dist(int x1, int y1, int x2, int y2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}
private final boolean in(int x, int set) {
return ((1 << x) & set) != 0;
}
private final int off(int x, int set) {
return (set ^ (set & (1 << x)));
}
private final int solve(int set) {
if (time[set] > 0)
return time[set];
int min = Integer.MAX_VALUE;
if (set == 0)
min = 0;
else {
int a;
for (a = 0; a < n; a++)
if (in(a, set))
break;
int subset = off(a, set);
int aux = 2 * d[a][a] + solve(subset);
if (aux < min) {
min = aux;
actions[set] = new Action(a);
}
for (int b = a + 1; b < n; b++)
if (in(b, subset)) {
aux = d[a][a] + d[b][b] + d[a][b] + solve(off(b, subset));
if (aux < min) {
min = aux;
actions[set] = new Action(a, b);
}
}
}
time[set] = min;
return min;
}
private B() throws IOException {
int bx = nextInt();
int by = nextInt();
n = nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextInt();
y[i] = nextInt();
}
reader.close();
d = new int[n][n];
for (int i = 0; i < n; i++) {
d[i][i] = dist(bx, by, x[i], y[i]);// |A|
for (int j = i + 1; j < n; j++)
d[i][j] = dist(x[i], y[i], x[j], y[j]);// |AB|
}
int set = 1 << n;
time = new int[set];
actions = new Action[set];
set--;
printer.println(solve(set));
printer.print("0");
while (set != 0) {
solve(set);
Action action = actions[set];
printer.print(action);
printer.print(" 0");
set = off(action.a, set);
set = off(action.b, set);
}
printer.println();
printer.close();
}
private final int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private final 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 {
new B();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class b {
public static void main(String[] args) throws Exception {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer st = new StringTokenizer(f.readLine());
int T = Integer.parseInt(st.nextToken());
for (int t = 0; t < T; t++) {
st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int sqrt = (int)Math.sqrt(n);
int sqrt2 = (int)Math.sqrt(n/2);
if (sqrt*sqrt == n && sqrt%2 == 0) {
out.println("YES");
} else if (2*sqrt2*sqrt2 == n) {
out.println("YES");
} else {
out.println("NO");
}
}
out.close();
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.util.Scanner;
public class GiveString23A {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String stroke = in.next();
char[] s = new char [stroke.length()];
for (int i=0;i<stroke.length();i++)
s[i]=stroke.charAt(i);
int dlina = 0;
for (int i=0;i<s.length-1;i++)
for (int j=i+1;j<s.length;j++)
for (int k=0;k<(s.length-j);k++)
if (s[i]==s[j])
{
int ik=i+k;
int jk = j+k;
if (s[ik]==s[jk])
{
if (dlina<k+1)
dlina=k+1;
}
else
break;
}
System.out.println(dlina);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* Created with IntelliJ IDEA.
* User: ira
* Date: 3/23/13
* Time: 12:19 PM
*/
public class B2 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
StringTokenizer tokenizer = new StringTokenizer(line);
long n = Long.parseLong(tokenizer.nextToken());
long k = Long.parseLong(tokenizer.nextToken());
if (n == 1){
System.out.println("0");
return;
}
if (n <= k){
System.out.println("1");
return;
}
long first = 0;
long end = k;
long mid;
while (first < end){
mid = first + (end - first)/2;
if (is_exist(n, k , mid - 1)){
end = mid;
} else {
first = mid + 1;
}
}
if (is_exist(n, k, end - 1)){
System.out.println((end ));
return;
}
System.out.println("-1");
return;
}
static boolean is_exist(long n, long k, long x){
long res = n - (k - 1 + k - x)* (k - 1 - (k - x) + 1)/2;
if (res <= k - x ){
return true;
}
return false;
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
//contest 23. You're Given A String
import java.util.*;
public class ProblemA
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
boolean con = false;
for( int i = input.length()-1; i > 0 ; i--)
{
for ( int j = 0; j+i< input.length(); j++ )
for( int k = j+1; k+i <= input.length(); k++ )
if( input.substring(j,j+i).equals( input.substring(k,k+i) ) )
{
System.out.print(i+"\n");
k = input.length()+1;
j = input.length();
i = -1;
con = true;
}
}
if( con == false )
System.out.print(0+"\n");
}
}
|
cubic
|
23_A. You're Given a String...
|
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;
public class Div1_503B {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int N = Integer.parseInt(reader.readLine());
printer.println("? 1");
printer.flush();
int v1 = Integer.parseInt(reader.readLine());
printer.println("? " + (1 + N / 2));
printer.flush();
int v2 = Integer.parseInt(reader.readLine());
if ((v1 + v2) % 2 != 0) {
printer.println("! -1");
printer.close();
return;
}
if (v1 == v2) {
printer.println("! 1");
printer.close();
return;
}
boolean less = v1 < v2;
int low = 1;
int high = (1 + N / 2);
while (low != high) {
int mid = (low + high) >> 1;
printer.println("? " + mid);
printer.flush();
int r1 = Integer.parseInt(reader.readLine());
int q2 = (mid + N / 2);
if (q2 > N) {
q2 -= N;
}
printer.println("? " + q2);
printer.flush();
int r2 = Integer.parseInt(reader.readLine());
if (r1 == r2) {
printer.println("! " + mid);
printer.close();
return;
}
if (r1 < r2 == less) {
low = mid + 1;
} else {
high = mid - 1;
}
}
printer.println("! " + low);
printer.close();
return;
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
//package baobab;
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
CIO io = new CIO();
try {
Csolver solver = new Csolver(io);
solver.solve();
} finally {
io.close();
}
}
}
class Csolver {
CIO io;
public Csolver(CIO io) {
this.io = io;
}
public void solve() {
int n = io.nextInt();
String input = io.next();
int[] count = new int[1000];
int pokemonsInRange = 0;
int answer = Integer.MAX_VALUE;
int a = 0;
int b = 0;
for (; b < n ; b++) {
char end = input.charAt(b);
if (count[end] == 0) {
pokemonsInRange++;
answer = Integer.MAX_VALUE;
}
count[end]++;
while (count[input.charAt(a)] > 1) {
count[input.charAt(a)]--;
a++;
}
answer = Math.min(answer, b-a+1);
}
io.println(answer);
}
private static class Pair implements Comparable<Pair> {
int id;
long val;
public Pair(long val, int id) {
this.val = val;
this.id = id;
}
@Override
public int compareTo(Pair o) {
if (this.val < o.val) return -1;
if (this.val > o.val) return 1;
return this.id - o.id;
}
}
private List<Integer>[] toGraph(CIO io, int n) {
List<Integer>[] g = new ArrayList[n+1];
for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
for (int i=1; i<=n-1; i++) {
int a = io.nextInt();
int b = io.nextInt();
g[a].add(b);
g[b].add(a);
}
return g;
}
}
class CIO extends PrintWriter {
private InputStreamReader r;
private static final int BUFSIZE = 1 << 15;
private char[] buf;
private int bufc;
private int bufi;
private StringBuilder sb;
public CIO() {
super(new BufferedOutputStream(System.out));
r = new InputStreamReader(System.in);
buf = new char[BUFSIZE];
bufc = 0;
bufi = 0;
sb = new StringBuilder();
}
private void fillBuf() throws IOException {
bufi = 0;
bufc = 0;
while(bufc == 0) {
bufc = r.read(buf, 0, BUFSIZE);
if(bufc == -1) {
bufc = 0;
return;
}
}
}
private boolean pumpBuf() throws IOException {
if(bufi == bufc) {
fillBuf();
}
return bufc != 0;
}
private boolean isDelimiter(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
}
private void eatDelimiters() throws IOException {
while(true) {
if(bufi == bufc) {
fillBuf();
if(bufc == 0) throw new RuntimeException("IO: Out of input.");
}
if(!isDelimiter(buf[bufi])) break;
++bufi;
}
}
public String next() {
try {
sb.setLength(0);
eatDelimiters();
int start = bufi;
while(true) {
if(bufi == bufc) {
sb.append(buf, start, bufi - start);
fillBuf();
start = 0;
if(bufc == 0) break;
}
if(isDelimiter(buf[bufi])) break;
++bufi;
}
sb.append(buf, start, bufi - start);
return sb.toString();
} catch(IOException e) {
throw new RuntimeException("IO.next: Caught IOException.");
}
}
public int nextInt() {
try {
int ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
ret *= 10;
ret -= (int)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
} else {
throw new RuntimeException("IO.nextInt: Invalid int.");
}
++bufi;
}
if(positive) {
if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextInt: Caught IOException.");
}
}
public long nextLong() {
try {
long ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret *= 10;
ret -= (long)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
} else {
throw new RuntimeException("IO.nextLong: Invalid long.");
}
++bufi;
}
if(positive) {
if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextLong: Caught IOException.");
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class Main {
public static void main(String [] args ) {
try{
String str;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedOutputStream bos = new BufferedOutputStream(System.out);
String eol = System.getProperty("line.separator");
byte [] eolb = eol.getBytes();
byte[] spaceb= " ".getBytes();
str = br.readLine();
int blank = str.indexOf( " ");
long l = Long.parseLong(str.substring(0,blank));
long r = Long.parseLong(str.substring(blank+1));
String one = "";
String two = "";
while(l>0) {
if((l%2)==0) {
one = "0".concat(one);
} else {
one = "1".concat(one);
}
l/=2;
}
while(r>0) {
if((r%2)==0) {
two = "0".concat(two);
} else {
two = "1".concat(two);
}
r/=2;
}
while(one.length()<60) {
one = "0".concat(one);
}
while(two.length()<60) {
two = "0".concat(two);
}
int iter = 0;
String xor = "";
boolean big = false;
boolean small = false;
while(one.charAt(iter) == two.charAt(iter)) {
xor = xor.concat("0");
iter++;
if(iter==60) {
break;
}
}
for(int i = iter ; i < 60 ; i++) {
xor = xor.concat("1");
}
bos.write(new BigInteger(xor,2).toString().getBytes());
bos.write(eolb);
bos.flush();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.awt.*;
import java.io.*;
import java.util.*;
public class Abc {
public static void main(String[] args) throws IOException {
// FastReader sc = new FastReader();
Scanner sc=new Scanner(new FileReader("input.txt"));
PrintWriter out=new PrintWriter(new File("output.txt"));
int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt();
boolean vis[][]=new boolean[n][m];
LinkedList<Integer> q=new LinkedList<>();
for (int i=0;i<k;i++){
int x=sc.nextInt()-1,y=sc.nextInt()-1;
vis[x][y]=true;
q.add(x);q.add(y);
}
int lastx=-1,lasty=-1;
int dirX[]={1,-1,0,0},dirY[]={0,0,1,-1};
while (!q.isEmpty()){
int x=q.removeFirst();
int y=q.removeFirst();
lastx=x;lasty=y;
for (int i=0;i<4;i++){
int newx=x+dirX[i],newy=y+dirY[i];
if (newx>=0 && newx<n && newy>=0 && newy<m && !vis[newx][newy]){
vis[newx][newy]=true;
q.add(newx);q.add(newy);
}
}
}
out.println((lastx+1)+" "+(lasty+1));
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.Scanner;
public class p23a {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char[] x = in.next().toCharArray();
int min = 0;
int max = x.length;
while(true) {
if(max-min == 1)
break;
int mid = (max+min)/2;
boolean eq = false;
for (int i = 0; i <= x.length-mid; i++) {
for (int j = 0; j <= x.length-mid; j++) {
if(j == i)
continue;
eq = true;
for (int k = 0; k < mid; k++) {
if(x[i+k] != x[j+k]) {
eq = false;
break;
}
}
if(eq)
break;
}
if(eq) break;
}
if(eq) {
min = mid;
} else {
max = mid;
}
}
System.out.println(min);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.Scanner;
public class C_1523 {
static Scanner input = new Scanner(System.in);
static int n;
public static void main(String[] args) {
int t = input.nextInt();
for(int test = 0; test < t; test++){
n = input.nextInt();
int num = input.nextInt();
if(num == 1){
n--;
recur("");
}else{
System.out.println("ERROR");
}
}
}
public static int recur(String before){
int num = 1;
System.out.println(before + num);
while(n > 0){
int val = input.nextInt();
n--;
if(val == 1){
val = recur(before + num + ".");
}
if(val == num + 1){
num++;
System.out.println(before + num);
}else{
return val;
}
}
return -1;
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.*;
import java.util.regex.*;
import java.text.*;
import java.math.*;
import java.io.*;
public class Mulitple
{
public static void main(String[] args) throws IOException
{
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String s = r.readLine();
System.out.println(num(s));
}
public static int num(String s)
{
int answer = 0;
Set<String> set = new HashSet<String>();
for(int j = s.length()-1; j>=1; j--)
{
for(int i = 0; i<s.length()-j+1; i++)
{
if(set.contains(s.substring(i,i+j)))
{
return s.substring(i,i+j).length();
}
else
{
set.add(s.substring(i,i+j));
}
}
}
return 0;
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
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();
String word = in.next();
int cnt[] = new int[1000];
int let = 0;
Set<Character> set = new TreeSet<>();
for (int i = 0; i < word.length(); i++) {
set.add(word.charAt(i));
}
int uniq = set.size();
int i = 0, j = -1;
int ans = Integer.MAX_VALUE;
while (i < N && j < N) {
while (j + 1 < N && let < uniq) {
j++;
if (cnt[word.charAt(j)] == 0) {
let++;
}
cnt[word.charAt(j)]++;
}
if (let == uniq)
ans = Math.min(ans, j - i + 1);
cnt[word.charAt(i)]--;
if (cnt[word.charAt(i)] == 0) let--;
i++;
}
out.println(ans);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.IOException;
import java.util.StringTokenizer;
/*
* @author Tnascimento
*/
public class MaeDosDragoes {
public static PrintWriter saida = new PrintWriter(System.out, false);
public static class Escanear {
BufferedReader reader;
StringTokenizer tokenizer;
public Escanear() {
this(new InputStreamReader(System.in));
}
public Escanear(Reader in) {
reader = new BufferedReader(in);
}
String proximo() {
if (tokenizer == null || !tokenizer.hasMoreElements()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
int proximoNum() {
return Integer.parseInt(proximo());
}
}
public static void main(String[] args) {
Escanear escanear = new Escanear();
int proximoInt = escanear.proximoNum();
long[] aux = new long[proximoInt];
double proximoDouble = escanear.proximoNum();
for(Integer i = 0; i < proximoInt; i++) {
for(Integer j =0; j < proximoInt; j++) {
Integer val = escanear.proximoNum();
if (val.equals(1) || i.equals(j)) {
aux[i] |= 1L << j;
}
}
}
int esquerda = proximoInt/2;
int direita = proximoInt - esquerda;
int maiorMascara = 1 << esquerda;
int[] depois = new int[1 << esquerda];
Integer mascara = 1;
while (mascara < maiorMascara) {
int mascaraAtual = mascara;
for(int j = 0; j < esquerda; j++) {
if (((1 << j) & mascara) > 0) {
mascaraAtual &= aux[j + direita] >> direita;
depois[mascara] = Math.max(depois[mascara], depois[mascara ^ (1 << j)]);
}
}
if (mascara.equals(mascaraAtual)) {
depois[mascara] = Math.max(depois[mascara],Integer.bitCount(mascara));
}
mascara++;
}
int auxiliar = 0;
int mascaraMaxima = 1 << direita;
for(int i = 0; i < mascaraMaxima; i++) {
int mascaraCorrente = i;
int mascaraValor = maiorMascara -1;
for(int j = 0; j < direita; j++) {
if (((1 << j) & i) > 0) {
mascaraCorrente &= (aux[j] & (mascaraMaxima-1));
mascaraValor &= aux[j] >> direita;
}
}
if (mascaraCorrente != i) continue;
auxiliar = Math.max(auxiliar, Integer.bitCount(i) + depois[mascaraValor]);
}
proximoDouble/=auxiliar;
saida.println(proximoDouble * proximoDouble * (auxiliar * (auxiliar-1))/2);
saida.flush();
}
}
|
np
|
839_E. Mother of Dragons
|
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<Long, ArrayList<Interval>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
long sum = 0;
for (int j = i; j < n; j++) {
sum += a[j];
if (map.containsKey(sum) == false) {
map.put(sum, new ArrayList<>());
}
ArrayList<Interval> arr = map.get(sum);
if (arr.isEmpty() || arr.get(arr.size() - 1).r < i) {
arr.add(new Interval(i, j));
} else if (arr.get(arr.size() - 1).r >= j) {
arr.set(arr.size() - 1, new Interval(i, j));
}
}
}
ArrayList<Interval> best = new ArrayList<>();
for (ArrayList<Interval> arr : map.values()) {
if (best.size() < arr.size()) {
best = arr;
}
}
out.println(best.size());
for (Interval i : best) {
out.println((i.l + 1) + " " + (i.r + 1));
}
}
class Interval {
int l;
int r;
Interval(int l, int r) {
this.l = l;
this.r = r;
}
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isWhitespace(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isWhitespace(c));
return res * sgn;
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
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<<26).start();
}
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt();
String a[]=new String[n];
String b[]=new String[n];
int freaa[][]=new int[5][4];
for (int i = 0; i <n ; i++) {
a[i]=sc.next();
int ll=a[i].length();
for (int j = 0; j <a[i].length() ; j++) {
if(a[i].charAt(j)=='X')
freaa[ll][0]++;
if(a[i].charAt(j)=='L')
freaa[ll][1]++;
if(a[i].charAt(j)=='M')
freaa[ll][2]++;
if(a[i].charAt(j)=='S')
freaa[ll][3]++;
}
}
int frebb[][]=new int[5][4];
for (int i = 0; i <n ; i++) {
b[i]=sc.next();
int ll=b[i].length();
for (int j = 0; j <b[i].length() ; j++) {
if(b[i].charAt(j)=='X')
frebb[ll][0]++;
if(b[i].charAt(j)=='L')
frebb[ll][1]++;
if(b[i].charAt(j)=='M')
frebb[ll][2]++;
if(b[i].charAt(j)=='S')
frebb[ll][3]++;
}
}
int ans=0;
for (int i = 1; i <5 ; i++) {
for (int j = 0; j <4 ; j++) {
if(freaa[i][j]<frebb[i][j]){
ans+=frebb[i][j]-freaa[i][j];
}
}
}
out.println(ans);
out.close();
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
/**
* @author abashkin
*/
public class Solution implements Runnable {
public static void main(String[] args) {
new Thread(new Solution()).start();
}
public void run() {
try{
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
solve();
pw.close();
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private void solve() throws Exception {
int n = nextInt();
pw.print(n + n / 2);
}
private BufferedReader br;
private PrintWriter pw;
private StringTokenizer tok;
private String next() throws Exception {
while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
private int nextInt() throws Exception {
return Integer.parseInt(next());
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.util.*;
public class A
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
long n=sc.nextLong();
if(n==0)
System.out.println(0);
else if(n%2==1)
System.out.println((n+1)/2);
else
System.out.println(n+1);
}
}
|
constant
|
979_A. Pizza, Pizza, Pizza!!!
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static int MOD = 1000000007;
// After writing solution, quick scan for:
// array out of bounds
// special cases e.g. n=1?
// npe, particularly in maps
//
// Big numbers arithmetic bugs:
// int overflow
// sorting, or taking max, after MOD
void solve() throws IOException {
int[] nT = ril(2);
int n = nT[0];
int T = nT[1];
int[][] tg = new int[n][];
for (int i = 0; i < n; i++) tg[i] = ril(2);
// dp[t][m][g] is the number of sequences possible to be formed from
// songs indicated by mask m, having total time t, and whose last song
// is genre g.
int[][][] dp = new int[T+1][1 << n][3];
for (int ti = 1; ti <= T; ti++) {
for (int mask = 1; mask <= (1 << n); mask++) {
// Iterate over the possible last song. It's genre will determine
// what the third dimension should be
for (int j = 0; j < n; j++) {
if (((1 << j) & mask) == 0) continue;
int time = tg[j][0];
int genre = tg[j][1]-1;
if (ti - time < 0) continue;
long base = dp[ti][mask][genre];
long add = 0;
if (ti - time == 0) {
// Base case: there is always one way regardless of what songs are available.
// The empty playlist
add = 1;
} else {
for (int g = 0; g < 3; g++) add += dp[ti-time][mask ^ (1 << j)][g];
add -= dp[ti-time][mask ^ (1 << j)][genre];
}
dp[ti][mask][genre] = (int) ((base + add) % MOD);
}
}
}
long ans = 0;
for (int g = 0; g < 3; g++) ans += dp[T][(1 << n)-1][g];
pw.println(ans % MOD);
}
// IMPORTANT
// DID YOU CHECK THE COMMON MISTAKES ABOVE?
// Template code below
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
Main m = new Main();
m.solve();
m.close();
}
void close() throws IOException {
pw.flush();
pw.close();
br.close();
}
int ri() throws IOException {
return Integer.parseInt(br.readLine().trim());
}
long rl() throws IOException {
return Long.parseLong(br.readLine().trim());
}
int[] ril(int n) throws IOException {
int[] nums = new int[n];
int c = 0;
for (int i = 0; i < n; i++) {
int sign = 1;
c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
nums[i] = x * sign;
}
while (c != '\n' && c != -1) c = br.read();
return nums;
}
long[] rll(int n) throws IOException {
long[] nums = new long[n];
int c = 0;
for (int i = 0; i < n; i++) {
int sign = 1;
c = br.read();
long x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
nums[i] = x * sign;
}
while (c != '\n' && c != -1) c = br.read();
return nums;
}
int[] rkil() throws IOException {
int sign = 1;
int c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
return ril(x);
}
long[] rkll() throws IOException {
int sign = 1;
int c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
return rll(x);
}
char[] rs() throws IOException {
return br.readLine().toCharArray();
}
void sort(int[] A) {
Random r = new Random();
for (int i = A.length-1; i > 0; i--) {
int j = r.nextInt(i+1);
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
Arrays.sort(A);
}
void printDouble(double d) {
pw.printf("%.16f", d);
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.util.Scanner;
public class MargariteBestPresent_1080B {
private static int f(int x) {
return (x%2==0)?x/2:(x-1)/2-x;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n,r,l;
n = sc.nextInt();
while(n-->0) {
l = sc.nextInt();
r = sc.nextInt();
System.out.println(f(r)-f(l-1));
}
sc.close();
}
}
|
constant
|
1080_B. Margarite and the best present
|
CODEFORCES
|
import java.util.Scanner;
/**
* Created by carolineshi on 3/30/17.
*/
public class Subtractions {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while(t != 0) {
int f = scan.nextInt();
int s = scan.nextInt();
System.out.println(ops(f, s));
t--;
}
}
public static int ops(int f, int s) {
int ops = 0;
while((f > 0) && (s > 0)) {
if(f > s) {
ops += f/s;
f %= s;
} else {
//f <= s
ops += s/f;
s %= f;
}
}
return ops;
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import static java.util.Arrays.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
public class A {
final int MOD = (int)1e9 + 7;
final double eps = 1e-12;
final int INF = (int)1e9;
public A () {
int N = sc.nextInt();
int K = sc.nextInt();
Long [] A = sc.nextLongs();
sort(A);
TreeSet<Long> S = new TreeSet<Long>();
for (long a : A) {
if (a % K == 0 && S.contains(a/K))
continue;
S.add(a);
}
int res = S.size();
exit(res);
}
////////////////////////////////////////////////////////////////////////////////////
/* Dear hacker, don't bother reading below this line, unless you want to help me debug my I/O routines :-) */
static MyScanner sc = new MyScanner();
static class MyScanner {
public String next() {
newLine();
return line[index++];
}
public char nextChar() {
return next().charAt(0);
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
line = null;
return readLine();
}
public String [] nextStrings() {
line = null;
return readLine().split(" ");
}
public char [] nextChars() {
return next().toCharArray();
}
public Integer [] nextInts() {
String [] L = nextStrings();
Integer [] res = new Integer [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Integer.parseInt(L[i]);
return res;
}
public Long [] nextLongs() {
String [] L = nextStrings();
Long [] res = new Long [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Long.parseLong(L[i]);
return res;
}
public Double [] nextDoubles() {
String [] L = nextStrings();
Double [] res = new Double [L.length];
for (int i = 0; i < L.length; ++i)
res[i] = Double.parseDouble(L[i]);
return res;
}
public String [] next (int N) {
String [] res = new String [N];
for (int i = 0; i < N; ++i)
res[i] = sc.next();
return res;
}
public Integer [] nextInt (int N) {
Integer [] res = new Integer [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInt();
return res;
}
public Long [] nextLong (int N) {
Long [] res = new Long [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLong();
return res;
}
public Double [] nextDouble (int N) {
Double [] res = new Double [N];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDouble();
return res;
}
public String [][] nextStrings (int N) {
String [][] res = new String [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextStrings();
return res;
}
public Integer [][] nextInts (int N) {
Integer [][] res = new Integer [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextInts();
return res;
}
public Long [][] nextLongs (int N) {
Long [][] res = new Long [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextLongs();
return res;
}
public Double [][] nextDoubles (int N) {
Double [][] res = new Double [N][];
for (int i = 0; i < N; ++i)
res[i] = sc.nextDoubles();
return res;
}
//////////////////////////////////////////////
private boolean eol() {
return index == line.length;
}
private String readLine() {
try {
return r.readLine();
} catch (Exception e) {
throw new Error(e);
}
}
private final BufferedReader r;
MyScanner () {
this(new BufferedReader(new InputStreamReader(System.in)));
}
MyScanner(BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine() {
if (line == null || eol()) {
line = readLine().split(" ");
index = 0;
}
}
}
static void print(Object o, Object... a) {
printDelim(" ", o, a);
}
static void cprint(Object o, Object... a) {
printDelim("", o, a);
}
static void printDelim (String delim, Object o, Object... a) {
pw.println(build(delim, o, a));
}
static void exit (Object o, Object... a) {
print(o, a);
exit();
}
static void exit () {
pw.close();
System.out.flush();
System.err.println("------------------");
System.err.println("Time: " + ((millis() - t) / 1000.0));
System.exit(0);
}
void NO() {
throw new Error("NO!");
}
////////////////////////////////////////////////////////////////////////////////////
static String build(String delim, Object o, Object... a) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : a)
append(b, p, delim);
return b.toString().trim();
}
static void append(StringBuilder b, Object o, String delim) {
if (o.getClass().isArray()) {
int L = Array.getLength(o);
for (int i = 0; i < L; ++i)
append(b, Array.get(o, i), delim);
} else if (o instanceof Iterable<?>) {
for (Object p : (Iterable<?>)o)
append(b, p, delim);
} else
b.append(delim).append(o);
}
////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
new A();
exit();
}
static void start() {
t = millis();
}
static PrintWriter pw = new PrintWriter(System.out);
static long t;
static long millis() {
return System.currentTimeMillis();
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
public class AAA {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] array = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
sum += array[i];
}
int counter = 0;
Arrays.sort(array);
int first = 0;
for (int j = n - 1; j >= 0; j--) {
first += array[j];
sum -= array[j];
counter++;
if (first > sum) {
break;
}
}
System.out.println(counter);
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main implements Runnable {
private void solution() throws IOException {
int n = in.nextInt();
int m = in.nextInt();
boolean[][] adj = new boolean[n][n];
long res = 0;
for (int i = 0; i < m; ++i) {
int x = in.nextInt();
int y = in.nextInt();
adj[x - 1][y - 1] = true;
adj[y - 1][x - 1] = true;
}
final long[][] dp = new long[1 << n][n];
for (int i = 0; i < n; ++i) {
for (int mask = 0; mask < (1 << (n - i)); ++mask) {
for (int j = 0; j < n - i; ++j) {
dp[mask][j] = 0;
}
}
dp[0][0] = 1;
for (int mask = 0; mask < (1 << (n - i)); ++mask) {
for (int j = 0; j < n - i; ++j) {
if (dp[mask][j] != 0) {
long am = dp[mask][j];
for (int k = 0; k < n - i; ++k) {
if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) {
dp[mask | (1 << k)][k] += am;
}
}
}
}
if (((mask >> 0) & 1) != 0) {
res += dp[mask][0];
}
}
}
out.println((res - m) / 2);
}
public void run() {
try {
solution();
in.reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private class Scanner {
BufferedReader reader;
StringTokenizer tokenizer;
public Scanner(Reader reader) {
this.reader = new BufferedReader(reader);
this.tokenizer = new StringTokenizer("");
}
public boolean hasNext() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String next = reader.readLine();
if (next == null) {
return false;
}
tokenizer = new StringTokenizer(next);
}
return true;
}
public String next() throws IOException {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public String nextLine() throws IOException {
tokenizer = new StringTokenizer("");
return reader.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
public static void main(String[] args) throws IOException {
new Thread(null, new Main(), "", 1 << 28).start();
}
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
Scanner in = new Scanner(new InputStreamReader(System.in));
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class CodeforcesRound159 {
/**
* @param args
*/
public static void main(String[] args)
{
Scanner kde = new Scanner(System.in);
int n =kde.nextInt(); //���������� ������� ��������
int m =kde.nextInt(); //���������� ���������
int k =kde.nextInt(); //���������� �������
ArrayList<Integer> count = new ArrayList<Integer>();
for (int i=0; i<n; i++ )
{
count.add(kde.nextInt()) ;
}
Collections.sort(count);
Collections.reverse(count);
if(m<=k)
{
System.out.println("0");
return;
}
m=m-k+1;
int res=0;
for(int i=0; i<n; i++ )
{
if(i!=0)
{
res+=count.get(i)-1;
}
else
{
res+=count.get(i);
}
if(res>=m)
{
System.out.println(i+1);
return;
}
}
System.out.println("-1");
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.ObjectInputStream.GetField;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.sound.sampled.ReverbType;
public class N718 {
static PrintWriter out;
static Scanner sc;
static ArrayList<int[]>q,w,x;
static ArrayList<Integer>adj[];
static HashSet<Integer>primesH;
static boolean prime[];
//static ArrayList<Integer>a;
static HashSet<Long>tmp;
static int[][][]dist;
static boolean[]v;
static int[]a,b,c,d;
static Boolean[][]dp;
static char[][]mp;
static int A,B,n,m,h,ans,sum;
//static String a,b;
static long oo=(long)1e9+7;
public static void main(String[]args) throws IOException {
sc=new Scanner(System.in);
out=new PrintWriter(System.out);
//A();
//B();
//C();
D();
//E();
//F();
//G();
out.close();
}
private static void A() throws IOException {
int t=ni();
while(t-->0) {
long l=nl();
if(l%2050!=0)ol(-1);
else {
long num=l/2050;
int cnt=0;
while(num>0) {
cnt+=num%10;
num/=10;
}
ol(cnt);
}
}
}
static void B() throws IOException {
int t=ni();
while(t-->0) {
int n=ni(),m=ni();
int[][]a=nmi(n,m);
PriorityQueue<int[]>pq=new PriorityQueue<int[]>((u,v)->u[0]-v[0]);
ArrayList<Integer>[]nums=new ArrayList[n];
for(int i=0;i<n;i++) {
//nums[i]=new ArrayList<Integer>();
for(int j=0;j<m;j++) {
///nums[i].add(a[i][j]);
pq.add(new int[] {a[i][j],i});
}
}
int[][]ans=new int[n][m];
for(int i=0;i<m;i++) {
int[]x=pq.poll();
ans[x[1]][i]=x[0];
}
int []indices=new int[n];
while(!pq.isEmpty()) {
int[]x=pq.poll();
int i=x[1];
while(ans[i][indices[i]]!=0) {
indices[i]++;
}
ans[i][indices[i]]=x[0];
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
out.print(ans[i][j]+" ");
}
ol("");
}
}
}
static void C() throws IOException{
int t=1;
while(t-->0) {
int n=ni();
a=nai(n);
int[][]ans=new int[n][n];
for(int i=0;i<n;i++)ans[i][i]=a[i];
for(int i=n-1;i>=0;i--) {
int j=i,k=i;
int cur=ans[i][i];
cur--;
while(cur>0) {
j++;
if(j>=n||ans[j][k]!=0) {
j--;
k--;
}
ans[j][k]=ans[i][i];
cur--;
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<=i;j++) {
out.print(ans[i][j]+" ");
}
ol("");
}
}
}
private static Boolean dp(int i, int j) {
if(j>sum/2)return false;
if(i==x.size()) {
return sum/2==j;
}
if(dp[i][j]!=null)return dp[i][j];
return dp[i][j]=dp(i+1,j+x.get(i)[0])||dp(i+1,j);
}
static boolean isPrime(long n) {
if(n==2)return true;
if(n<2||n%2==0)return false;
for(long i=3L;i*i<n;i+=2l) {
long rem=(n%i);
if(rem==0)return false;
}
return true;
}
static void D() throws IOException {
int t=1;
while(t-->0) {
int n=ni(),m=ni(),k=ni();
int[][]ans=new int[n][m];
dist=new int[n][m][4];
for(int i=0;i<n;i++)for(int j=0;j>m;j++)
Arrays.fill(dist[i][j], Integer.MAX_VALUE);
int x;
for(int i=0;i<n;i++) {
for(int j=0;j<m-1;j++) {
dist[i][j][2]=(x=ni());
dist[i][j+1][3]=x;
}
}
for(int i=0;i<n-1;i++) {
for(int j=0;j<m;j++) {
dist[i][j][1]=(x=ni());
dist[i+1][j][0]=x;
}
}
int[][]nans=new int[n][m];
if(k%2==1) {
for(int i=0;i<n;i++)Arrays.fill(ans[i], -1);
}else {
for(int ii=0;ii<k/2;ii++) {
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
nans[i][j]=Integer.MAX_VALUE;
if(i>0)
nans[i][j]=Math.min(nans[i][j], ans[i-1][j]+2*dist[i-1][j][1]);
if(i<n-1)
nans[i][j]=Math.min(nans[i][j], ans[i+1][j]+2*dist[i+1][j][0]);
if(j>0)
nans[i][j]=Math.min(nans[i][j], ans[i][j-1]+2*dist[i][j-1][2]);
if(j<m-1)
nans[i][j]=Math.min(nans[i][j], ans[i][j+1]+2*dist[i][j+1][3]);
}
}
int[][]tmp=ans;
ans=nans;
nans=tmp;
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
out.print(ans[i][j]+" ");
}
ol("");
}
}
}
private static int bfs(int i, int j,int k) {
boolean [][]vis=new boolean[dist.length][dist[0].length];
Queue<int[]>q=new LinkedList<int[]>();
int mn=Integer.MAX_VALUE;
q.add(new int[] {i,j,0,0});
int[]dx=new int[] {-1,1,0,0};
int[]dy=new int[] {0,0,1,-1};
while(!q.isEmpty()) {
int []x=q.poll();
vis[x[0]][x[1]]=true;
int c=x[2];
if(c>k/2)continue;
if(c>0&&k%c==0&&(k/c)%2==0) {
mn=Math.min(mn,x[3]*k/c );
}
for(int a=0;a<4;a++) {
int nx=x[0]+dx[a];
int ny=x[1]+dy[a];
if(valid(nx,ny)&&!vis[nx][ny]) {
q.add(new int[] {nx,ny,c+1,x[3]+dist[x[0]][x[1]][a]});
}
}
}
return mn;
}
private static boolean valid(int nx, int ny) {
return nx>=0&&nx<dist.length&&ny>=0&&ny<dist[0].length;
}
static int gcd (int a, int b) {
return b==0?a:gcd (b, a % b);
}
static void E() throws IOException {
int t=ni();
while(t-->0) {
}
}
static void F() throws IOException {
int t=ni();
while(t-->0) {
}
}
static void CC() throws IOException {
for(int kk=2;kk<21;kk++) {
ol(kk+" -------");
int n=kk;
int k=n-2;
int msk=1<<k;
int[]a=new int[k];
for(int i=0;i<a.length;i++)a[i]=i+2;
int mx=1;
int ms=0;
for(int i=1;i<msk;i++) {
long prod=1;
int cnt=0;
for(int j=0;j<a.length;j++) {
if(((i>>j)&1)!=0) {
prod*=a[j];
cnt++;
}
}
if(cnt>=mx&&prod%n==1) {
mx=cnt;
ms=i;
}
}
ol(mx==1?mx:mx+1);
out.print(1+" ");
long pr=1;
for(int j=0;j<a.length;j++) {
if(((ms>>j)&1)!=0) {
out.print(a[j]+" ");
pr*=a[j];
}
}
ol("");
ol("Prod: "+pr);
ol(n+"*"+((pr-1)/n)+" + "+1);
}
}
static int ni() throws IOException {
return sc.nextInt();
}
static double nd() throws IOException {
return sc.nextDouble();
}
static long nl() throws IOException {
return sc.nextLong();
}
static String ns() throws IOException {
return sc.next();
}
static int[] nai(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
return a;
}
static long[] nal(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextLong();
return a;
}
static int[][] nmi(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]=sc.nextInt();
}
}
return a;
}
static long[][] nml(int n,int m) throws IOException{
long[][]a=new long[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j]=sc.nextLong();
}
}
return a;
}
static void o(String x) {
out.print(x);
}
static void ol(String x) {
out.println(x);
}
static void ol(int x) {
out.println(x);
}
static void disp1(int []a) {
for(int i=0;i<a.length;i++) {
out.print(a[i]+" ");
}
out.println();
}
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 boolean hasNext() {return st.hasMoreTokens();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready(); }
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
/*
* Created on 17.05.2019
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author Wolfgang Weck
*/
public class C01Easy {
public static void main(String[] args) {
try (BufferedReader r = new BufferedReader(new InputStreamReader(System.in))) {
final String[] line = r.readLine().split(" ");
final int N = Integer.parseInt(line[0]), P = Integer.parseInt(line[1]);
final String[] numS = r.readLine().split(" ");
if (numS.length != N) throw new IllegalArgumentException();
final int[] n = new int[N];
int sum1 = 0, sum2 = 0;
for (int i = 0; i < N; i++) {
n[i] = Integer.parseInt(numS[i]) % P;
sum2 += n[i];
if (sum2 >= P) sum2 -= P;
}
int max = sum2;
for (int i = 0; i < N; i++) {
sum1 += n[i];
if (sum1 >= P) sum1 -= P;
sum2 -= n[i];
if (sum2 < 0) sum2 += P;
final int s = sum1 + sum2;
if (s > max) max = s;
}
System.out.println(max);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
|
linear
|
958_C1. Encryption (easy)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Ok_Simple {
static BufferedReader reader;
static StringTokenizer tokenizer;
static boolean am[][];
static long dp[][];
static int n;
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
int m;
n = NextInt();
m = NextInt();
am = new boolean[n][n];
dp = new long[n][1 << n];
for (int i = 0; i < n; ++i)
Arrays.fill(dp[i], -1);
for (int i = 0; i < m; ++i) {
int a = NextInt() - 1;
int b = NextInt() - 1;
am[a][b] = am[b][a] = true;
};
long res = 0;
for (int a = 0; a < n; ++a)
res += solve(a, (1 << a));
System.out.println(res / 2);
}
private static long solve(int b, int mask) {
int a = 0;
for (int i = 0 ;i < n; ++i)
if (((mask >> i) & 1) != 0)
{
a = i;
break;
}
if (dp[b][mask] >= 0)
return dp[b][mask];
long res = 0;
if (am[b][a] && Integer.bitCount(mask) > 2)
res = 1;
for (int i = a + 1; i < n; ++i)
if (((mask >> i) & 1) == 0 && am[b][i])
res += solve(i, mask ^ (1 << i));
return dp[b][mask] = res;
}
static int NextInt() throws NumberFormatException, IOException {
return Integer.parseInt(NextToken());
}
static double NextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(NextToken());
}
static long NextLong() throws NumberFormatException, IOException {
return Long.parseLong(NextToken());
}
static String NextToken() throws IOException {
while(tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.*;
public class PaintNumbers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = in.nextInt();
}
boolean[] visited = new boolean[n];
int min = Integer.MAX_VALUE;
int a = 0;
boolean cont = true;
while (cont) {
for (int i = 0; i < n; i++) {
if (!visited[i]) {
min = Math.min(min, nums[i]);
}
}
cont = false;
for (int i = 0; i < n; i++) {
if (!visited[i] && nums[i] % min == 0) {
cont = true;
visited[i] = true;
}
}
a++;
min = Integer.MAX_VALUE;
}
System.out.println(a - 1);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Map.Entry;
import static java.lang.Math.*;
public class C extends PrintWriter {
void run() {
int n = nextInt();
int r = nextInt();
int[] x = nextArray(n);
double[] y = new double[n];
Arrays.fill(y, r);
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
int dx = abs(x[i] - x[j]);
int sdy = 4 * r * r - dx * dx;
if (sdy >= 0) {
double dy = sqrt(sdy);
y[i] = max(y[i], y[j] + dy);
}
}
}
for (double v : y) {
printf(Locale.ENGLISH, "%.10f ", v);
}
}
boolean skip() {
while (hasNext()) {
next();
}
return true;
}
int[][] nextMatrix(int n, int m) {
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
matrix[i][j] = nextInt();
return matrix;
}
String next() {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String line = nextLine();
if (line == null) {
return false;
}
tokenizer = new StringTokenizer(line);
}
return true;
}
int[] nextArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
return reader.readLine();
} catch (IOException err) {
return null;
}
}
public C(OutputStream outputStream) {
super(outputStream);
}
static BufferedReader reader;
static StringTokenizer tokenizer = new StringTokenizer("");
static Random rnd = new Random();
static boolean OJ;
public static void main(String[] args) throws IOException {
OJ = System.getProperty("ONLINE_JUDGE") != null;
C solution = new C(System.out);
if (OJ) {
reader = new BufferedReader(new InputStreamReader(System.in));
solution.run();
} else {
reader = new BufferedReader(new FileReader(new File(C.class.getName() + ".txt")));
long timeout = System.currentTimeMillis();
while (solution.hasNext()) {
solution.run();
solution.println();
solution.println("----------------------------------");
}
solution.println("time: " + (System.currentTimeMillis() - timeout));
}
solution.close();
reader.close();
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {new Main().run();}
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
void run(){
int t=in.nextInt();
for(int i=0;i<t;i++) {
out.println(work());
}
out.flush();
}
long mod=1000000007;
long gcd(long a,long b) {
return b==0?a:gcd(b,a%b);
}
int work() {
int n=in.nextInt();
int m=in.nextInt();
int[][] A=new int[n][m];
int[][] B=new int[n][m];
int[][] R=new int[m][2];
for(int i=0;i<m;i++)R[i][1]=i;
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
A[i][j]=in.nextInt();
R[j][0]=Math.max(R[j][0], A[i][j]);
}
}
Arrays.sort(R,new Comparator<int[]>() {
public int compare(int[] arr1,int[] arr2) {
return arr2[0]-arr1[0];
}
});
for(int j=0;j<m;j++) {
int index=R[j][1];
for(int i=0;i<n;i++) {
B[i][j]=A[i][index];
}
}
m=Math.min(n, m);
int[][] dp=new int[m][1<<n];
int[][] rec=new int[m][1<<n];
for(int j=0;j<m;j++) {
for(int s=0;s<n;s++) {//转
for(int i=1;i<1<<n;i++) {
int sum=0;
for(int b=0;b<n;b++) {
if(((1<<b)&i)>0) {
sum+=B[(b+s)%n][j];
}
}
rec[j][i]=Math.max(sum, rec[j][i]);
}
}
}
for(int j=0;j<m;j++) {
for(int i=0;i<1<<n;i++) {
if(j==0) {
dp[j][i]=rec[j][i];
}else {
for(int p=i;p<1<<n;p++) {
p=p|i;
dp[j][p]=Math.max(dp[j][p], rec[j][i]+dp[j-1][p^i]);
}
}
}
}
return dp[m-1][(1<<n)-1];
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
if(st==null || !st.hasMoreElements())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner (System.in);
public static void main(String[] args) {
int n = sc.nextInt();
int k = sc.nextInt();
char str[][] = new char[5][n];
for(int i = 0;i < 4;i ++){
for(int j = 0;j < n;j ++)
str[i][j] = '.';
}
if(k % 2 == 0){
k /= 2;
for(int i = 1;i <= 2;i++){
for(int j = 1;j <= k;j++)
str[i][j] = '#';
}
}
else{
str[1][n / 2] = '#';
if(k != 1){
int tmp = n / 2;
if(k <= n - 2){
for(int i = 1;i<= (k - 1) / 2;i++){
str[1][i] = '#';
str[1][n - 1 - i] = '#';
}
}
else{
for(int i = 1;i <= n - 2;i++) str[1][i] = '#';
k -= n - 2;
for(int i = 1;i <= k/2;i++){
str[2][i] = '#';
str[2][n - 1 - i]='#';
}
}
}
}
System.out.println("YES");
for(int i = 0;i < 4;i ++){
System.out.println(str[i]);
}
}
}
|
linear
|
980_B. Marlin
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Date;
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = s.nextInt();
Arrays.sort(a);
int min = a[0];
if (a[0] == a[n-1]){
System.out.println("NO");
}else{
for(int i=1;;i++){
if (a[i] > min) {
System.out.println(a[i]);
break;
}
}
}
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.geom.*;
import java.util.regex.*;
public class Main implements Runnable {
StreamTokenizer ST;
PrintWriter out;
BufferedReader br;
int inf = 1000000000;
int nextInt() throws IOException{
ST.nextToken();
return (int)ST.nval;
}
long nextLong() throws IOException{
ST.nextToken();
return (long)ST.nval;
}
String next() throws IOException{
ST.nextToken();
return ST.sval;
}
double nextD() throws IOException{
ST.nextToken();
return ST.nval;
}
public static void main(String[] args) throws IOException {
new Thread(new Main()).start();
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new InputStreamReader(System.in, "ISO-8859-1"));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
ST = new StreamTokenizer(br);
solve();
out.close();
br.close();
}
catch (IOException e) {
throw new IllegalStateException(e);
}
}
String code(int x) {
x--;
StringBuilder sb = new StringBuilder();
while (x>0) {
int c = x%26;
if (x<10) sb.append((char)(c+'0')); else sb.append((char)('A'+c-10));
x /= 26;
}
if (sb.length()==0) sb.append("0");
return sb.toString();
}
StringBuilder sb = new StringBuilder();
public void solve() throws IOException {
int tt = Integer.parseInt(br.readLine());
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i=1; i<=10; i++) map.put(code(i), i);
while (tt-->0) {
String s = br.readLine();
if (s.matches("^[A-Z]+[0-9]+$")) {
int t = 0;
while (Character.isLetter(s.charAt(t))) t++;
int r = Integer.parseInt(s.substring(t));
s = s.substring(0, t);
int res = 0;
for (int c:s.toCharArray()) {
res *= 26;
res += c-'A'+1;
}
out.println("R"+r+"C"+res);
} else {
int t = s.indexOf('C');
int c = Integer.parseInt(s.substring(1, t));
int r = Integer.parseInt(s.substring(t+1));
//out.println(r+" "+c);
sb.setLength(0);
while (r>0) {
r--;
int ch = r%26;
sb.append((char)('A'+ch));
r /= 26;
}
sb = sb.reverse();
out.println(sb+""+c);
}
}
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
void solve() throws IOException {
int n=ni();
int k=ni();
boolean[] t = new boolean[n+1];
for(int i=2;i<=n;i++){
t[i]=false;
}
int p=2;
while(true){
int pointer=2;
while(pointer*p<=n){
t[pointer*p]=true;
pointer++;
}
boolean flag=false;
for(int i=p+1;i<=n;i++){
if(!t[i]){p=i;flag=true;break;}
}
if(!flag)break;
}
List<Integer> lst=new ArrayList<Integer>();
int countN=0;
for(int i=1;i<=n;i++){
if(!t[i]){lst.add(i);countN++; }
}
int count=0;
String resulPO="NO";
for(int i=2;i<countN;i++){
boolean result=false;
for(int j=0;j<i;j++){
if(lst.get(j)+lst.get(j+1)+1==lst.get(i)){
result=true;
//out.println(lst.get(j)+"+"+lst.get(j+1)+"+"+1+"=="+lst.get(i));
break;
}
}
if(result)count++;
}
if(count>=k)resulPO="YES";
else resulPO="NO";
out.print(resulPO);
}
public Main() throws IOException {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
String ns() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int ni() throws IOException {
return Integer.valueOf(ns());
}
long nl() throws IOException {
return Long.valueOf(ns());
}
double nd() throws IOException {
return Double.valueOf(ns());
}
public static void main(String[] args) throws IOException {
new Main();
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
public class Main {
static PrintWriter out;
static Reader in;
public static void main(String[] args) throws IOException {
input_output();
Main solver = new Main();
solver.solve();
out.close();
out.flush();
}
static int INF = (int)1e9;
static int MAXN = (int)4e5 + 5;
static int MOD = (int)1e9+7;
static int q, t, n, m, k;
static double pi = Math.PI;
void solve() throws IOException {
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
int[][] right = new int[n][m],
left = new int[n][m],
up = new int[n][m],
down = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m-1; j++) {
right[i][j] = in.nextInt();
left[i][j+1] = right[i][j];
}
}
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < m; j++) {
down[i][j] = in.nextInt();
up[i+1][j] = down[i][j];
}
}
if (k%2 == 1) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.print("-1 ");
}
out.println();
}
return;
}
int[][][] dp = new int[n][m][k+1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
for (int kk = 1; kk <= k; kk++) {
dp[i][j][kk] = INF;
}
}
}
for (int step = 2; step <= k; step+=2) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i != 0) {
dp[i][j][step] = Math.min(dp[i][j][step], dp[i-1][j][step-2]+up[i][j]*2);
}
if (i != n-1) {
dp[i][j][step] = Math.min(dp[i][j][step], dp[i+1][j][step-2]+down[i][j]*2);
}
if (j != 0) {
dp[i][j][step] = Math.min(dp[i][j][step], dp[i][j-1][step-2]+left[i][j]*2);
}
if (j != m-1) {
dp[i][j][step] = Math.min(dp[i][j][step], dp[i][j+1][step-2]+right[i][j]*2);
}
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.print(dp[i][j][k]+" ");
}
out.println();
}
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
static void input_output() throws IOException {
File f = new File("in.txt");
if (f.exists() && !f.isDirectory()) {
in = new Reader(new FileInputStream("in.txt"));
} else in = new Reader();
f = new File("out.txt");
if (f.exists() && !f.isDirectory()) {
out = new PrintWriter(new File("out.txt"));
} else out = new PrintWriter(System.out);
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
/*
*
* @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya)
* Dhirubhai Ambani Institute of Information And Communication Technology
*
*/
import java.util.*;
import java.io.*;
import java.lang.*;
public class Code1
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = in.nextInt();
long d = in.nextLong();
long[]a = new long[n];
for(int i=0;i<n;i++)
a[i] = in.nextLong();
int ans = 1;
for(int i=0;i<n-1;i++)
{
long x = a[i+1]-a[i];
if(x==2*d)
ans++;
else if(x>2*d)
ans+=2;
//System.out.println(ans);
}
ans++;
pw.print(ans);
pw.flush();
pw.close();
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static long mod = 1000000007;
public static int d;
public static int p;
public static int q;
public static int[] suffle(int[] a,Random gen)
{
int n = a.length;
for(int i=0;i<n;i++)
{
int ind = gen.nextInt(n-i)+i;
int temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
return a;
}
public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
public static HashSet<Integer> primeFactorization(int n)
{
HashSet<Integer> a =new HashSet<Integer>();
for(int i=2;i*i<=n;i++)
{
while(n%i==0)
{
a.add(i);
n/=i;
}
}
if(n!=1)
a.add(n);
return a;
}
public static void sieve(boolean[] isPrime,int n)
{
for(int i=1;i<n;i++)
isPrime[i] = true;
isPrime[0] = false;
isPrime[1] = false;
for(int i=2;i*i<n;i++)
{
if(isPrime[i] == true)
{
for(int j=(2*i);j<n;j+=i)
isPrime[j] = false;
}
}
}
public static int GCD(int a,int b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static long GCD(long a,long b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static void extendedEuclid(int A,int B)
{
if(B==0)
{
d = A;
p = 1 ;
q = 0;
}
else
{
extendedEuclid(B, A%B);
int temp = p;
p = q;
q = temp - (A/B)*q;
}
}
public static long LCM(long a,long b)
{
return (a*b)/GCD(a,b);
}
public static int LCM(int a,int b)
{
return (a*b)/GCD(a,b);
}
public static int binaryExponentiation(int x,int n)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static long binaryExponentiation(long x,long n)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static int modularExponentiation(int x,int n,int M)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x*x)%M;
n=n/2;
}
return result;
}
public static long modularExponentiation(long x,long n,long M)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x*x)%M;
n=n/2;
}
return result;
}
public static int modInverse(int A,int M)
{
return modularExponentiation(A,M-2,M);
}
public static long modInverse(long A,long M)
{
return modularExponentiation(A,M-2,M);
}
public static boolean isPrime(int n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n%2 == 0 || n%3 == 0)
return false;
for (int i=5; i*i<=n; i=i+6)
{
if (n%i == 0 || n%(i+2) == 0)
return false;
}
return true;
}
static class pair implements Comparable<pair>
{
Integer x, y;
pair(int x,int y)
{
this.x=x;
this.y=y;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString()
{
return x+" "+y;
}
public boolean equals(Object o)
{
if (o instanceof pair)
{
pair p = (pair)o;
return p.x == x && p.y == y ;
}
return false;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode();
}
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class C {
public static void main(String[] args) {
FastScanner in = new FastScanner();
int n = in.nextInt();
double r = in.nextInt();
double x[] = new double[n];
for(int i = 0; i < n; i++)
x[i] = in.nextDouble();
double y[] = new double[n];
y[0] = r;
for(int i = 1; i < n; i++){
double miny = r;
for(int j = 0; j < i; j++){
double dx = Math.abs(x[i]-x[j]);
if(dx > r*2) continue;
double yy = Math.sqrt(4*r*r-dx*dx);
miny = Math.max(miny, yy+y[j]);
}
y[i] = miny;
}
for(int i = 0; i < n; i++){
System.out.print(y[i]+" ");
}
}
static class FastScanner{
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try{
br = new BufferedReader(new FileReader(s));
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while(st == null ||!st.hasMoreElements()){
try {
st = new StringTokenizer(br.readLine());}
catch(IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
String next() {
return nextToken();
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.Scanner;
public class c {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int rad = in.nextInt();
int[] start = new int[num];
for(int i=0; i<num; i++)
start[i] = in.nextInt();
// If you can hack doubles that's dumb
double[] finalY = new double[num];
double hyp = rad*2;
for(int cur=0; cur<num; cur++){
double stopAt = rad;
for(int comp=0; comp<cur; comp++){
if(Math.abs(start[comp]-start[cur]) > rad*2) continue;
double base = Math.abs(start[comp]-start[cur]);
double ny = Math.sqrt(hyp*hyp - base*base) + finalY[comp];
stopAt = Math.max(ny, stopAt);
}
finalY[cur] = stopAt;
}
for(int i=0; i<num; i++)
System.out.print(finalY[i]+" ");
System.out.println();
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
//package learning;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class NitsLocal {
static ArrayList<String> s1;
static boolean[] prime;
static int n = (int)1e7;
static void sieve() {
Arrays.fill(prime , true);
prime[0] = prime[1] = false;
for(int i = 2 ; i * i <= n ; ++i) {
if(prime[i]) {
for(int k = i * i; k<= n ; k+=i) {
prime[k] = false;
}
}
}
}
public static void main(String[] args) {
InputReader sc = new InputReader(System.in);
prime = new boolean[n + 1];
sieve();
prime[1] = false;
long n = sc.nl();
long k = sc.nl();
long b = 2*n + 3;
long c = n*n - 2*k + n;
long q1 = (b + (long)Math.sqrt(b*b - 4*c))/2;
long q2 = (b - (long)Math.sqrt(b*b - 4*c))/2;
if(q1 >= q2 && q1 <= n)
w.println(q1);
else
w.println(q2);
w.close();
}
static int nextPowerOf2(int n)
{
int count = 0;
// First n in the below
// condition is for the
// case where n is 0
if (n > 0 && (n & (n - 1)) == 0)
return n;
while(n != 0)
{
n >>= 1;
count += 1;
}
return 1 << count;
}
static long sum1(int t1,int t2,int x,int []t)
{
int mid = (t2-t1+1)/2;
if(t1==t2)
return 0;
else
return sum1(t1,mid-1,x,t) + sum1(mid,t2,x,t);
}
static String replace(String s,int a,int n)
{
char []c = s.toCharArray();
for(int i=1;i<n;i+=2)
{
int num = (int) (c[i] - 48);
num += a;
num%=10;
c[i] = (char) (num+48);
}
return new String(c);
}
static String move(String s,int h,int n)
{
h%=n;
char []c = s.toCharArray();
char []temp = new char[n];
for(int i=0;i<n;i++)
{
temp[(i+h)%n] = c[i];
}
return new String(temp);
}
public static int ip(String s){
return Integer.parseInt(s);
}
static class multipliers implements Comparator<Long>{
public int compare(Long a,Long b) {
if(a<b)
return 1;
else if(b<a)
return -1;
else
return 0;
}
}
static class multipliers1 implements Comparator<Student>{
public int compare(Student a,Student b) {
if(a.y<b.y)
return 1;
else if(b.y<a.y)
return -1;
else
{
if(a.id < b.id)
return 1;
else if(b.id<a.id)
return -1;
else
return 0;
//return 0;
}
}
}
// Java program to generate power set in
// lexicographic order.
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nia(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public String rs() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
static PrintWriter w = new PrintWriter(System.out);
static class Student
{
int id;
//int x;
int y;
//long z;
Student(int id,int y)
{
this.id = id;
//this.x = x;
//this.s = s;
this.y = y;
// this.z = z;
}
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main{
public static boolean isPrime(long num){
int divisor = 2;
boolean bandera = true;
while(bandera && divisor<num) //ponemos el while con su condicion en este caso si bandera
{
if (num%divisor==0) {
bandera=false;
break;
}else{
divisor++; //igual si el divisor llego al numero q se capturo este sera primo
}
}
return bandera;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int uno = 4;
int dos = n-4;
while(isPrime(dos) || isPrime(uno)){
dos--;
uno++;
}
System.out.println(uno+" "+dos);
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
/**
* 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);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[][] graph = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
graph[i][j] = in.nextInt();
}
int[][] mn1 = new int[n][n];
int[][] mn2 = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
int min_val = Integer.MAX_VALUE;
for (int k = 0; k < m; k++)
min_val = Math.min(min_val, Math.abs(graph[i][k] - graph[j][k]));
mn1[i][j] = min_val;
min_val = Integer.MAX_VALUE;
for (int k = 0; k < m - 1; k++) {
min_val = Math.min(min_val, Math.abs(graph[i][k] - graph[j][k + 1]));
}
mn2[i][j] = min_val;
}
int[][] dp = new int[(1 << (n + 2))][n];
int ans = 0;
for (int i = 0; i < n; i++) {
for (int[] temp : dp)
Arrays.fill(temp, -1);
for (int j = 0; j < n; j++) {
dp[1 << j][j] = (j == i ? Integer.MAX_VALUE : 0);
// dp[1 << j][j] = (j == i ? 0: Integer.MAX_VALUE );
}
for (int j = 0; j < n; j++) {
ans = Math.max(ans, Math.min(mn2[j][i], calc((1 << n) - 1, j, dp, mn1, n)));
}
}
out.println(ans);
}
public int calc(int mask, int v, int[][] dp, int[][] mn1, int n) {
// System.out.println(mask+","+v);
if (dp[mask][v] != -1)
return dp[mask][v];
dp[mask][v] = 0;
for (int u = 0; u < n; u++) {
if (u != v && (((mask >> u) & 1) == 1))
dp[mask][v] = Math.max(dp[mask][v], Math.min(mn1[u][v], calc(mask ^ (1 << v), u, dp, mn1, n)));
}
return dp[mask][v];
}
}
}
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
import java.util.stream.IntStream;
public class B {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
Solver solver = new Solver();
solver.solve(in, out);
out.close();
}
static class Solver {
int n;
int n2;
InputReader in;
PrintWriter out;
public void solve(InputReader in, PrintWriter out) {
this.in = in;
this.out = out;
n = in.readInt();
n2 = n/2;
int res = find();
out.print("! ");
out.println(res);
}
public int find() {
if (n%4 != 0) return -1;
int c = compare(0);
if (c == 0) return 1;
int s = 1;
int f = n2-1;
if (c > 0) {
s = n2+1;
f = n-1;
}
while (s <= f) {
int m = (s+f)/2;
int v = compare(m);
if (v == 0) return m+1;
else if (v < 0) s = m+1;
else f = m-1;
}
return -1;
}
public int compare(int z) {
out.print("? ");
out.println(z+1);
out.flush();
int r1 = in.readInt();
out.print("? ");
out.println((z+n2)%n+1);
out.flush();
int r2 = in.readInt();
return r1-r2;
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
}
public String read() {
try {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return tokenizer.nextToken();
}
public int readInt() {
return Integer.parseInt(read());
}
public long readLong() {
return Long.parseLong(read());
}
public void readIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readInt();
}
}
}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.util.Scanner;
/**
* @author Son-Huy TRAN
*
*/
public class P15A_CottageVillage {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int t = scanner.nextInt();
scanner.nextLine();
int[] x = new int[n];
int[] a = new int[n];
for (int i = 0; i < n; i++) {
x[i] = scanner.nextInt();
a[i] = scanner.nextInt();
scanner.nextLine();
}
scanner.close();
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (x[i] > x[j]) {
swap(x, i, j);
swap(a, i, j);
}
}
}
int countPositions = 2;
for (int i = 1; i < n; i++) {
double left = x[i - 1] + a[i - 1] * 1.0 / 2;
double right = x[i] - a[i] * 1.0 / 2;
double length = right - left;
if (length == (double) t) {
countPositions++;
} else if (length > t) {
countPositions += 2;
}
}
System.out.println(countPositions);
}
private static void swap(int[] numbers, int i, int j) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
//package round227;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class D {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni();
int[] from = new int[m];
int[] to = new int[m];
for(int i = 0;i < m;i++){
from[i] = ni()-1;
to[i] = ni()-1;
}
int[] nfrom = new int[m];
int[] nto = new int[m];
int min = 999999999;
for(int i = 0;i < n;i++){
int p = 0;
for(int j = 0;j < m;j++){
if(from[j] != i && to[j] != i){
nfrom[p] = from[j];
nto[p] = to[j];
p++;
}
}
int[][] g = packD(n, nfrom, nto, p);
int mat = doBipartiteMatchingHKNoRec(g, n);
int ch = p - mat + (n-1-mat);
ch += 2*n-1 - (m - p);
min = Math.min(min, ch);
}
out.println(min);
}
public static int doBipartiteMatchingHKNoRec(int[][] g, int m)
{
int n = g.length;
if(n == 0)return 0;
int[] from = new int[m];
int[] to = new int[n];
Arrays.fill(to, -1);
Arrays.fill(from, n);
int[] d = new int[n+1];
int mat = 0;
int[] stack = new int[n+1];
int[] adjind = new int[n+1];
while(true){
Arrays.fill(d, -1);
int[] q = new int[n];
int r = 0;
for(int i = 0;i < n;i++){
if(to[i] == -1){
d[i] = 0;
q[r++] = i;
}
}
for(int p = 0;p < r;p++) {
int cur = q[p];
for(int adj : g[cur]){
int nex = from[adj];
if(d[nex] == -1) {
if(nex != n)q[r++] = nex;
d[nex] = d[cur] + 1;
}
}
}
if(d[n] == -1)break;
for(int i = 0;i < n;i++){
if(to[i] == -1){
int sp = 1;
stack[0] = i;
adjind[0] = 0;
boolean prevB = false;
outer:
while(sp >= 1){
int cur = stack[sp-1];
if(cur == n){
prevB = true;
sp--;
continue;
}
for(;adjind[sp-1] < 2*g[cur].length;){
int adj = g[cur][adjind[sp-1]/2];
if(adjind[sp-1] % 2 == 0){
int nex = from[adj];
if(d[nex] == d[cur] + 1){
stack[sp] = nex;
adjind[sp] = 0;
adjind[sp-1]++;
sp++;
continue outer;
}else{
adjind[sp-1]+=2;
}
}else{
if(prevB){
to[cur] = adj;
from[adj] = cur;
prevB = true;
sp--;
continue outer;
}
adjind[sp-1]++;
}
}
d[cur] = -1;
prevB = false;
sp--;
}
if(prevB)mat++;
}
}
}
return mat;
}
public static int[][] packD(int n, int[] from, int[] to, int sup)
{
int[][] g = new int[n][];
int[] p = new int[n];
for(int i = 0;i < sup;i++)p[from[i]]++;
for(int i = 0;i < n;i++)g[i] = new int[p[i]];
for(int i = 0;i < sup;i++){
g[from[i]][--p[from[i]]] = to[i];
}
return g;
}
void run() throws Exception
{
// int n = 500, m = 1000;
// Random gen = new Random();
// StringBuilder sb = new StringBuilder();
// sb.append(n + " ");
// sb.append(m + " ");
// boolean[][] g = new boolean[n][n];
// for(int i = 0;i < m;i++){
// while(true){
// int r = gen.nextInt(n);
// int c = gen.nextInt(n);
// if(!g[r][c]){
// g[r][c] = true;
// break;
// }
// }
// }
// for(int i = 0;i < n;i++){
// for(int j = 0;j < n;j++){
// if(g[i][j]){
// sb.append((i+1) + " ");
// sb.append((j+1) + " ");
// }
// }
// }
// 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 D().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
cubic
|
387_D. George and Interesting Graph
|
CODEFORCES
|
import java.util.*;
public class A
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if(n % 2 == 1)
{
System.out.println(9 + " " + (n - 9));
}
else
{
System.out.println(4 + " " + (n - 4));
}
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.*;
public class A23 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
for(int length = s.length(); length > 0; length--) {
for(int start = 0; start + length <= s.length(); start++) {
String test = s.substring(start, start+length);
if(s.indexOf(test) != s.lastIndexOf(test)) {
System.out.println(length);
return;
}
}
}
System.out.println(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.