src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Map;
import java.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;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int n;
long neededSum;
long[] sums;
Map<Long, Integer> where;
public void solve(int testNumber, FastScanner in, PrintWriter out) {
n = in.nextInt();
int[][] a = new int[n][];
neededSum = 0;
sums = new long[n];
for (int i = 0; i < n; i++) {
int k = in.nextInt();
a[i] = new int[k];
for (int j = 0; j < k; j++) {
a[i][j] = in.nextInt();
neededSum += a[i][j];
sums[i] += a[i][j];
}
}
if (neededSum % n != 0) {
out.println("No");
return;
}
neededSum /= n;
where = new HashMap<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < a[i].length; j++) {
where.put((long) a[i][j], i);
}
}
Entry[][] cycleSol = new Entry[1 << n][];
List<Entry> sol = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int x : a[i]) {
search(i, i, x, x, 0, 0, sol, cycleSol);
}
}
boolean[] can = new boolean[1 << n];
int[] via = new int[1 << n];
can[0] = true;
for (int mask = 0; mask < 1 << n; mask++) {
for (int submask = mask; submask > 0; submask = (submask - 1) & mask) {
if (cycleSol[submask] != null && can[mask ^ submask]) {
can[mask] = true;
via[mask] = submask;
}
}
}
if (!can[(1 << n) - 1]) {
out.println("No");
return;
}
int[][] ans = new int[n][2];
for (int mask = (1 << n) - 1; mask > 0; ) {
int sm = via[mask];
mask ^= sm;
for (Entry e : cycleSol[sm]) {
ans[e.from][0] = e.what;
ans[e.from][1] = e.to + 1;
}
}
out.println("Yes");
for (int i = 0; i < n; i++) {
out.println(ans[i][0] + " " + ans[i][1]);
}
}
private void search(int start, int cur, long fromStart, long fromCur, int hasIn, int hasOut, List<Entry> sol, Entry[][] cycleSol) {
for (int i = start; i < n; i++) {
if ((hasIn & (1 << i)) > 0) {
continue;
}
if ((hasOut & (1 << cur)) > 0) {
continue;
}
long fromI = sums[i] + fromCur - neededSum;
Integer w = where.get(fromI);
if (w == null || w != i) {
continue;
}
sol.add(new Entry(cur, i, (int) fromCur));
int nHasIn = hasIn | (1 << i);
int nHasOut = hasOut | (1 << cur);
if (i == start && fromI == fromStart) {
cycleSol[nHasOut] = sol.toArray(new Entry[0]);
}
search(start, i, fromStart, fromI, nHasIn, nHasOut, sol, cycleSol);
sol.remove(sol.size() - 1);
}
}
class Entry {
int from;
int to;
int what;
Entry(int from, int to, int what) {
this.from = from;
this.to = to;
this.what = what;
}
public String toString() {
return from + " " + to + " " + what;
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
np
|
1242_C. Sum Balance
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
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.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main
{
private static BufferedReader in;
private static BufferedWriter out;
public static void main(String[] args) throws NumberFormatException, IOException
{
// streams
boolean file = false;
if (file)
in = new BufferedReader(new FileReader("input.txt"));
else
in = new BufferedReader(new InputStreamReader(System.in));
// out = new BufferedWriter(new OutputStreamWriter(System.out));
out = new BufferedWriter(new FileWriter("output.txt"));
StringTokenizer tok;
int n = Integer.parseInt(in.readLine());
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.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.InputMismatchException;
public class R113_D2_A {
public static void main(String[] args) throws NumberFormatException,
IOException {
// BufferedReader in = new BufferedReader(new
// InputStreamReader(System.in));
InputReader4 in = new InputReader4(System.in);
int n = in.readInt();
int k = in.readInt();
p[] inp = new p[n];
for (int i = 0; i < inp.length; i++) {
inp[i] = new p(in.readInt(), in.readInt());
}
Arrays.sort(inp);
for (int i = 0; i < inp.length;) {
int j = i + 1;
while (j < inp.length && inp[i].x == inp[j].x
&& inp[i].y == inp[j].y) {
j++;
}
int num = j - i;
if (k <= num) {
System.out.println(num);
return;
} else
k -= num;
i = j;
}
}
static class p implements Comparable<p> {
int x;
int y;
public p(int a, int b) {
x = a;
y = b;
}
public int compareTo(p o) {
if (x > o.x)
return -1;
if (x < o.x)
return 1;
return y - o.y;
}
}
static class InputReader4 {
private InputStream stream;
private byte[] buf = new byte[1000];
private int curChar, numChars;
public InputReader4(InputStream stream) {
this.stream = stream;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == '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;
}
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class p2 {
final static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static String ss() throws IOException {return br.readLine();}
private static int stoi(String x) {return Integer.parseInt(x);}
private static int si() throws IOException {return stoi(ss());}
private static long sl() throws IOException {return Long.parseLong(ss());}
private static int[] sia(int len) throws IOException {
int[] ret = new int[len];
final StringTokenizer st = new StringTokenizer(ss());
for (int i = 0; i < len; ++i) {ret[i] = stoi(st.nextToken());}
return ret;
}
private static long[] sla(int len) throws IOException {
long[] ret = new long[len];
final StringTokenizer st = new StringTokenizer(ss());
for (int i = 0; i < len; ++i) {ret[i] = Long.parseLong(st.nextToken());}
return ret;
}
public static void main (final String[] args) throws IOException {
//goal is to always be higher
Set<Integer> poss = new HashSet<>();
for (int i = 1; 2 * (i*i) <= 1000000000; ++i) {
poss.add(2 * (i*i));
poss.add(4 * (i*i));
}
int t = si();
for (int i = 0; i < t; ++i) {
int n = si();
if (poss.contains(n)) System.out.println("YES");
else System.out.println("NO");
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class B {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
int[] level;
int[] loyal;
double ans;
int n, k, plLev, needVotes;
double check() {
//System.err.println(Arrays.toString(loyal));
double res = 0;
for (int mask = 0; mask < (1 << n); mask++) {
double prob = 1;
int vote = 0;
int kill = 0;
for (int i = 0; i < n; i++)
if (((mask >> i) & 1) == 1) {
prob *= loyal[i] / 100.0;
vote++;
}
else {
prob *= 1 - loyal[i] / 100.0;
kill += level[i];
}
if (vote >= needVotes)
res += prob;
else
res += prob * plLev / (kill + plLev);
}
return res;
}
void go(int ind, int candy) {
if (ind == n) {
ans = Math.max(ans, check());
return;
}
for (int i = 0; i <= candy; i++) {
loyal[ind] += 10 * i;
if (loyal[ind] > 100) {
loyal[ind] -= 10 * i;
break;
}
go(ind + 1, candy - i);
loyal[ind] -= 10 * i;
}
}
void solve() throws IOException {
n = nextInt();
k = nextInt();
plLev = nextInt();
needVotes = n / 2 + 1;
ans = 0;
level = new int[n];
loyal = new int[n];
for (int i = 0; i < n; i++) {
level[i] = nextInt();
loyal[i] = nextInt();
}
go(0, k);
out.printf("%.12f", ans);
}
void inp() throws IOException {
Locale.setDefault(Locale.US);
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new B().inp();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return "0";
}
}
return st.nextToken();
}
String nextString() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return "0";
}
}
return st.nextToken("\n");
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class B {
static int n, t[], g[], MOD = (int) 1e9 + 7;
static int[][][] memo1, memo2[], memo3[];
static int dp1(int idx, int remCnt, int remSum) {
if (idx == n)
return remSum == 0 && remCnt == 0 ? 1 : 0;
if (remCnt < 0 || remSum < 0)
return 0;
if (memo1[idx][remCnt][remSum] != -1)
return memo1[idx][remCnt][remSum];
int ans = dp1(idx + 1, remCnt, remSum);
if (g[idx] == 0) {
ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]);
if (ans >= MOD)
ans -= MOD;
}
return memo1[idx][remCnt][remSum] = ans;
}
static int dp2(int idx, int remCnt1, int remCnt2, int remSum) {
if (idx == n)
return remSum == 0 && remCnt1 == 0 && remCnt2 == 0 ? 1 : 0;
if (remSum < 0 || remCnt1 < 0 || remCnt2 < 0)
return 0;
if (memo2[idx][remCnt1][remCnt2][remSum] != -1)
return memo2[idx][remCnt1][remCnt2][remSum];
int ans = dp2(idx + 1, remCnt1, remCnt2, remSum);
if (g[idx] == 1)
ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]);
else if (g[idx] == 2)
ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]);
return memo2[idx][remCnt1][remCnt2][remSum] = ans;
}
private static int dp3(int cnt0, int cnt1, int cnt2, int last) {
if (cnt0 + cnt1 + cnt2 == 0)
return 1;
if (memo3[last][cnt0][cnt1][cnt2] != -1)
return memo3[last][cnt0][cnt1][cnt2];
long ans = 0;
if (cnt0 > 0 && last != 0)
ans += dp3(cnt0 - 1, cnt1, cnt2, 0);
if (cnt1 > 0 && last != 1)
ans += dp3(cnt0, cnt1 - 1, cnt2, 1);
if (cnt2 > 0 && last != 2)
ans += dp3(cnt0, cnt1, cnt2 - 1, 2);
return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD);
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
int[] fac = new int[n + 1];
t = new int[n];
g = new int[n];
int[] cnt = new int[3];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = (int) (i * 1L * fac[i - 1] % MOD);
int T = sc.nextInt();
for (int i = 0; i < n; i++) {
t[i] = sc.nextInt();
g[i] = sc.nextInt() - 1;
cnt[g[i]]++;
}
memo1 = new int[n][cnt[0] + 1][T + 1];
memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1];
memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= cnt[0]; j++)
Arrays.fill(memo1[i][j], -1);
for (int j = 0; j <= cnt[1]; j++)
for (int k = 0; k <= cnt[2]; k++)
Arrays.fill(memo2[i][j][k], -1);
}
for (int i = 0; i < 4; i++)
for (int j = 0; j <= cnt[0]; j++)
for (int k = 0; k <= cnt[1]; k++)
Arrays.fill(memo3[i][j][k], -1);
int ans = 0;
for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++)
for (int sum0 = 0; sum0 <= T; sum0++)
for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++)
for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) {
long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD;
ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD;
ways *= fac[cnt0];
ways %= MOD;
ways *= fac[cnt1];
ways %= MOD;
ways *= fac[cnt2];
ways %= MOD;
ans += ways;
if (ans >= MOD)
ans -= MOD;
}
out.println(ans);
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
}
|
cubic
|
1185_G2. Playlist for Polycarp (hard version)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Codechef{
static int max=Integer.MIN_VALUE;
static int res=0;
static int[] checkMax(int arr[],int j){
int sum=0;
int x=arr[j];
while(x!=0){
if(j+1==15){
j=0;
}else{
arr[j+1]=arr[j+1]+1;
}
// if(arr[j+1]%2==0){
// sum=sum+arr[j+1];
// if(sum>=max){
// max=sum;
// }
// }
x--;
j++;
}
return arr;
}
public static void main(String []args){
Scanner sc = new Scanner (System.in);
long a [] = new long [14];
long b [] = new long [14];
long p,q,r,s,max = 0;
for(int i = 0; i < 14; i++) a[i] = sc.nextInt();
for(int i = 0; i < 14; i++){
p = a[i]%14;
q = a[i]/14;
r = 0;
s = 0;
for(int j = 0; j < 14; j++) b[j] = a[j];
b[i] = 0;
int j = (i+1)%14;
for(; r < p; r++) {
b[j]++;
j=(j+1)%14;
}
for( j = 0; j < 14; j++) {
b[j] += q;
if(b[j] % 2 == 0) s+= b[j];
}
max = Math.max(max,s);
}
System.out.println(max);
}
}
|
constant
|
975_B. Mancala
|
CODEFORCES
|
import java.util.Scanner;
public class Contest25_A {
static int[] parity;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numberEntries = scan.nextInt();
scan.nextLine();
String[] numbers = scan.nextLine().split(" ");
numbers = parity(numbers);
int evenOdd = evenOdd(parity);
for (int i = 0; i < parity.length; i++) {
if (parity[i] == evenOdd) {
System.out.println(i + 1);
System.exit(0);
}
}
}
public static int evenOdd(int[] parity) {
/*
* Determines what I should be looking for
* Return 0 if even
* Return 1 if odd
*/
int numberOnes = 0;
int numberZeroes = 0;
int one = parity[0];
int two = parity[1];
int three = parity[2];
if (one == 1)
numberOnes++;
else
numberZeroes++;
if (two == 1)
numberOnes++;
else
numberZeroes++;
if (three == 1)
numberOnes++;
else
numberZeroes++;
if (numberOnes >= 2)
return 0;
else
return 1;
}
public static String[] parity(String[] numbers) {
parity = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
parity[i] = Integer.parseInt(numbers[i]) % 2;
numbers[i] = Integer.toString(parity[i]);
}
return numbers;
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class ProblemE_16 {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException{
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException{
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException{
return Integer.parseInt(readString());
}
long readLong() throws IOException{
return Long.parseLong(readString());
}
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
public static void main(String[] args){
new ProblemE_16().run();
}
public void run(){
try{
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = "+(t2-t1));
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
void solve() throws IOException{
int n = readInt();
double[][] a = new double[n][n];
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
a[i][j] = readDouble();
}
}
double[] d = new double[1<<n];
d[(1 << n) - 1] = 1;
for (int i = (1 << n) - 1; i > 0; i--){
ArrayList<Integer> list = new ArrayList<Integer>();
for (int j = 0; j < n; j++){
if ((i & (1 << j)) != 0) list.add(j);
}
double s = 0;
for (int j = 0; j < list.size(); j++){
s = 0;
for (int k = 0; k < list.size(); k++){
s += a[list.get(k)][list.get(j)];
}
d[i ^ (1 << list.get(j))] += s * d[i] * 2 / list.size() / (list.size() - 1);
}
}
for (int i = 0; i < n; i++){
out.printf(Locale.US, "%.9f", d[1 << i]);
out.print(" ");
}
}
static int[][] step8 = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, -1}, {-1, 1}, {1, 1}};
static int[][] stepKnight = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}};
static long gcd(long a, long b){
if (a == 0) return b;
return gcd(b % a, a);
}
static long lcm(long a, long b){
return a / gcd(a, b)*b;
}
static long[] gcdPlus(long a, long b){
long[] d = new long[3];
if (a == 0){
d[0] = b;
d[1] = 0;
d[2] = 1;
}else{
d = gcdPlus(b % a, a);
long r = d[1];
d[1] = d[2] - b/a*d[1];
d[2] = r;
}
return d;
}
static long binpow(long a, int n){
if (n == 0) return 1;
if ((n & 1) == 0){
long b = binpow(a, n/2);
return b*b;
}else return binpow(a, n - 1)*a;
}
static long binpowmod(long a, int n, long m){
if (m == 1) return 0;
if (n == 0) return 1;
if ((n & 1) == 0){
long b = binpowmod(a, n/2, m);
return (b*b) % m;
}else return binpowmod(a, n - 1, m)*a % m;
}
static long phi(long n){
int[] p = Sieve((int)ceil(sqrt(n)) + 2);
long phi = 1;
for (int i = 0; i < p.length; i++){
long x = 1;
while (n % p[i] == 0){
n /= p[i];
x *= p[i];
}
phi *= x - x/p[i];
}
if (n != 1) phi *= n - 1;
return phi;
}
static long f(long n, int x, int k){ //Кол-во десятичных чисел (включая 0), содержащих в себе цифры от 0 до k-1
if (n == 0) return 1;
long b = binpow(10, x - 1);
long c = n / b;
return (c < k? c: k)*binpow(k, x - 1) + (c < k? 1: 0)*f(n % b, x - 1, k);
}
static long fib(int n){
if (n == 0) return 0;
if ((n & 1) == 0){
long f1 = fib(n/2 - 1);
long f2 = fib(n/2 + 1);
return f2*f2 - f1*f1;
}else{
long f1 = fib(n/2);
long f2 = fib(n/2 + 1);
return f1*f1 + f2*f2;
}
}
static BigInteger BigFib(int n){
if (n == 0) return BigInteger.ZERO;
if ((n & 1) == 0){
BigInteger f1 = BigFib(n/2 - 1);
f1 = f1.multiply(f1);
BigInteger f2 = BigFib(n/2 + 1);
f2 = f2.multiply(f2);
return f2.subtract(f1);
}else{
BigInteger f1 = BigFib(n/2);
f1 = f1.multiply(f1);
BigInteger f2 = BigFib(n/2 + 1);
f2 = f2.multiply(f2);
return f2.add(f1);
}
}
static public class PointD{
double x, y;
public PointD(double x, double y){
this.x = x;
this.y = y;
}
}
static double d(Point p1, Point p2){
return sqrt(d2(p1, p2));
}
static public double d(PointD p1, PointD p2){
return sqrt(d2(p1, p2));
}
static double d2(Point p1, Point p2){
return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
}
static public double d2(PointD p1, PointD p2){
return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
}
static boolean IsProbablyPrime(long n){
if (n == 1) return false;
if ((n & 1) == 0) return false;
for (int j = 3; j < sqrt(n) + 1; j += 2){
if (n % j == 0) return false;
}
return true;
}
static int[] Sieve(int n){
boolean[] b = new boolean[n+1];
Arrays.fill(b, true);
b[0] = false;
b[1] = false;
long nLong = n;
int j=0;
for (int i = 1; i <= n; i++) {
if (b[i]){
j++;
if (((long)i)*i <= nLong) {
for (int k = i*i; k <= n; k += i) {
b[k] = false;
}
}
}
}
int[] p = new int[j];
Arrays.fill(p, 0);
j=0;
for (int i = 2; i <= n; i++) {
if (b[i]){
p[j]=i;
j++;
}
}
return p;
}
static int[][] Palindromes(String s){
char[] c = s.toCharArray();
int n = c.length;
int[][] d = new int[2][n];
int l = 0, r = -1;
for (int i = 0; i < n; i++){
int j = (i > r? 0: min(d[0][l+r-i+1], r-i+1)) + 1;
for (; i - j >= 0 && i + j - 1< n && c[i-j] == c[i+j-1]; j++);
d[0][i] = --j;
if (i + d[0][i] - 1 > r){
r = i + d[0][i] - 1;
l = i - d[0][i];
}
}
l = 0;
r = -1;
for (int i = 0; i < n; i++){
int j = (i > r? 0: min(d[1][l+r-i], r-i)) + 1;
for (; i - j >= 0 && i + j < n && c[i-j] == c[i+j]; j++);
d[1][i] = --j;
if (i + d[1][i] > r){
r = i + d[1][i];
l = i - d[1][i];
}
}
return d;
}
static public class Permutation {
int[] a;
int n;
public Permutation(int n){
this.n=n;
a=new int[n];
for (int i=0; i<n; i++){
a[i]=i;
}
}
public boolean nextPermutation(){ //Пишется с do{}while(nextPermutation(a));
int i=n-1;
for (i=n-2; i>=0; i--){
if (a[i]<a[i+1]){
break;
}
}
if (i==-1){
return false;
}
int jMin=i+1;
for (int j=n-1; j>i; j--){
if (a[i]<a[j]&&a[j]<a[jMin]){
jMin=j;
}
}
swap(i, jMin);
for (int j=1; j<=(n-i)/2; j++){
swap(i+j, n-j);
}
return true;
}
public int get(int i){
return a[i];
}
void swap(int i, int j){
int r=a[i];
a[i]=a[j];
a[j]=r;
}
}
static public class Fraction implements Comparable<Fraction>, Cloneable{
public final Fraction FRACTION_ZERO = new Fraction();
public final Fraction FRACTION_ONE = new Fraction(1);
public long numerator = 0;
public long denominator = 1;
public Fraction(){
numerator = 0;
denominator = 1;
}
public Fraction(long numerator){
this.numerator = numerator;
denominator = 1;
}
public Fraction(long numerator, long denominator){
this.numerator = numerator;
this.denominator = denominator;
Cancellation();
}
public Fraction(double numerator, double denominator, int accuracy){
this.numerator = (long)(numerator*pow(10,accuracy));
this.denominator = (long)(denominator*pow(10,accuracy));
Cancellation();
}
public Fraction(String s){
if (s.charAt(0) == '-'){
denominator = -1;
s = s.substring(1);
}
if (s.indexOf("/") != -1){
denominator *= Integer.parseInt(s.substring(s.indexOf("/") + 1));
}
if (s.indexOf(" ") != -1){
numerator = Integer.parseInt(s.substring(0, s.indexOf(" "))) * abs(denominator) + Integer.parseInt(s.substring(s.indexOf(" ") + 1, s.indexOf("/")));
}else{
if (s.indexOf("/") != -1){
numerator = Integer.parseInt(s.substring(0, s.indexOf("/")));
}else{
numerator = Integer.parseInt(s)*abs(denominator);
}
}
this.Cancellation();
}
void Cancellation(){
long g = gcd(abs(numerator), abs(denominator));
numerator /= g;
denominator /= g;
if (denominator < 0){
numerator *= -1;
denominator *= -1;
}
}
public String toString(){
String s = "";
if (numerator == 0){
return "0";
}
if (numerator < 0){
s += "-";
}
if (abs(numerator) >= denominator){
s += Long.toString(abs(numerator) / denominator) + " ";
}
if (abs(numerator) % denominator != 0){
s += Long.toString(abs(numerator) % denominator);
}else{
s = s.substring(0, s.length()-1);
}
if (denominator != 1){
s += "/" + Long.toString(denominator);
}
return s;
}
public Fraction add(Fraction f){
Fraction fResult = new Fraction();
fResult.denominator = lcm(denominator, f.denominator);
fResult.numerator = numerator * fResult.denominator / denominator + f.numerator * fResult.denominator / f.denominator;
fResult.Cancellation();
return fResult;
}
public Fraction subtract(Fraction f){
Fraction fResult = new Fraction();
fResult.denominator = lcm(denominator, f.denominator);
fResult.numerator = numerator * fResult.denominator / denominator - f.numerator * fResult.denominator / f.denominator;
fResult.Cancellation();
return fResult;
}
public Fraction multiply(Fraction f){
Fraction fResult = new Fraction();
fResult.numerator = numerator * f.numerator;
fResult.denominator = denominator * f.denominator;
fResult.Cancellation();
return fResult;
}
public Fraction divide(Fraction f){
Fraction fResult = new Fraction();
fResult.numerator = numerator * f.denominator;
fResult.denominator = denominator * f.numerator;
fResult.Cancellation();
return fResult;
}
@Override
public int compareTo(Fraction f){
long g = gcd(denominator, f.denominator);
long res = numerator * (f.denominator / g) - f.numerator * (denominator / g);
if (res < 0){
return -1;
}
if (res > 0){
return 1;
}
return 0;
}
public Fraction clone(){
Fraction fResult = new Fraction(numerator, denominator);
return fResult;
}
public Fraction floor(){
Fraction fResult = this.clone();
fResult.numerator = (fResult.numerator / fResult.denominator) * fResult.denominator;
return fResult;
}
public Fraction ceil(){
Fraction fResult = this.clone();
fResult.numerator = (fResult.numerator/fResult.denominator + 1) * fResult.denominator;
return fResult;
}
public Fraction binpow(int n){
if (n==0) return FRACTION_ONE;
if ((n&1)==0){
Fraction f=this.binpow(n/2);
return f.multiply(f);
}else return binpow(n-1).multiply(this);
}
}
static public class FenwickTree_1{ //One-dimensional array
int n;
long[] t;
public FenwickTree_1(int n){
this.n = n;
t = new long[n];
}
public long sum(int xl, int xr){
return sum(xr) - sum(xl);
}
public long sum(int x){
long result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1){
result += t[i];
}
return result;
}
public void update(int x, long delta){
for (int i = x; i < n; i = (i | (i + 1))){
t[i] += delta;
}
}
}
static public class FenwickTree_2{ //Two-dimensional array
int n, m;
long[][] t;
public FenwickTree_2(int n, int m){
this.n = n;
this.m = m;
t = new long[n][m];
}
public long sum(int xl, int yl, int xr, int yr){
return sum(xr, yr) - sum(xl - 1, yr) - sum(xr, yl - 1) + sum(xl - 1, yl - 1);
}
public long sum(int x, int y){
long result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1){
for (int j = y; j >= 0; j = (j & (j + 1)) - 1){
result+=t[i][j];
}
}
return result;
}
public void update(int x, int y, long delta){
for (int i = x; i < n; i = (i | (i + 1))){
for (int j = y; j < m; j = (j | (j + 1))){
t[i][j] += delta;
}
}
}
}
static public class FenwickTree_3{ //Three-dimensional array
int n, m, l;
long[][][] t;
public FenwickTree_3(int n, int m, int l){
this.n = n;
this.m = m;
this.l = l;
t = new long[n][m][l];
}
public long sum(int xl, int yl, int zl, int xr, int yr, int zr){
return sum(xr, yr, zr) - sum(xl - 1, yr, zr)
+ sum(xl - 1, yr, zl - 1) - sum(xr, yr, zl - 1)
- sum(xr, yl - 1, zr) + sum(xl - 1, yl - 1, zr)
- sum(xl - 1, yl - 1, zl - 1) + sum(xr, yl - 1, zl - 1);
}
public long sum(int x, int y, int z){
long result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1){
for (int j = y; j >= 0; j = (j & (j + 1)) - 1){
for (int k = z; k >= 0; k = (k & (k + 1)) - 1){
result += t[i][j][k];
}
}
}
return result;
}
public void update(int x, int y, int z, long delta){
for (int i = x; i < n; i = (i | (i + 1))){
for (int j = y; j < n; j = (j | (j + 1))){
for (int k = z; k < n; k = (k | (k + 1))){
t[i][j][k] += delta;
}
}
}
}
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
public class lc1 implements Runnable{
public void run() {
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t = 1;
while(t-- > 0) {
int n = s.nextInt();
int[] a = new int[n + 1];
for(int i = 1; i <= n; i++)
a[i] = s.nextInt();
int curr = 0;
for(int i = 1; i <= n; i++)
for(int j = i + 1; j <= n; j++)
if(a[i] > a[j])
curr++;
curr = curr % 2;
int m = s.nextInt();
while(m-- > 0) {
int l = s.nextInt();
int r = s.nextInt();
int fact = (r - l) % 4;
if(fact == 1 || fact == 2)
curr = 1 - curr;
if(curr % 2 == 0)
w.println("even");
else
w.println("odd");
}
}
w.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new lc1(),"lc1",1<<26).start();
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class D implements Runnable {
public static void main(String[] args) {
new D().run();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
boolean eof;
String buf;
public FastScanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
nextToken();
}
public FastScanner(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
nextToken();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
break;
}
}
String ret = buf;
buf = eof ? "-1" : st.nextToken();
return ret;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
void close() {
try {
br.close();
} catch (Exception e) {
}
}
boolean isEOF() {
return eof;
}
}
FastScanner sc;
PrintWriter out;
public void run() {
Locale.setDefault(Locale.US);
try {
sc = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
sc.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() {
return sc.nextInt();
}
String nextToken() {
return sc.nextToken();
}
long nextLong() {
return sc.nextLong();
}
double nextDouble() {
return sc.nextDouble();
}
void solve() {
// long time = System.currentTimeMillis();
int n = nextInt();
int m = nextInt();
boolean[][] edges = new boolean[n][n];
boolean[] edge = new boolean[(n << 5) | n];
for (int i = 0; i < m; i++) {
int x = nextInt() - 1;
int y = nextInt() - 1;
edges[x][y] = edges[y][x] = true;
edge[(x << 5) | y] = edge[(y << 5) | x] = true;
}
long[][] dp = new long[n][1 << n];
long ans = 0;
for (int i = 0; i < n; i++) {
for (int mask2 = 1; mask2 < 1 << (n - i - 1); ++mask2) {
for (int j = i + 1; j < n; j++) {
dp[j][mask2 << i << 1] = 0;
}
}
for (int j = i + 1; j < n; j++) {
if (edges[i][j]) {
dp[j][1 << j] = 1;
}
}
for (int mask2 = 1; mask2 < 1 << (n - i - 1); ++mask2) {
int mask = (mask2 << i << 1);
if ((mask & (mask - 1)) == 0) {
continue;
}
for (int j = i + 1; j < n; j++) {
if (((mask >> j) & 1) == 0) {
continue;
}
dp[j][mask] = 0;
for (int k = i + 1; k < n; k++) {
if (((mask >> k) & 1) == 0 || !edge[(j << 5) | k]) {
continue;
}
dp[j][mask] += dp[k][mask & ~(1 << j)];
}
if (edge[(i << 5) | j]) {
ans += dp[j][mask];
}
}
}
}
// if (n >= 3) {
// if (edges[n - 3][n - 2] && edges[n - 3][n - 1]
// && edges[n - 2][n - 1]) {
// ans += 2;
// }
// }
out.println(ans / 2);
// System.err.println(System.currentTimeMillis() - time);
// out.println(19 + " " + 19 * 9);
// for (int i = 0; i < 19; ++i) {
// for (int j = i + 1; j < 19; ++j) {
// out.println((i + 1) + " " + (j + 1));
// }
// }
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Map.Entry;
import static java.lang.Math.*;
public class A extends PrintWriter {
void run() {
int n = nextInt();
int m = 101;
boolean[] c = new boolean[m];
for (int i = 0; i < n; i++) {
int v = nextInt();
c[v] = true;
}
int ans = 0;
for (int v = 1; v < m; v++) {
if (c[v]) {
++ans;
for (int u = v; u < m; u += v) {
c[u] = false;
}
}
}
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;
}
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 A(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;
A solution = new A(System.out);
if (OJ) {
reader = new BufferedReader(new InputStreamReader(System.in));
solution.run();
} else {
reader = new BufferedReader(new FileReader(new File(A.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
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class Sockets {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt(), m = in.nextInt(), socket = in.nextInt();
int[] filters = new int[n];
for (int i = 0; i < n; i++ ) {
filters[i] = in.nextInt();
}
Arrays.sort(filters);
int result = 0, index = n - 1;
while ( m > socket && index >= 0) {
socket += filters[index] - 1;
result += 1;
index -= 1;
}
out.println(m > socket ? -1 : result);
out.close();
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Egor Kulikov (egor@egork.net)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int[] array = IOUtils.readIntArray(in, count);
int[] sorted = array.clone();
ArrayUtils.sort(sorted, IntComparator.DEFAULT);
int differs = 0;
for (int i = 0; i < count; i++) {
if (array[i] != sorted[i])
differs++;
}
if (differs <= 2)
out.printLine("YES");
else
out.printLine("NO");
}
}
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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
class ArrayUtils {
private static int[] tempInt = new int[0];
public static int[] sort(int[] array, IntComparator comparator) {
return sort(array, 0, array.length, comparator);
}
public static int[] sort(int[] array, int from, int to, IntComparator comparator) {
ensureCapacityInt(to - from);
System.arraycopy(array, from, tempInt, 0, to - from);
sortImpl(array, from, to, tempInt, 0, to - from, comparator);
return array;
}
private static void ensureCapacityInt(int size) {
if (tempInt.length >= size)
return;
size = Math.max(size, tempInt.length << 1);
tempInt = new int[size];
}
private static void sortImpl(int[] array, int from, int to, int[] temp, int fromTemp, int toTemp, IntComparator comparator) {
if (to - from <= 1)
return;
int middle = (to - from) >> 1;
int tempMiddle = fromTemp + middle;
sortImpl(temp, fromTemp, tempMiddle, array, from, from + middle, comparator);
sortImpl(temp, tempMiddle, toTemp, array, from + middle, to, comparator);
int index = from;
int index1 = fromTemp;
int index2 = tempMiddle;
while (index1 < tempMiddle && index2 < toTemp) {
if (comparator.compare(temp[index1], temp[index2]) <= 0)
array[index++] = temp[index1++];
else
array[index++] = temp[index2++];
}
if (index1 != tempMiddle)
System.arraycopy(temp, index1, array, index, tempMiddle - index1);
if (index2 != toTemp)
System.arraycopy(temp, index2, array, index, toTemp - index2);
}
}
interface IntComparator {
public static final IntComparator DEFAULT = new IntComparator() {
public int compare(int first, int second) {
if (first < second)
return -1;
if (first > second)
return 1;
return 0;
}
};
public int compare(int first, int second);
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.*;
public class Main {
private static void solve() throws IOException {
long n = nextLong();
out.println(25);
}
public static void main(String[] args) throws Exception {
File file = new File("System.in");
InputStream input = System.in;
PrintStream output = System.out;
if (file.exists() && file.canRead()) {
input = new FileInputStream(file);
output = new PrintStream("System.out");
}
br = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(output);
solve();
out.close();
}
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter out;
private static boolean hasNextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return false;
}
st = new StringTokenizer(line);
}
return true;
}
private static String nextToken() throws IOException {
return hasNextToken() ? st.nextToken() : null;
}
private static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.io.IOException;
import java.util.Arrays;
import java.io.FilterInputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.TreeSet;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Zyflair Griffane
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputUtil in = new InputUtil(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
HashMap<Integer, Integer> left = new HashMap<Integer, Integer>();
public void solve(int testNumber, InputUtil in, PrintWriter out) {
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] res = new int[n];
int[] arr = in.nextIntArray(n);
IntDeque[] adj = IntDeque.IntDeques(n);
boolean[] self = new boolean[n];
boolean[] assigned = new boolean[n];
for (int i = 0; i < n; i++) {
left.put(arr[i], i);
}
for (int i = 0; i < n; i++) {
int x = arr[i];
boolean canA = left.containsKey(a - x);
boolean canB = left.containsKey(b - x);
if (!canA && !canB) {
out.println("NO");
return;
}
if (left.containsKey(a - x)) {
self[i] |= x == a - x;
if (x != a - x) {
adj[i].add(left.get(a - x));
}
}
if (left.containsKey(b - x)) {
self[i] |= x == b - x;
if (x != b - x) {
adj[i].add(left.get(b - x));
}
}
}
if (a == b) {
out.println("YES");
out.println(IntArrayUtil.toString(res));
return;
}
for (int iter = 0; iter < 2; iter++) {
for (int i = 0; i < n; i++) {
if (!self[i] && !assigned[i] && (iter == 1 || adj[i].size() == 1)) {
int u = i;
DFS:
while (true) {
assigned[u] = true;
if (self[u] && arr[u] == b - arr[u]) {
res[u] = 1;
break;
}
for (int v : adj[u]) {
if (!assigned[v]) {
assigned[v] = true;
if (arr[u] == b - arr[v]) {
res[u] = res[v] = 1;
}
for (int newU : adj[v]) {
if (!assigned[newU]) {
u = newU;
continue DFS;
}
}
break DFS;
}
}
out.println("NO");
return;
}
}
else if (iter == 1 && !assigned[i] && adj[i].size() == 0 && arr[i] == b - arr[i]) {
res[i] = 1;
}
}
}
out.println("YES");
out.println(IntArrayUtil.toString(res));
}
}
class InputUtil {
JoltyScanner in;
public InputUtil(InputStream istream) {
in = new JoltyScanner(istream);
}
public String next() {
return in.next();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArray (int size) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = in.nextInt();
}
return arr;
}
}
class IntDeque implements Iterable<Integer> {
private int capacity;
private int size = 0;
private int front = 0;
private int back = 0;
private int[] deque;
public IntDeque() {
this(16);
}
public IntDeque(int capacity) {
this.capacity = capacity;
deque = new int[capacity];
}
public static IntDeque[] IntDeques(int length) {
IntDeque[] arr = new IntDeque[length];
for (int i = 0; i < length; i++) {
arr[i] = new IntDeque();
}
return arr;
}
public <T extends Iterable<Integer>>IntDeque(T intList) {
this(16);
addAll(intList);
}
public IntDeque(int[] intArr) {
this(16);
for (int i: intArr) {
addLast(i);
}
}
public void add(int x) {
addLast(x);
}
public <T extends Iterable<Integer>>void addAll(T intList) {
for (int i: intList) {
addLast(i);
}
}
public void addLast(int x) {
ensureCapacity();
size++;
deque[back++] = x;
if (back == capacity) {
back = 0;
}
}
public void ensureCapacity() {
if (size < capacity) {
return;
}
int[] newDeque = new int[capacity << 1];
for (int i = 0, j = front; i < size; i++, j++) {
if (j == capacity) {
j = 0;
}
newDeque[i] = deque[j];
}
deque = newDeque;
capacity <<= 1;
front = 0;
back = size;
}
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
int done = 0;
int curr = front;
public boolean hasNext() {
return done < size;
}
public Integer next() {
Integer res = deque[curr++];
if (curr == capacity) {
curr = 0;
}
done++;
return res;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public int size() {
return size;
}
public String toString() {
if (size == 0) {
return "";
}
StringBuilder res = new StringBuilder();
for (int i: this) {
res.append(i);
res.append(" ");
}
res.setLength(res.length() - 1);
return res.toString();
}
}
class IntArrayUtil {
public static String toString(int[] arr) {
return toString(arr, " ");
}
public static String toString(int[] arr, String delimiter) {
StringBuilder res = new StringBuilder();
for (int i: arr) {
res.append(i);
res.append(delimiter);
}
res.setLength(res.length() - delimiter.length());
return res.toString();
}
}
class JoltyScanner {
public static final int BUFFER_SIZE = 1 << 16;
public static final char NULL_CHAR = (char) -1;
StringBuilder str = new StringBuilder();
byte[] buffer = new byte[BUFFER_SIZE];
boolean EOF_FLAG = false;
int bufferIdx = 0, size = 0;
char c = NULL_CHAR;
BufferedInputStream in;
public JoltyScanner(InputStream in) {
this.in = new BufferedInputStream(in, BUFFER_SIZE);
}
public int nextInt() {
long x = nextLong();
if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
throw new ArithmeticException("Scanned value overflows integer");
}
return (int) x;
}
public long nextLong() {
boolean negative = false;
if (c == NULL_CHAR) {
c = nextChar();
}
for (; !EOF_FLAG && (c < '0' || c > '9'); c = nextChar()) {
if (c == '-') {
negative = true;
}
}
checkEOF();
long res = 0;
for (; c >= '0' && c <= '9'; c = nextChar()) {
res = (res << 3) + (res << 1) + c - '0';
}
return negative ? -res : res;
}
public String next() {
checkEOF();
if (c == NULL_CHAR) {
c = nextChar();
}
while (Character.isWhitespace(c)) {
c = nextChar();
checkEOF();
}
str.setLength(0);
for (; !EOF_FLAG && !Character.isWhitespace(c); c = nextChar()) {
str.append(c);
}
return str.toString();
}
public char nextChar() {
if (EOF_FLAG) {
return NULL_CHAR;
}
while (bufferIdx == size) {
try {
size = in.read(buffer);
if (size == -1) {
throw new Exception();
}
} catch (Exception e) {
EOF_FLAG = true;
return NULL_CHAR;
}
if (size == -1) {
size = BUFFER_SIZE;
}
bufferIdx = 0;
}
return (char) buffer[bufferIdx++];
}
public void checkEOF() {
if (EOF_FLAG) {
throw new EndOfFileException();
}
}
public class EndOfFileException extends RuntimeException {
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
int n;
void run()throws IOException{
Scanner sc = new Scanner(new InputStreamReader(System.in));
n = sc.nextInt();
int i,tmp,even,odd,e,o;
even=odd=e=o=0;
for(i=1;i<=n;i++){
tmp = sc.nextInt();
if(tmp%2==0){
e++;
if(even==0) even=i;
} else{
o++;
if(odd==0) odd=i;
}
}
if(e>1) System.out.println(odd);
else System.out.println(even);
}
public static void main(String[] args)throws IOException {
new A().run();
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.util.Scanner;
public class code0 {
public static void main(String[] args){
Scanner scr= new Scanner(System.in);
int c=0,e=0,d=0;
int a=scr.nextInt();
d=a/2;
if(a>=11 && a%2==1){
c=9;
e=a-9;
}
else{
c=a-4;e=4;
}
System.out.print(c+" "+e);
}
}
|
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.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
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);
TaskE2 solver = new TaskE2();
solver.solve(1, in, out);
out.close();
}
static class TaskE2 {
int[][] grid;
int[][] val;
int[][] dp;
int rows;
int two(int bit) {
return 1 << bit;
}
boolean contain(int mask, int bit) {
return (mask & two(bit)) > 0;
}
int rec(int col, int mask) {
if (col == grid[0].length)
return 0;
if (dp[col][mask] != -1)
return dp[col][mask];
int res = rec(col + 1, mask);
for (int newMask = mask; newMask > 0; newMask = (mask & (newMask - 1))) {
res = Math.max(res, rec(col + 1, mask ^ newMask) + val[col][newMask]);
}
dp[col][mask] = res;
return res;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int T = in.nextInt();
for (int t = 0; t < T; t++) {
int n = in.nextInt();
int m = in.nextInt();
rows = n;
int[][] input = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
input[i][j] = in.nextInt();
}
}
ArrayList<Col> cols = new ArrayList<>();
for (int col = 0; col < m; col++) {
int maxVal = 0;
for (int row = 0; row < n; row++) {
maxVal = Math.max(maxVal, input[row][col]);
}
cols.add(new Col(maxVal, col));
}
Collections.sort(cols);
m = Math.min(n, m);
grid = new int[n][m];
for (int i = 0; i < m; i++) {
int c = cols.get(i).colID;
for (int row = 0; row < n; row++) {
grid[row][i] = input[row][c];
}
}
val = new int[m][two(n)];
for (int c = 0; c < m; c++) {
for (int mask = 0; mask < two(n); mask++) {
val[c][mask] = 0;
for (int offset = 0; offset < n; offset++) {
int sum = 0;
for (int bit = 0; bit < n; bit++) {
if (contain(mask, bit) == true)
sum += grid[(bit + offset) % n][c];
}
val[c][mask] = Math.max(val[c][mask], sum);
}
}
}
dp = new int[m][two(n)];
for (int[] aux : dp)
Arrays.fill(aux, -1);
int ans = rec(0, two(n) - 1);
out.println(ans);
}
}
class Col implements Comparable<Col> {
int maxVal;
int colID;
Col(int _maxVal, int _colID) {
this.maxVal = _maxVal;
this.colID = _colID;
}
public int compareTo(Col o) {
if (o.maxVal != this.maxVal) return this.maxVal > o.maxVal ? -1 : 1;
if (o.colID != this.colID) return this.colID < o.colID ? -1 : 1;
return 0;
}
}
}
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;
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.util.*;
public class D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long L = sc.nextLong();
long R = sc.nextLong();
long res = Math.max(2 * Long.highestOneBit(L ^ R) - 1, 0);
System.out.println(res);
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class AAA {
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 m=Integer.parseInt(st.nextToken());
String a="";
String b="";
for(int i=0;i<1129;i++) {
a+="1";
b+="8";
}
a+="9";
b+="1";
System.out.println(a);
System.out.println(b);
}
}
|
constant
|
1028_B. Unnatural Conditions
|
CODEFORCES
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.StringJoiner;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] line = reader.readLine().split(" ");
int w = Integer.valueOf(line[0]);
int h = Integer.valueOf(line[1]);
int n = Integer.valueOf(line[2]);
Request[] requests = new Request[n];
for (int i = 0; i < n; i++) {
line = reader.readLine().split(" ");
requests[i] = new Request(line[0], Integer.valueOf(line[1]));
}
for (long e : solve(h, w, requests))
System.out.println(e);
// int w = 200000, h = 200000, n = 400000;
// Request[] requests = generate(w, h, n);
//
// long start = System.currentTimeMillis();
// solve(h, w, requests);
// long end = System.currentTimeMillis();
//
// System.out.println("Time: " + (end - start) + " ms");
}
private static Request[] generate(int w, int h, int n) {
Request[] requests = new Request[n];
Random rnd = new Random();
for (int i = 0; i < n; i++) {
requests[i] = rnd.nextBoolean() ? new Request("V", rnd.nextInt(w)) : new Request("H", rnd.nextInt(h));
}
return requests;
}
private static long[] solve(int h, int w, Request[] requests) {
TreeSet<Integer> hTree = new TreeSet<>();
TreeSet<Integer> wTree = new TreeSet<>();
Queue<CoordinateWithSize> hHeap = new PriorityQueue<>();
Queue<CoordinateWithSize> wHeap = new PriorityQueue<>();
hTree.add(0);
hTree.add(h);
wTree.add(0);
wTree.add(w);
hHeap.add(new CoordinateWithSize(0, h));
wHeap.add(new CoordinateWithSize(0, w));
long[] res = new long[requests.length];
for (int i = 0; i < requests.length; i++) {
Request request = requests[i];
switch (request.type) {
case "H": {
if (!hTree.contains(request.coordinate)) {
int higher = hTree.higher(request.coordinate);
int lower = hTree.lower(request.coordinate);
hHeap.add(new CoordinateWithSize(lower, request.coordinate - lower));
hHeap.add(new CoordinateWithSize(request.coordinate, higher - request.coordinate));
hTree.add(request.coordinate);
}
break;
}
case "V": {
if (!wTree.contains(request.coordinate)) {
int higher = wTree.higher(request.coordinate);
int lower = wTree.lower(request.coordinate);
wHeap.add(new CoordinateWithSize(lower, request.coordinate - lower));
wHeap.add(new CoordinateWithSize(request.coordinate, higher - request.coordinate));
wTree.add(request.coordinate);
}
break;
}
default:
throw new IllegalStateException("Unknown type [type=" + request.type + "]");
}
while (true) {
CoordinateWithSize c = hHeap.peek();
if (hTree.higher(c.coordinate) - c.coordinate == c.size)
break;
hHeap.remove();
}
while (true) {
CoordinateWithSize c = wHeap.peek();
if (wTree.higher(c.coordinate) - c.coordinate == c.size)
break;
wHeap.remove();
}
res[i] = 1L * hHeap.peek().size * wHeap.peek().size;
}
return res;
}
private static class CoordinateWithSize implements Comparable<CoordinateWithSize> {
private final int coordinate;
private final int size;
public CoordinateWithSize(int coordinate, int size) {
this.coordinate = coordinate;
this.size = size;
}
@Override public int compareTo(CoordinateWithSize o) {
return Integer.compare(o.size, size);
}
}
private static class Request {
private final String type;
private final int coordinate;
public Request(String type, int coordinate) {
this.type = type;
this.coordinate = coordinate;
}
}
}
|
nlogn
|
527_C. Glass Carving
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class HexTheorem {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int x = Integer.parseInt(read.readLine());
System.out.println("0 0 "+x);
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.awt.Point;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args)throws IOException, URISyntaxException {
Reader.init(new FileInputStream("input.txt"));
StringBuilder s=new StringBuilder();
boolean[][]vis=new boolean[Reader.nextInt()][Reader.nextInt()];
int k=Reader.nextInt(),r,c;
Queue<Point>q=new LinkedList<Point>();
while(k-->0) {
r=Reader.nextInt()-1;
c=Reader.nextInt()-1;
vis[r][c]=true;
q.add(new Point(r,c));
}
Point end=null;
int[]x={0,0,1,-1},y={1,-1,0,0};
int a,b,i;
while(!q.isEmpty()) {
end=q.poll();
for(i=0;i<4;i++) {
a=end.x+x[i];
b=end.y+y[i];
if(a>=0&&b>=0&&a<vis.length&&b<vis[a].length&&!vis[a][b]) {
vis[a][b]=true;
q.add(new Point(a,b));
}
}
}
s.append(end.x+1).append(' ').append(end.y+1);
PrintWriter p=new PrintWriter("output.txt");
p.println(s);
p.close();
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) throws UnsupportedEncodingException {
reader = new BufferedReader(
new InputStreamReader(input, "UTF-8") );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static String nextLine() throws IOException {
return reader.readLine();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class StrangeAddition {
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
sc = new StringTokenizer(br.readLine());
int tc = nxtInt();
while (tc-- > 0) {
int a = nxtInt();
int b = nxtInt();
int ans = 0;
while (a != b) {
if (a == 0 || b == 0)
break;
if (a > b) {
int div = a / b;
a -= b * div;
ans += div;
} else {
int div = b / a;
b -= a * div;
ans += div;
}
}
out.println(ans + (a == b ? 1 : 0));
}
br.close();
out.close();
}
static BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer sc;
static String nxtTok() throws IOException {
while (!sc.hasMoreTokens()) {
String s = br.readLine();
if (s == null)
return null;
sc = new StringTokenizer(s.trim());
}
return sc.nextToken();
}
static int nxtInt() throws IOException {
return Integer.parseInt(nxtTok());
}
static long nxtLng() throws IOException {
return Long.parseLong(nxtTok());
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ShekharN
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int[] arr = new int[n + 1];
for (int i = 1; i <= n; i++) {
arr[i] = in.nextInt();
}
int inversions = 0;
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
if (arr[i] > arr[j])
inversions++;
}
}
inversions %= 2;
int q = in.nextInt();
for (int i = 0; i < q; i++) {
int l = in.nextInt(), r = in.nextInt();
int d = r - l + 1;
d = d * (d - 1) / 2;
if ((d & 1) == 1) inversions ^= 1;
out.println((inversions & 1) == 1 ? "odd" : "even");
}
}
}
static class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
public String nextString() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main{
// ArrayList<Integer> lis = new ArrayList<Integer>();
// ArrayList<String> lis = new ArrayList<String>();
// PriorityQueue<P> que = new PriorityQueue<P>();
// PriorityQueue<Integer> que = new PriorityQueue<Integer>();
// Stack<Integer> que = new Stack<Integer>();
//HashMap<Long,Long> map = new HashMap<Long,Long>();
// static long sum=0;
// 1000000007 (10^9+7)
static int mod = 1000000007;
//static int mod = 1000000009,r=0; ArrayList<Integer> l[]= new ArrayList[n];
// static int dx[]={1,-1,0,0};
// static int dy[]={0,0,1,-1};
// static int dx[]={1,-1,0,0,1,1,-1,-1};
// static int dy[]={0,0,1,-1,1,-1,1,-1};
//static Set<Integer> set = new HashSet<Integer>();p
static ArrayList<Integer> cd[];
static int K=0;
public static void main(String[] args) throws Exception, IOException{
//String line=""; throws Exception, IOException
//(line=br.readLine())!=null
//Scanner sc =new Scanner(System.in);
// !!caution!! int long //
Reader sc = new Reader(System.in);
//,a=sc.nextInt(),b=sc.nextInt();
// int n=sc.nextInt(),p[]=new int[n],q[]=new int[n];
//int n=sc.nextInt(),a[]=new int[n],b[]=new int[n];
// int n=sc.nextInt(),m=sc.nextInt(),a=sc.nextInt(),b=sc.nextInt();
// int r=1<<28;
int n=sc.nextInt();//,k=sc.nextInt();
int a=sc.nextInt(),b=sc.nextInt(),d[]=new int[n];
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
ArrayList<Integer> A = new ArrayList<Integer>();
for (int i = 0; i < n ; i++) {
d[i]=sc.nextInt();
map.put(d[i],i );
}
int c=1;
if( a>b ){c--; int x=a; a=b; b=x;}
int r[]=new int[n];
if(a==b){
for (int i = 0; i < n; i++) {
if(d[i]>a || !map.containsKey(a-d[i]) ){System.out.println("NO"); return;}
}
System.out.println("YES");
for (int i = 0; i < n; i++) {System.out.print("1 ");}
System.out.println();
return;
}
sort(d);
for (int j = 0; j < n; j++) {
int i=n-j-1;
int id=map.get(d[i]),idd=-1;
if( id<0)continue;
// db(id,d[i]);
if( d[i]<=a ){
if( map.containsKey(a-d[i]) && 0<=(idd=map.get(a-d[i])) ){
r[id]=r[idd]=(c+1)%2;
map.put(a-d[i], -1);
}
else if( map.containsKey(b-d[i]) && 0<=(idd=map.get(b-d[i])) ){
r[id]=r[idd]=c;
map.put(b-d[i], -1); }
else{ System.out.println("NO"); return; }
}
else{
if( map.containsKey(b-d[i]) && 0<=(idd=map.get(b-d[i])) ){
r[id]=r[idd]=c;
map.put(b-d[i], -1); }
else{ System.out.println("NO"); return; }
}
map.put(d[i], -1);
}
System.out.println("YES");
for (int j = 0; j < n; j++) {
System.out.print(r[j]+" ");
}
System.out.println();
}
static class P implements Comparable<P>{
// implements Comparable<Pair>
int id; long d; ;
P(int id,long d){
this.id=id;
this.d=d;
}
public int compareTo(P x){
return (-x.d+d)>=0?1:-1 ; // ascend long
// return -x.d+d ; // ascend
// return x.d-d ; //descend
}
}
static void db(Object... os){
System.err.println(Arrays.deepToString(os));
}
}
class Reader
{
private BufferedReader x;
private StringTokenizer st;
public Reader(InputStream in)
{
x = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String nextString() throws IOException
{
while( st==null || !st.hasMoreTokens() )
st = new StringTokenizer(x.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
public long nextLong() throws IOException
{
return Long.parseLong(nextString());
}
public double nextDouble() throws IOException
{
return Double.parseDouble(nextString());
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class paint {
static PriorityQueue<Integer> sequence;
public static void main (String [] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out, true);
int numSeq = Integer.parseInt(f.readLine());
sequence = new PriorityQueue<Integer>();
StringTokenizer st = new StringTokenizer(f.readLine());
for(int i = 0; i < numSeq; i++) {
sequence.add(Integer.parseInt(st.nextToken()));
}
int numColors = 0;
while(sequence.size() > 0) {
numColors++;
int smallest = sequence.poll();
PriorityQueue<Integer> temp = new PriorityQueue<Integer>();
for(int each: sequence) {
if(each % smallest != 0) {
temp.add(each);
}
}
sequence = temp;
}
System.out.println(numColors);
out.close();
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class BetaRound72_Div2_A implements Runnable {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws IOException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
@Override
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
Locale.setDefault(Locale.US);
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
public static void main(String[] args) {
new Thread(new BetaRound72_Div2_A()).start();
}
void solve() throws IOException {
int n = readInt();
int ans = n * 3 / 2;
out.print(ans);
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
FastReader in;
PrintWriter out;
int n;
public void solve(int testNumber, FastReader in, PrintWriter out) {
this.in = in;
this.out = out;
n = in.nextInt();
if (n % 4 != 0) {
out.println("! -1");
return;
}
int low = 0;
int high = n >> 1;
if (BValue(low) == 0) {
out.println("! " + (low + 1));
return;
}
int fSign = Integer.signum(BValue(low));
while (high - low > 1) {
int mid = (high + low) >> 1;
int mSign = Integer.signum(BValue(mid));
if (mSign == 0) {
out.println("! " + (mid + 1));
return;
}
if (mSign == -fSign) {
high = mid;
} else {
low = mid;
}
}
out.println("! -1");
}
public int BValue(int index) {
out.println("? " + (index + 1));
out.flush();
int f = in.nextInt();
out.println("? " + (index + 1 + (n >> 1)));
out.flush();
int s = in.nextInt();
return f - s;
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class C{
static long mod=1000000007;
static int n;
static long w[][];
static void MainMethod()throws Exception{
n=reader.nextInt();
w=new long[n+2][n+2];
for (int i=0;i<=(n+1);i++)
Arrays.fill(w[i], 0);
w[1][0]=1;
String prev,next;
prev=reader.next();
long s[]=new long[n+2];
for (int i=2;i<=n;i++) {
next=reader.next();
if (prev.equals("f"))
for (int lv=0;lv<=n;lv++)
w[i][lv+1]=w[i-1][lv];
else
for (int lv=n;lv>=0;lv--){
w[i][lv]=(w[i-1][lv]+w[i][lv+1])%mod;
}
prev=next;
}
long res=0;
for (int i=0;i<=n;i++)
res=(res+w[n][i])%mod;
printer.print(res);
}
public static void main(String[] args)throws Exception{
MainMethod();
printer.close();
}
static void halt(){
printer.close();
System.exit(0);
}
static PrintWriter printer=new PrintWriter(new OutputStreamWriter(System.out));
static class reader{
static BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer token=new StringTokenizer("");
static String readNextLine() throws Exception{
return bReader.readLine();
}
static String next() throws Exception{
while (token.hasMoreTokens()==false){
token=new StringTokenizer(bReader.readLine());
}
return token.nextToken();
}
static int nextInt()throws Exception{
while (token.hasMoreTokens()==false){
token=new StringTokenizer(bReader.readLine());
}
return Integer.parseInt(token.nextToken());
}
static long nextLong()throws Exception{
while (token.hasMoreTokens()==false){
token=new StringTokenizer(bReader.readLine());
}
return Long.parseLong(token.nextToken());
}
static double nextDouble()throws Exception{
while (token.hasMoreTokens()==false){
token=new StringTokenizer(bReader.readLine());
}
return Double.parseDouble(token.nextToken());
}
}
static class MyMathCompute{
static long [][] MatrixMultiplyMatrix(long [][] A, long [][] B, long mod) throws Exception{
int n=A.length, m=B[0].length;
int p=A[0].length;
int i,j,k;
if (B.length!=p) throw new Exception("invalid matrix input");
long [][] res=new long [n][m];
for (i=0;i<n;i++) for (j=0;j<m;j++){
if (A[i].length!=p) throw new Exception("invalid matrix input");
res[i][j]=0;
for (k=0;k<p;k++)
res[i][j]=(res[i][j]+((A[i][k]*B[k][j])% mod))% mod;
}
return res;
}
static double [][] MatrixMultiplyMatrix(double [][] A, double [][] B ) throws Exception{
int n=A.length, m=B[0].length;
int p=A[0].length;
int i,j,k;
if (B.length!=p) throw new Exception("invalid matrix input");
double [][] res=new double [n][m];
for (i=0;i<n;i++) for (j=0;j<m;j++){
if (A[i].length!=p) throw new Exception("invalid matrix input");
res[i][j]=0;
for (k=0;k<p;k++)
res[i][j]=res[i][j]+(A[i][k]*B[k][j]);
}
return res;
}
static long [][] MatrixPow(long [][] A,long n, long mod) throws Exception{
if (n==1) return A;
long [][] res=MatrixPow(A, n/2, mod);
res=MatrixMultiplyMatrix(res, res, mod);
if ((n % 2) == 1) res=MatrixMultiplyMatrix(A,res, mod);
return res;
}
static double [][] MatrixPow(double [][] A,long n) throws Exception{
if (n==1) return A;
double[][] res=MatrixPow(A, n/2);
res=MatrixMultiplyMatrix(res, res);
if ((n % 2) == 1) res=MatrixMultiplyMatrix(A,res);
return res;
}
static long pow(long a,long n,long mod){
a= a % mod;
if (n==0) return 1;
long k=pow(a,n/2,mod);
if ((n % 2)==0) return ((k*k)%mod);
else return (((k*k) % mod)*a) % mod;
}
static double pow(double a,long n){
if (n==0) return 1;
double k=pow(a,n/2);
if ((n % 2)==0) return (k*k);
else return (((k*k) )*a) ;
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class tank {
static final FastScanner fs = new FastScanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int t = fs.nextInt();
while(t-->0) {
run_case();
}
out.close();
}
static void run_case() {
int n = fs.nextInt(), prevLen = 1, one = 1;
int[] arr = fs.readArray(n);
int[] len = new int[1001];
StringBuilder[] prev = new StringBuilder[1001];
len[1] = 1;
out.println(1);
for (int i = 0; i < 1001; i++) {
prev[i] = new StringBuilder();
}
prev[1].append("1");
for (int i = 1; i < n; i++) {
if(arr[i] == 1) {
prev[prevLen + 1] = new StringBuilder(prev[prevLen]);
prev[prevLen + 1].append(".1");
out.println(prev[prevLen + 1]);
prevLen++;
len[prevLen] = 1;
}else {
for (int j = 1000; j > 0; j--) {
if(len[j] == arr[i] - 1 && j <= prevLen) {
char[] tmp = prev[j].toString().toCharArray();
if(fn(tmp)) {
prev[j] = new StringBuilder("" + (len[j] + 1));
}else {
prev[j] = new StringBuilder();
int ub = fn2(tmp);
for (int k = 0; k <= ub; k++) {
prev[j].append(tmp[k]);
}
prev[j].append(len[j] + 1);
}
out.println(prev[j]);
len[j] = len[j] + 1;
prevLen = j;
break;
}
if(j == 1) {
prev[j] = new StringBuilder("" + (one + 1));
out.println(prev[j]);
len[j] = one + 1;
prevLen = j;
one++;
}
}
}
}
}
static boolean fn(char[] arr) {
for(char c: arr) {
if(c == '.') return false;
}
return true;
}
static int fn2(char[] arr) {
int ret = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i] == '.') ret = i;
}
return ret;
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
String nextLine(){
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.Scanner;
public class C {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int r = in.nextInt();
double pos[][] = new double[n][2];
for(int i = 0; i < n; i++) {
pos[i][0] = in.nextInt();
double y = r;
for(int j = 0; j < i; j++) {
if(Math.abs(pos[i][0] - pos[j][0]) <= 2*r) {
double tempy = pos[j][1] + Math.sqrt(Math.pow(2*r, 2) - Math.pow(Math.abs(pos[i][0] - pos[j][0]), 2));
if(tempy > y) y = tempy;
}
}
pos[i][1] = y;
System.out.print(y + " ");
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
public class A
{
public static void main(String[] args)
{
new A(new Scanner(System.in));
}
public A(Scanner in)
{
int n = in.nextInt();
int t = in.nextInt();
int tt = 2*t;
rect[] rs = new rect[n];
for (int i=0; i<n; i++)
rs[i] = new rect(in.nextInt(), in.nextInt());
Arrays.sort(rs);
int res = 2;
for (int i=1; i<n; i++)
{
rect a = rs[i-1];
rect b = rs[i];
int d = b.p-a.p;
int dd = a.t+b.t;
int tv = 2*d-dd;
if (tt == tv)
res++;
if (tv > tt)
res+=2;
}
System.out.printf("%d%n", res);
}
}
class rect implements Comparable<rect>
{
int p;
int t;
public rect(int pp, int tt)
{
p = pp;
t = tt;
}
public int compareTo(rect rhs)
{
return p-rhs.p;
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
public class q1 {
public static MyScanner in = new MyScanner();
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out), true);
public static MyViewer view = new MyViewer();
public static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
public static Random rand = new Random(System.currentTimeMillis());
public static class Pair<A, B> {
private final A first;
private final B second;
public Pair(A first, B second) {
super();
this.first = first;
this.second = second;
}
public int hashCode() {
int hashFirst = first != null ? first.hashCode() : 0;
int hashSecond = second != null ? second.hashCode() : 0;
return (hashFirst + hashSecond) * hashSecond + hashFirst;
}
public boolean equals(Object other) {
if (other instanceof Pair) {
Pair otherPair = (Pair) other;
return
((this.first == otherPair.first ||
(this.first != null && otherPair.first != null &&
this.first.equals(otherPair.first))) &&
(this.second == otherPair.second ||
(this.second != null && otherPair.second != null &&
this.second.equals(otherPair.second))));
}
return false;
}
public String toString() {
return "(" + first + ", " + second + ")";
}
public A getFirst() {
return first;
}
public B getSecond() {
return second;
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
private boolean randomInput = false;
private Random rand;
void randomInput(boolean r) {
randomInput = r;
rand = new Random(System.currentTimeMillis());
//rand = new Random(42);
}
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
public String next() {
while (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 int nextInt(int val) {
return randomInput ? val : Integer.parseInt(next());
}
public int nextInt(int low, int high) {
if (randomInput) {
return rand.nextInt(high - low + 1) + low;
} else {
return Integer.parseInt(next());
}
}
long nextLong() {
return Long.parseLong(next());
}
long nextLong(long val) {
return randomInput ? val : Long.parseLong(next());
}
long nextLong(long low, long high) {
if (randomInput) {
return low + ((long) (rand.nextDouble() * (high - low + 1)));
} else {
return Long.parseLong(next());
}
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] arrayInt(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
int[] arrayInt(int n, int low, int high) {
int[] a = new int[n];
if (randomInput) {
for (int i = 0; i < n; i++) {
a[i] = rand.nextInt(high - low + 1) + low;
}
} else {
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
}
return a;
}
ArrayList<Integer> list(int n) {
ArrayList<Integer> a = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++) {
a.add(nextInt());
}
return a;
}
ArrayList<Integer> list(int n, int low, int high) {
ArrayList<Integer> a = new ArrayList<Integer>(n);
if (randomInput) {
for (int i = 0; i < n; i++) {
a.add(rand.nextInt(high - low + 1) + low);
}
} else {
for (int i = 0; i < n; i++) {
a.add(nextInt());
}
}
return a;
}
long[] arrayLong(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
long[] arrayLong(int n, long low, long high) {
long[] a = new long[n];
if (randomInput) {
for (int i = 0; i < n; i++) {
double r = rand.nextDouble();
a[i] = (long) (r * (double) (high - low + 1)) + low;
if (a[i] == 0) {
out.println("Ouch : " + r);
}
}
} else {
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
}
return a;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ArrayList<ArrayList<Integer>> randomTree(int n) {
ArrayList<ArrayList<Integer>> edges = new ArrayList<>();
for (int i = 0; i < n; i++) {
edges.add(new ArrayList<>());
}
for (int i = 1; i < n; i++) {
int par = rand.nextInt(i);
edges.get(par).add(i);
}
return edges;
}
}
static class MyViewer {
private static boolean print = true;
public void on() {
print = true;
}
public void off() {
print = false;
}
public <T extends List> void list(T a) {
if (!print) return;
if (a == null) {
out.println("List: NULL");
return;
}
if (a.size() == 0) {
out.println("List: []");
return;
}
out.print("List: [" + a.get(0));
for (int i = 1; i < a.size(); i++) {
out.print(", " + a.get(i));
}
out.println("] Len: " + a.size());
}
public <T> void array(T[] a) {
if (!print) return;
if (a == null) {
out.println("Array: NULL");
return;
}
if (a.length == 0) {
out.println("Array: []");
return;
}
out.print("Array: [" + a[0]);
for (int i = 1; i < a.length; i++) {
out.print(", " + a[i]);
}
out.println("] Len: " + a.length);
}
public void array(boolean[] a) {
if (!print) return;
if (a == null) {
out.println("boolean[]: NULL");
return;
}
if (a.length == 0) {
out.println("boolean[]: Len: 0");
return;
}
out.print("boolean[] Len: " + a.length + " [");
for (boolean x : a) {
out.print(x + ", ");
}
out.println("\b\b]");
}
public void array(int[] a) {
if (!print) return;
if (a == null) {
out.println("Array: NULL");
return;
}
if (a.length == 0) {
out.println("Array: []");
return;
}
out.print("int[] Len: " + a.length + " [");
for (int x : a) {
out.print(x + ", ");
}
out.println("\b\b]");
}
public void array(long[] a) {
if (!print) return;
if (a == null) {
out.println("Array: NULL");
return;
}
if (a.length == 0) {
out.println("Array: []");
return;
}
out.print("long Array: [");
for (long x : a) {
out.print(x + ", ");
}
out.println("\b\b] Len: " + a.length);
}
public void matrix(int[][] a, int cutoff) {
if (cutoff == 0)
cutoff = Integer.MAX_VALUE;
if (a == null) {
out.println("Matrix: NULL");
return;
}
for (int i = 0; i < a.length; i++) {
if (i < cutoff) {
printMatrixRow(a[i], cutoff);
} else {
out.println(" ...");
printMatrixRow(a[a.length - 1], cutoff);
break;
}
}
}
public void matrix(long[][] a, long cutoff) {
if (cutoff == 0)
cutoff = Long.MAX_VALUE;
if (a == null) {
out.println("Matrix: NULL");
return;
}
for (int i = 0; i < a.length; i++) {
if (i < cutoff) {
printMatrixRow(a[i], cutoff);
} else {
out.println(" ...");
printMatrixRow(a[a.length - 1], cutoff);
break;
}
}
}
public void matrix(boolean[][] a, int cutoff) {
if (cutoff == 0)
cutoff = Integer.MAX_VALUE;
if (a == null) {
out.println("Matrix: NULL");
return;
}
for (int i = 0; i < a.length; i++) {
if (i < cutoff) {
printMatrixRow(a[i], cutoff);
} else {
out.println(" ...");
printMatrixRow(a[a.length - 1], cutoff);
break;
}
}
}
private void printMatrixRow(int[] a, int cutoff) {
for (int j = 0; j < a.length; j++) {
if (j < cutoff) {
out.printf("%6d ", a[j]);
} else {
out.printf(" ... %6d", a[a.length - 1]);
break;
}
}
out.println();
}
private void printMatrixRow(long[] a, long cutoff) {
for (int j = 0; j < a.length; j++) {
if (j < cutoff) {
out.printf("%6d ", a[j]);
} else {
out.printf(" ... %6d", a[a.length - 1]);
break;
}
}
out.println();
}
private void printMatrixRow(boolean[] a, int cutoff) {
for (int j = 0; j < a.length; j++) {
if (j < cutoff) {
out.print(a[j] ? "T " : "F ");
} else {
out.print(" ... " + (a[a.length - 1] ? "T" : "F"));
break;
}
}
out.println();
}
}
public static void main(String[] args) throws IOException {
int n = in.nextInt();
int d = in.nextInt();
int[] a = in.arrayInt(n);
int count = 2;
for(int i = 0 ;i < n-1; i++) {
if( a[i+1] - a[i] == 2 * d )
count += 1;
if( a[i+1] - a[i] > 2 * d)
count += 2;
}
out.println(count);
log.flush();
in.close();
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class a implements Runnable {
private void solve() throws IOException {
int n = nextInt();
int oddcnt = 0, evencnt = 0;
int odd = 0, even = 0;
for (int i = 0; i < n; i++) {
int a = nextInt();
if (a % 2 == 0) {
even = i + 1;
evencnt++;
} else {
odd = i + 1;
oddcnt++;
}
}
if (oddcnt == 1) {
System.out.println(odd);
} else {
System.out.println(even);
}
}
public static void main(String[] args) {
new Thread(new a()).start();
}
BufferedReader br;
StringTokenizer st;
PrintWriter out;
boolean eof = false;
public void run() {
Locale.setDefault(Locale.US);
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(239);
}
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return "0";
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Dummy {
private static long mod = 1000000007;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] strs = reader.readLine().split(" ");
long x = Long.parseLong(strs[0]);
long k = Long.parseLong(strs[1]);
long twoPK = modPow(2, k);
long twoPK_1 = (twoPK * 2) % mod;
long res = ((twoPK_1 * (x % mod)) % mod - (twoPK - 1) + mod) % mod;
System.out.println(x == 0? x: res);
}
private static long modPow(long base, long pow) {
long res = 1;
while(pow != 0) {
if((pow & 1) != 0) {
res = (res % mod * base % mod)%mod;
}
base = (base % mod * base % mod) % mod;
pow >>= 1;
}
return res;
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
// Don't place your source in a package
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
// Please name your class Main
public class Main {
static FastScanner fs=new FastScanner();
static class FastScanner {//scanner from SecondThread
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int Int() {
return Integer.parseInt(next());
}
long Long() {
return Long.parseLong(next());
}
String Str(){
return next();
}
}
public static void main (String[] args) throws java.lang.Exception {
PrintWriter out = new PrintWriter(System.out);
int primes[]=new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167,
173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269,
271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,
383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487,
491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727,
733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607,
1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721,
1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847,
1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973,
1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373,
3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517,
3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999};
int T=Int();
for(int t=0;t<T;t++){
int n=Int();
int k=Int();
int A[]=new int[n];
for(int i=0;i<n;i++){
A[i]=Int();
}
Sol sol=new Sol();
sol.solution(out,A,k,primes);
}
out.flush();
}
public static int Int(){
return fs.Int();
}
public static long Long(){
return fs.Long();
}
public static String Str(){
return fs.Str();
}
}
class Sol{
int dp[][];
public void solution(PrintWriter out,int A[],int K,int primes[]){
int n=A.length;
int id=0;
int dp[][]=new int[n+1][K+1];
for(int i=0;i<dp.length;i++){
Arrays.fill(dp[i],n);
}
//pre-processing
Map<String,Integer>f=new HashMap<>();
for(int i=0;i<A.length;i++){
String h=hash(A[i],primes);
if(!f.containsKey(h)){
f.put(h,id);
A[i]=id;
id++;
}
else{
A[i]=f.get(h);
}
}
int dis[][]=new int[A.length][K+1];
for(int k=0;k<=K;k++){//how far it can go
int r=n-1;
Map<Integer,Integer>ff=new HashMap<>();
for(int i=n-1;i>=0;i--){
put(ff,A[i]);
while(ff.size()+k<(r-i+1)){
remove(ff,A[r]);
dis[r][k]=i+1;
r--;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<=K;j++){
if(j>=i+1){
dp[i][j]=1;
continue;
}
for(int k=0;k<=j;k++){//take k change
int reach=dis[i][k];//the maximum place I can reach
if(reach==0)dp[i][j]=1;
else dp[i][j]=Math.min(dp[i][j],1+dp[reach-1][j-k]);
}
}
}
out.println(dp[n-1][K]);
}
public void put(Map<Integer,Integer>f,int key){
if(!f.containsKey(key))f.put(key,1);
else f.put(key,f.get(key)+1);
}
public void remove(Map<Integer,Integer>f,int key){
f.put(key,f.get(key)-1);
if(f.get(key)==0)f.remove(key);
}
public String hash(int n,int primes[]){
StringBuilder str=new StringBuilder("a,");
for(int i:primes){
if(i*i>n)break;
int cnt=0;
while(n%i==0){
n/=i;
cnt++;
}
cnt%=2;
if(cnt!=0)str.append(i+",");
}
if(n!=1)str.append(n+",");
return str.toString();
}
}
|
cubic
|
1497E2
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////// SOLUTION ///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Solution{
// main();
public static void main(String[] args) throws IOException{
///input
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] str=br.readLine().split(" ");
long n=Long.parseLong(str[0]);
if(n<3)
System.out.println(n);
else if(n%2==1)
System.out.println(n*(n-1)*(n-2));
else
{
if(n%3!=0)
System.out.println(n*(n-1)*(n-3));
else
System.out.println((n-1)*(n-2)*(n-3));
}
}//void main
}//class main
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tb;
int n = Integer.parseInt(br.readLine());
int x = 0,y=0;
if(n%2==0){
x = n-4;
y = 4;
}else{
x = n-9;
y = 9;
}
System.out.println(x+" "+y);
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.StringTokenizer;
import static java.lang.Integer.*;
public class A {
public static void main(String[] args) throws IOException {
//BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
Scanner sc=new Scanner (System.in);
// StringTokenizer st=new StringTokenizer(buf.readLine());
int n=sc.nextInt();
System.out.println(n%2==0?4+" "+(n-4):9+" "+(n-9));
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import com.sun.org.apache.xpath.internal.axes.SubContextList;
import java.util.Scanner;
/**
*
* @author Madi
*/
public class Round42CC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String s = sc.nextLine();
int k = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'H') {
k++;
}
}
s = s + s.substring(0, k);
String ss = "";
int max = 0;
for (int i = 0; i < s.length() - k; i++) {
ss = s.substring(i, i + k);
int count = 0;
for (int j = 0; j < ss.length(); j++) {
if (ss.charAt(j) == 'H') {
count++;
}
}
if (count > max) {
max = count;
}
}
System.out.println(k - max);
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.io.*;
import java.util.Scanner;
/**
* @author pvasilyev
* @since 8/16/13
*/
public class ProblemC {
public static final String FILE_IN = "std.in";
public static final String FILE_OUT = "std.out";
private static boolean debugMode = true;
private static final long MOD = 1000 * 1000 * 1000 + 9;
public static void main(String[] args) throws IOException {
final Scanner reader = new Scanner(new InputStreamReader(debugMode ? System.in : new FileInputStream(FILE_IN)));
final PrintWriter writer = new PrintWriter(debugMode ? System.out : new FileOutputStream(FILE_OUT));
// final long start = System.currentTimeMillis();
solveTheProblem(reader, writer);
// System.out.println(System.currentTimeMillis() - start);
reader.close();
writer.close();
}
private static void solveTheProblem(final Scanner reader, final PrintWriter writer) {
final long n = reader.nextLong();
final long m = reader.nextLong();
final long k = reader.nextLong();
if (n - n/k >= m) {
writer.println(m);
return;
} else {
long sum = 1;
long maxK = m - n + n/k;
sum = fastPow(2, maxK);
sum = 2 * (sum - 1);
sum = sum % MOD;
sum *= k;
sum += m - maxK * k;
writer.println(sum % MOD);
}
}
private static long fastPow(final int exp, final long deg) {
if (deg == 0) {
return 1;
} else if (deg == 1) {
return exp;
} else if (deg % 2 == 0) {
long temp = fastPow(exp, deg / 2);
temp = (temp * temp) % MOD;
return temp;
} else {
long temp = fastPow(exp, deg / 2);
temp = (temp * temp) % MOD;
return (temp * exp) % MOD;
}
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Longest {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
int max=0;
for(int i=0;i<str.length();i++)
{
for(int x=0;x+i<=str.length();x++)
{
if(contains(str,str.substring(x,x+i),x))
{
//System.out.println(str.substring(x,x+i));
max=Math.max(max, i);
}
}
}
System.out.println(max);
}
public static boolean contains(String whole,String part,int start)
{
if(whole.indexOf(part, start+1)>=0)return true;
return false;
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
//package round169;
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 D2 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
long L = nl(), R = nl();
out.println(Math.max(0, Long.highestOneBit(L^R)*2-1));
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new D2().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)); }
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.util.Scanner;
public class C {
public static void main(String[] args) {
new C();
}
C() {
Scanner in = new Scanner(System.in);
long n = in.nextLong(), s = in.nextLong();
long lo = 1, hi = 1000000000000000000L;
while(lo<hi){
//System.out.println(lo+" "+hi);
//STUPID STUPID DUMB
long mid = (lo+hi)/2;
if(reallyBig(mid,s))
hi = mid;
else
lo = mid+1;
}
//System.out.println(lo+" "+hi);
if(!reallyBig(lo,s))
System.out.println(0);
else
System.out.println(Math.max(n-lo+1,0));
//System.out.println(reallyBig(100000000000000009L,100000000000000000L));
in.close();
}
boolean reallyBig(long n, long s){
int sum = 0;
long temp = n;
while(temp>0){
sum += temp%10;
temp/=10;
}
return n-sum>=s;
}
}
/*
12 1
25 20
10 9
1000000000000000000 1000000000000000000
1000000000000000000 100000000000000000
*/
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.awt.Point;
import static java.lang.Math.*;
public class P166A {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
Point[] P = new Point[n];
for(int i=0; i<n; i++)
P[i] = new Point(in.nextInt(), in.nextInt());
Arrays.sort(P, new Comparator<Point>() {
public int compare(Point A, Point B) {
if(A.x != B.x) return B.x-A.x;
return A.y - B.y;
}
});
int cnt = 0;
Point ans = P[k-1];
for(int i=0; i<n; i++) {
if(P[i].x == ans.x && P[i].y==ans.y)
cnt++;
}
System.out.println(cnt);
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A
{
public static void main(String[] args) throws IOException
{
Scanner sc=new Scanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
String []a=new String[n];
String []b=new String[n];
TreeMap<String,Integer> map1=new TreeMap(),map2=new TreeMap();
for(int i=0;i<n;i++)
{
String s=sc.next();
map1.put(s, map1.getOrDefault(s, 0)+1);
}
for(int i=0;i<n;i++)
{
String s=sc.next();
map2.put(s, map2.getOrDefault(s, 0)+1);
}
int ans=0;
for(String s:map2.keySet())
{
int cnt=map1.getOrDefault(s, 0);
ans+=Math.max(0, map2.get(s)-cnt);
}
pw.println(ans);
pw.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public Scanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(s));
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class LittleElephant {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int temp;
ArrayList<Integer> a2 = new ArrayList<Integer>();
ArrayList<Integer> a1 = new ArrayList<Integer>();
int count = 0;
int temp1,temp2;
for(int i= 0; i < n ; i++){
temp = input.nextInt();
a2.add(temp);
a1.add(temp);
}
Collections.sort(a2);
input.close();
for(int i = 0; i < n; i++){
temp1 = a2.get(i);
temp2 = a1.get(i);
if(temp1 != temp2){
count++;
}
}
if(count==2 || count==0){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
FastReader reader = new FastReader();
PrintWriter writer = new PrintWriter(System.out);
long n = reader.nextLong();
long k = reader.nextLong();
long s=0;
long e=n;
long ans = -1;
while (s<=e) {
long m = (s+e)/2;
long temp = ((n-m)*(n-m+1))/2 - m;
if (temp < k)
e = m-1;
else if (temp > k)
s = m+1;
else {
ans = m;
break;
}
}
writer.println(ans);
writer.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;
}
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class D {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
public void solve() throws IOException {
int N = nextInt();
int M = nextInt();
boolean[][] graph = new boolean[N][N];
for (int i = 0; i < M; i++) {
graph[nextInt()-1][nextInt()-1] = true;
}
int best = Integer.MAX_VALUE;
for (int c = 0; c < N; c++) {
int withC = 0;
for (int i = 0; i < N; i++) {
if (i == c) {
if (graph[c][i]) withC++;
} else {
if (graph[c][i]) withC++;
if (graph[i][c]) withC++;
}
}
int notC = M - withC;
List<Integer>[] g = new List[N];
for (int i = 0; i < N; i++) {
g[i] = new ArrayList<Integer>();
}
for (int i = 0; i < N; i++) {
if (i == c) continue;
for (int j = 0; j < N; j++) {
if (j == c) continue;
if (!graph[i][j]) continue;
g[i].add(j);
}
}
int glen = maxMatching(g, N);
// int src = 2*N;
// int dst = 2*N+1;
// int[][] cap = new int[2*N+2][2*N+2];
// int[][] cost = new int[2*N+2][2*N+2];
// for (int i = 0; i < N; i++) {
// cap[src][i] = 1;
// cost[src][i] = 1;
// cap[N+i][dst] = 1;
// cost[N+i][dst] = 1;
// }
// for (int i = 0; i < N; i++) {
// if (i == c) continue;
// for (int j = 0; j < N; j++) {
// if (j == c) continue;
// if (!graph[i][j]) continue;
// cap[i][N+j] = 1;
// cost[i][N+j] = 1;
// }
// }
// MinCostMaxFlow flow = new MinCostMaxFlow();
// int result[] = flow.getMaxFlow(cap, cost, src, dst);
// int glen = result[0];
int need = (2*N-1 - withC) + (notC - glen) + (N - 1 - glen);
best = Math.min(best, need);
}
out.println(best);
}
static boolean findPath(List<Integer>[] g, int u1, int[] matching, boolean[] vis) {
vis[u1] = true;
for (int v : g[u1]) {
int u2 = matching[v];
if (u2 == -1 || !vis[u2] && findPath(g, u2, matching, vis)) {
matching[v] = u1;
return true;
}
}
return false;
}
public static int maxMatching(List<Integer>[] g, int n2) {
int n1 = g.length;
int[] matching = new int[n2];
Arrays.fill(matching, -1);
int matches = 0;
for (int u = 0; u < n1; u++) {
if (findPath(g, u, matching, new boolean[n1]))
++matches;
}
return matches;
}
/**
* @param args
*/
public static void main(String[] args) {
new D().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
cubic
|
387_D. George and Interesting Graph
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
boolean[][] graph = new boolean[n][n];
for(int i = 0; i < m; i++) {
int from = in.nextInt() - 1;
int to = in.nextInt() - 1;
graph[from][to] = true;
graph[to][from] = true;
}
int max = 1 << n;
long[][] dp = new long[max][n];
for(int mask = 1; mask < max; mask++) {
for(int i = 0; i < n; i++) {
int countMask = Integer.bitCount(mask);
boolean existSubSeti = (mask & (1 << i)) > 0;
if(countMask == 1 && existSubSeti) {
dp[mask][i] = 1;
}
else if(countMask > 1 && existSubSeti) {
int mask1 = mask ^ (1 << i);
for(int j = 0; j < n; j++) {
if(((mask1 & (1 << j)) > 0) && graph[j][i] && i != firstMask(mask, n)) {
dp[mask][i] += dp[mask1][j];
}
}
}
}
}
long counter = 0;
for(int mask = 1; mask < max; mask++) {
for(int i = 0; i < n; i++) {
if(Integer.bitCount(mask) >= 3 && graph[firstMask(mask, n)][i]) {
counter += dp[mask][i];
}
}
}
System.out.println(counter / 2);
in.close();
}
public static int firstMask(int mask, int n) {
for(int i = 0; i < n; i++) {
if((mask & (1 << i)) > 0) return i;
}
return -1;
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.regex.*;
//import java.math.*;
//import static java.lang.Math.*;
//import static java.util.Arrays.*;
public class Main{
public static void main(String[] args) throws IOException { //1-checker 2-console
//if (args.length==2) open(args[0], args[1], true, false); else open ("input.txt", "output.txt", true, false);
open ("input.txt", "output.txt", false, true);
char[] alph = " ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
Pattern pat = Pattern.compile("[A-Z]+[\\d]+");
Matcher mat;
boolean b ;
String s;
int index, coef, row, col;
int n = nextInt();
String[] tmp;
char[] c;
for (int i=0; i<n; i++)
{
s = nextLine();
c = s.toCharArray();
mat = pat.matcher(s);
b = mat.matches();
if (b)
{
index = c.length-1;
coef = 1;
row = 0;
while (c[index]>='0' && c[index]<='9')
{
row += (c[index]-'0')*coef;
coef*=10;
index--;
}
coef = 1;
col = 0;
while (index>=0)
{
/*if (coef!=1)*/ col += (Arrays.binarySearch(alph, c[index]))*coef;
//else col += (Arrays.binarySearch(alph, c[index]))*coef;
coef*=26;
index--;
}
out.println("R"+row+"C"+col);
}
else
{
tmp = s.split("R|C");
//out.print(tmp.length);
//row = Integer.parseInt(tmp[1]);
col = Integer.parseInt(tmp[2]);
char[] temp = new char[10];
int len = 0;
int v = 0;
while (col>0)
{
index = col%26;
if (index==0)
{ index=26;
v = 1;
}
else v = 0;
/*if (len==0)*/ temp[len]=alph[index];
//else temp[len]=alph[index-1];
col = (col/26) - v;
len++;
}
for (int j=len-1; j>=0; j--)
{
out.print(temp[j]);
}
out.println(tmp[1]);
}
}
close();
}
static StringTokenizer st;
static StreamTokenizer strTok;
static BufferedReader in;
static PrintWriter out;
static String nextToken(boolean f) throws IOException {
if (f) {
return in.readLine();
} else {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
}
static String nextLine() throws IOException {
return nextToken(true);
}
static int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken(false));
}
static long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken(false));
}
static double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken(false));
}
static char nextChar() throws IOException {
return ((char)in.read());
}
static void close(){
out.flush();
out.close();
}
static void open(String filein, String fileout, boolean flag, boolean console) throws IOException{
if (flag) {
strTok = new StreamTokenizer(new FileReader (new File(filein)));
in = new BufferedReader(new FileReader (new File(filein)));
out = new PrintWriter(new FileWriter(new File (fileout)));
} else {
if (console){
strTok = new StreamTokenizer(new InputStreamReader (System.in, "ISO-8859-1"));
in = new BufferedReader (new InputStreamReader (System.in, "ISO-8859-1"));
out = new PrintWriter (new OutputStreamWriter (System.out, "ISO-8859-1"));
} else {
strTok = new StreamTokenizer(new FileReader (new File("input.txt")));
in = new BufferedReader(new FileReader (new File("input.txt")));
out = new PrintWriter(new FileWriter(new File ("output.txt")));
}
}
}
}
|
linear
|
1_B. Spreadsheets
|
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.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
E2RotateColumnsHardVersion solver = new E2RotateColumnsHardVersion();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class E2RotateColumnsHardVersion {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
E2RotateColumnsHardVersion.Column[] columns = new E2RotateColumnsHardVersion.Column[m];
for (int i = 0; i < columns.length; ++i) columns[i] = new E2RotateColumnsHardVersion.Column(new int[n]);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
columns[j].vals[i] = in.nextInt();
}
}
for (E2RotateColumnsHardVersion.Column column : columns) column.initMax();
Arrays.sort(columns, new Comparator<E2RotateColumnsHardVersion.Column>() {
public int compare(E2RotateColumnsHardVersion.Column o1, E2RotateColumnsHardVersion.Column o2) {
return o2.max - o1.max;
}
});
if (columns.length > n)
columns = Arrays.copyOf(columns, n);
out.println(solveOne(columns));
}
private int solveOne(E2RotateColumnsHardVersion.Column[] columns) {
int n = columns[0].vals.length;
int[] best = new int[1 << n];
int[] next = new int[1 << n];
int[] temp = new int[1 << n];
for (E2RotateColumnsHardVersion.Column nowColumn : columns) {
System.arraycopy(best, 0, next, 0, best.length);
for (int rot = 0; rot < n; ++rot) {
System.arraycopy(best, 0, temp, 0, next.length);
for (int i = 0, pos = rot; i < n; ++i, ++pos) {
if (pos >= n) pos = 0;
int val = nowColumn.vals[pos];
for (int j = 0; j < temp.length; ++j) {
if ((j & (1 << i)) == 0) {
temp[j | (1 << i)] = Math.max(temp[j | (1 << i)], temp[j] + val);
}
}
}
for (int j = 0; j < temp.length; ++j) {
next[j] = Math.max(next[j], temp[j]);
}
}
int[] aa = best;
best = next;
next = aa;
}
return best[best.length - 1];
}
static class Column {
int[] vals;
int max;
public Column(int[] vals) {
this.vals = vals;
}
void initMax() {
max = 0;
for (int vv : vals) max = Math.max(max, vv);
}
}
}
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 String next() {
return nextString();
}
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 String nextString() {
int c = pread();
while (isSpaceChar(c))
c = pread();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = pread();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Solution {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
int n, k;
boolean[] prime;
int[] primes;
void sieve() {
prime = new boolean[n + 1];
Arrays.fill(prime, true);
prime[0] = prime[1] = false;
int cnt = 0;
for (int i = 2; i <= n; ++i)
if (prime[i]) {
++cnt;
for (int j = i + i; j <= n; j += i)
prime[j] = false;
}
primes = new int[cnt];
cnt = 0;
for (int i = 0; i <= n; ++i)
if (prime[i])
primes[cnt++] = i;
}
void solve() throws IOException {
n = ni();
k = ni();
sieve();
int cnt = 0;
for (int i = 2; i <= n; ++i) {
if (!prime[i])
continue;
boolean ok = false;
for (int j = 0; j < primes.length - 1; ++j)
if (primes[j] + primes[j + 1] + 1 == i) {
ok = true;
break;
}
if (ok)
++cnt;
}
if (cnt >= k)
out.println("YES");
else
out.println("NO");
}
public Solution() 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 Solution();
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int one, two;
if(n%2 == 0)
{
one = two = n/2;
if(one%2 != 0 && two%2 != 0)
{
one--;
two++;
}
}
else
{
one = n - 9;
two = 9;
}
System.out.println(one+" "+two);
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;
public class C {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
long r = sc.nextInt();
double d = 2 * r;
long[] xs = sc.readLongArray(n);
P[] points = new P[n];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (i > 0) sb.append(' ');
double y = r;
for (int j = 0; j < i; j++) {
long diff = Math.abs(xs[i] - points[j].x);
if (diff <= 2 * r) {
double dy = Math.sqrt(d * d - diff * diff);
double testY = points[j].y + dy;
y = Math.max(y, testY);
}
}
sb.append(y);
points[i] = new P(xs[i], y);
}
System.out.println(sb);
}
static class P {
final long x;
final double y;
public P(long x, double y) {
this.x = x;
this.y = y;
}
}
static void shuffle(int[] arr) {
Random rng = new Random();
int length = arr.length;
for (int idx = 0; idx < arr.length; idx++) {
int toSwap = idx + rng.nextInt(length - idx);
int tmp = arr[idx];
arr[idx] = arr[toSwap];
arr[toSwap] = tmp;
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextLong();
}
return a;
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
public class C
{
public static void main(String[] args)
{
new C(new Scanner(System.in));
}
vect[] vs;
int N;
int oo = 987654321;
ArrayList<choice> cs;
choice[][] cg;
int MF;
int[] memo;
int[] next;
int go(int m)
{
if (m == MF)
return 0;
if (memo[m] != -1)
return memo[m];
// Try a new place
int res = oo;
int nxt = -1;
int i=0;
for (i=0; i<N; i++)
{
if (((1<<i)&m) == 0)
break;
}
for (int j=0; j<N; j++)
{
choice cc = cg[i][j];
if ((m&cc.m) > 0)
continue;
int r2 = cc.cost+go(m|cc.m);
if (r2 < res)
{
res = r2;
nxt = cc.index;
}
}
memo[m] = res;
next[m] = nxt;
return res;
}
public C(Scanner in)
{
vect vt = new vect(in.nextInt(), in.nextInt());
N = in.nextInt();
vs = new vect[N+1];
vs[N] = vt;
for (int i=0; i<N; i++)
vs[i] = new vect(in.nextInt(), in.nextInt());
// Precompute all choices and masks
cs = new ArrayList<choice>();
cg = new choice[N][N];
for (int i=0; i<N; i++)
{
choice cc = new choice(cs.size(), 2*vs[i].dist(vt), 1<<i);
cc.add(i);
cs.add(cc);
cg[i][i] = cc;
}
for (int i=0; i<N; i++)
{
for (int j=i+1; j<N; j++)
{
int dist = vs[i].dist(vt);
dist += vs[i].dist(vs[j]);
dist += vs[j].dist(vt);
choice cc = new choice(cs.size(), dist, (1<<i)|(1<<j));
cc.add(i); cc.add(j);
cs.add(cc);
cg[i][j] = cc;
cg[j][i] = cc;
}
}
MF = (1<<N)-1;
next = new int[MF+1];
memo = new int[MF+1];
Arrays.fill(next, -1);
Arrays.fill(memo, -1);
int res = go(0);
System.out.println(res);
int m = 0;
StringBuilder sb = new StringBuilder();
while (m != -1)
{
//System.out.println(Integer.toBinaryString(m));
sb.append(0);
sb.append(' ');
int i = next[m];
if (i == -1)
break;
choice cc = cs.get(i);
for (int j : cc.iv)
{
sb.append(f(j));
sb.append(' ');
}
m = m|cc.m;
}
System.out.println(sb.toString().trim());
}
int f(int i)
{
if (i == N)
return 0;
return i+1;
}
}
class choice
{
int cost;
int m;
int index;
ArrayList<Integer> iv;
public choice(int ii, int c, int mm)
{
index = ii;
cost = c;
m = mm;
iv = new ArrayList<Integer>(2);
}
void add(int i)
{
iv.add(i);
}
}
class vect
{
int x, y;
public vect(int i, int j)
{
x=i; y=j;
}
int dist(vect rhs)
{
int xx = x-rhs.x;
int yy = y-rhs.y;
return xx*xx+yy*yy;
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
public class A {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
HashSet<Integer> set = new HashSet<Integer>();
for ( int i = 0 ; i < n ; ++i ) {
set.add(sc.nextInt());
} // for i
ArrayList<Integer> list = new ArrayList<Integer>(set);
Collections.sort(list);
if(list.size() > 1)
System.out.println(list.get(1));
else
System.out.println("NO");
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
// by agus.mw
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws Exception {
new Main().doWork();
}
void doWork() throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String text = reader.readLine().trim();
int out = 0;
for(int i=0;i<text.length();i++){
for(int j=i+1;j<text.length();j++){
for(int len = out+1;len+j<=text.length();len++){
if(text.substring(i,i+len).compareTo(text.substring(j,j+len))==0){
out = len;
}
}
}
}
String buf = ""+out;
writer.write(buf,0,buf.length());
writer.newLine();
writer.flush();
writer.close();
reader.close();
}
String process(){
return "1";
}
int[] toIntArray(String line){
String[] p = line.split("[ ]+");
int[] out = new int[p.length];
for(int i=0;i<p.length;i++) out[i] = Integer.valueOf(p[i]);
return out;
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.text.*;
import java.math.*;
import java.util.*;
public class Main {
private BufferedReader in;
private BufferedWriter out;
double time(double a, double l, double v0, double v) {
double t = (v - v0) / a;
double s = a * t * t / 2 + v0 * t;
if (s <= l) {
return t + (l - s) / v;
}
double B = v0, C = -l;
double D = Math.sqrt(B * B - 2 * a * C);
return (-B + D) / a;
}
// )(()()))(())))
public void solve() throws Exception {
StreamTokenizer st = new StreamTokenizer(in);
st.nextToken();
double a = st.nval;
st.nextToken();
double v = st.nval;
st.nextToken();
double l = st.nval;
st.nextToken();
double d = st.nval;
st.nextToken();
double w = st.nval;
double ttt = Math.sqrt(2 * d / a);
double ans = 0.0;
if (w > v || ttt * a < w) {
ans = time(a, l, 0, v);
} else {
double B = 2 * w / a, C = -w * w / (a * a) - 4 * d / a;
double D = Math.sqrt(B * B - 4 * C);
ans = (-B + D) / 2;
if ((a * ans + w) / 2.0 > v) {
double t1 = v / a;
double t2 = (v - w) / a;
double s = (a * t1 * t1 / 2.0) + (v * t2 - a * t2 * t2 / 2.0);
ans = t1 + t2 + (d - s) / v;
}
ans += time(a, l - d, w, v);
}
DecimalFormat df = new DecimalFormat("0.000000000");
out.write(df.format(ans) + "\n");
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
try {
Locale.setDefault(Locale.US);
} catch (Exception e) {
}
new Main().run();
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class E2 {
static ArrayList<Integer> primes;
static int[] mind;
final static int MAXA = (int) 1e7;
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
int t = Integer.parseInt(st.nextToken());
primes = new ArrayList<>();
mind = new int[MAXA + 1];
for (int i = 2; i <= MAXA; i++) {
if (mind[i] == 0) {
primes.add(i);
mind[i] = i;
}
for (int x : primes) {
if (x > mind[i] || x * i > MAXA) break;
mind[x * i] = x;
}
}
int[] count = new int[MAXA + 1];
for (int on8y = 0; on8y < t; on8y++) {
st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] a = new int[n];
Arrays.fill(a, 1);
st = new StringTokenizer(f.readLine());
for (int i = 0; i < n; i++) {
int x = Integer.parseInt(st.nextToken());
int cnt = 0;
int last = 0;
while (x > 1) {
int p = mind[x];
if (last == p) cnt++;
else {
if (cnt % 2 == 1) a[i] *= last;
last = p;
cnt = 1;
}
x /= p;
}
if (cnt % 2 == 1) a[i] *= last;
}
int[][] mnleft = new int[n][k + 1];
for (int j = 0; j < k + 1; j++) {
int l = n;
int now = 0;
for (int i = n - 1; i >= 0; i--) {
while (l - 1 >= 0 && now + ((count[a[l - 1]] > 0) ? 1 : 0) <= j) {
l--;
now += (count[a[l]] > 0) ? 1 : 0;
count[a[l]]++;
}
mnleft[i][j] = l;
if (count[a[i]] > 1) now--;
count[a[i]]--;
}
}
int[][] dp = new int[n + 1][k + 1];
for (int i = 0; i < n + 1; i++) {
Arrays.fill(dp[i], (int) 1e9 + 1);
}
for (int i = 0; i < k + 1; i++) dp[0][i] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= k; j++) {
if (j > 0) dp[i][j] = dp[i][j - 1];
for (int lst = 0; lst <= j; lst++) {
dp[i][j] = Math.min(dp[i][j], dp[mnleft[i - 1][lst]][j - lst] + 1);
}
}
}
int ans = (int) 1e9 + 1;
for (int c : dp[n]) ans = Math.min(ans, c);
System.out.println(ans);
}
}
}
|
cubic
|
1497E2
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class c {
static boolean seq[];
static long memo[][], mod = (long)1e9 + 7;
static long go(int n, int d) {
long ans = 0;
if(d < 0) return 0;
if(n == seq.length) return 1;
int f = 1;
if(n > 0) f = seq[n-1]?1:0;
if(memo[n][d] != -1) return memo[n][d];
if(f == 0) {
ans += go(n + 1, d + (seq[n]?1:0));
ans %= mod;
ans += go(n, d-1);
ans %= mod;
}
if(f == 1) {
ans += go(n + 1, d + (seq[n]?1:0));
ans %= mod;
}
return memo[n][d] = ans;
}
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();
seq = new boolean[n];
for (int i = 0; i < n; i++ ) {
seq[i] = (in.next().charAt(0) == 'f');
}
memo = new long[n][n+1];
for(int i = 0; i < n; i++) {
Arrays.fill(memo[i], -1);
}
System.out.println(go(0, 0));
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
|
909_C. Python Indentation
|
CODEFORCES
|
import java.util.Scanner;
public class origami {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
double n = input.nextInt();
double k = input.nextInt();
double red = 0;
double green = 0;
double blue = 0;
double ans = 0;
red = (2 * n) / k;
green = (5 * n) / k;
blue = (8 * n) / k;
double red1 = Math.ceil(red) ;
double green1 = Math.ceil(green);
double blue1 = Math.ceil(blue);
ans+=red1;
ans+=green1;
ans+=blue1;
Double answer = new Double(ans);
int finished = answer.intValue();
System.out.println(finished);
}
}
|
constant
|
1080_A. Petya and Origami
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution
{
public static void main(String[] args) throws IOException
{
new Solution().run();
}
StreamTokenizer in;
Scanner ins;
PrintWriter out;
int nextInt() throws IOException
{
in.nextToken();
return (int)in.nval;
}
void run() throws IOException
{
if(System.getProperty("ONLINE_JUDGE")!=null)
{
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
ins = new Scanner(System.in);
out = new PrintWriter(System.out);
}
else
{
in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt")));
ins = new Scanner(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
}
int n = nextInt(),a = nextInt(),b = nextInt();
b--;
int [] A = new int[n];
for(int i = 0; i < n ;i++)
{
A[i] = nextInt();
}
Arrays.sort(A);
if(A[b] == A[b+1])
out.print(0);
else
out.print(A[b+1]- A[b]);
out.close();
}
class Team implements Comparable
{
public int p,t;
public int compareTo(Object obj)
{
Team a = (Team) obj;
if(p>a.p || p==a.p && t<a.t)
return -1;
else
if(p==a.p && t==a.t)
return 0;
else
return 1;
}
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1102f {
public static void main(String[] args) throws IOException {
int n = rni(), m = ni(), a[][] = new int[n][];
for (int i = 0; i < n; ++i) {
a[i] = ria(m);
}
int delta[][] = new int[n][n], end_delta[][] = new int[n][n], dp[][][] = new int[n][1 << n][n];
for (int i = 0; i < n; ++i) {
fill(delta[i], IBIG);
fill(end_delta[i], IBIG);
delta[i][i] = 0;
}
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++j) {
for (int k = 0; k < m; ++k) {
delta[i][j] = delta[j][i] = min(delta[i][j], abs(a[i][k] - a[j][k]));
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
for (int k = 1; k < m; ++k) {
end_delta[i][j] = min(end_delta[i][j], abs(a[j][k] - a[i][k - 1]));
}
}
}
for (int[][] layer : dp) {
for (int[] row : layer) {
fill(row, IBIG);
}
}
for (int i = 1; i < 1 << n; ++i) {
boolean one_bit = Integer.bitCount(i) == 1;
for (int j = 0; j < n; ++j) {
if ((i & (1 << j)) > 0) {
for (int l = 0; l < n; ++l) {
if ((i & (1 << l)) == 0) {
int max = 0;
for (int k = 0; k < n; ++k) {
if ((one_bit || j != k) && (i & (1 << k)) > 0) {
max = max(max, min(dp[j][i][k], delta[k][l]));
}
}
// pr(j + " ");
// pr(Integer.toBinaryString(i) + " ");
// prln(l, max);
dp[j][i | (1 << l)][l] = max;
}
}
}
}
}
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i != j) {
// prln(i, j, dp[i][(1 << n) - 1][j]);
ans = max(ans, min(dp[i][(1 << n) - 1][j], end_delta[j][i]));
}
}
}
if (n == 1) {
ans = maxof(end_delta[0]);
}
prln(ans);
close();
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;};
static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;}
static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
}
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class EdD {
static long[] mods = {1000000007, 998244353, 1000000009};
static long mod = mods[0];
public static MyScanner sc;
public static PrintWriter out;
public static void main(String[] havish) throws Exception{
// TODO Auto-generated method stub
sc = new MyScanner();
out = new PrintWriter(System.out);
int t = sc.nextInt();
for(int i = 0;i<t;i++){
int n =sc.nextInt();
if (n%2== 1)
out.println("NO");
else{
while(n%2 == 0){
n/=2;
}
verdict(isSquare(n) || isSquare(2*n));
}
}
out.close();
}
public static boolean isSquare(int n) {
int d = (int)Math.sqrt(n);
for(long s = d-2;s<=d+2;s++){
if (s*s == n)
return true;
}
return false;
}
public static void sort(int[] array){
ArrayList<Integer> copy = new ArrayList<>();
for (int i : array)
copy.add(i);
Collections.sort(copy);
for(int i = 0;i<array.length;i++)
array[i] = copy.get(i);
}
static String[] readArrayString(int n){
String[] array = new String[n];
for(int j =0 ;j<n;j++)
array[j] = sc.next();
return array;
}
static int[] readArrayInt(int n){
int[] array = new int[n];
for(int j = 0;j<n;j++)
array[j] = sc.nextInt();
return array;
}
static int[] readArrayInt1(int n){
int[] array = new int[n+1];
for(int j = 1;j<=n;j++){
array[j] = sc.nextInt();
}
return array;
}
static long[] readArrayLong(int n){
long[] array = new long[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextLong();
return array;
}
static double[] readArrayDouble(int n){
double[] array = new double[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextDouble();
return array;
}
static int minIndex(int[] array){
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(long[] array){
long minValue = Long.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(double[] array){
double minValue = Double.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static long power(long x, long y){
if (y == 0)
return 1;
if (y%2 == 1)
return (x*power(x, y-1))%mod;
return power((x*x)%mod, y/2)%mod;
}
static void verdict(boolean a){
out.println(a ? "YES" : "NO");
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.*;
import java.lang.*;
import java.util.*;
public class alex
{
public static void main(String[] args)throws IOException
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();int sum=1;
for(int i=1;i<=n;i++)
{
sum=sum+(4*(i-1));
}
System.out.println(sum);
}
}
|
linear
|
1180_A. Alex and a Rhombus
|
CODEFORCES
|
//package round584;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
// imp:12m
public class E5 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
for(int T = ni(); T> 0;T--){
int n = ni(), m = ni();
int[][] a = new int[m][n];
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
a[j][i] = ni();
}
}
int[][] mx = new int[m][];
for(int i = 0;i < m;i++){
int u = 0;
for(int j = 0;j < n;j++){
u = Math.max(u, a[i][j]);
}
mx[i] = new int[]{u, i};
}
Arrays.sort(mx, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return -(a[0] - b[0]);
}
});
int[] dp = new int[1<<n];
for(int i = 0;i < n && i < m;i++){
int c = mx[i][1];
int[] ls = new int[1<<n];
for(int j = 1;j < 1<<n;j++){
ls[j] = ls[j&j-1] + a[c][Integer.numberOfTrailingZeros(j)];
}
for(int j = 1;j < 1<<n;j++){
int r = rot(j, n);
ls[r] = Math.max(ls[r], ls[j]);
}
int[] ndp = new int[1<<n];
for(int j = 0;j < 1<<n;j++){
if(rot(j, n) == j){
int cur = j;
for(int sh = 0;sh < n;sh++){
cur = cur>>1|(cur&1)<<n-1;
int mask = (1<<n)-1^cur;
for(int k = mask;k >= 0;k--){
k &= mask;
ndp[k|cur] = Math.max(
ndp[k|cur], dp[k] + ls[j]);
}
}
}
}
dp = ndp;
}
out.println(dp[(1<<n)-1]);
}
}
int rot(int x, int n)
{
int ret = x;
for(int i = 0;i < n;i++){
x = x>>>1|(x&1)<<n-1;
ret = Math.min(ret, x);
}
return ret;
}
void run() throws Exception
{
// int n = 12, m = 2000;
// Random gen = new Random();
// StringBuilder sb = new StringBuilder();
// sb.append(40 + " ");
// for(int rep = 0;rep < 40;rep++){
// sb.append(n + " ");
// sb.append(m + " ");
// for (int i = 0; i < n*m; i++) {
// sb.append(gen.nextInt(100000) + " ");
// }
// }
// INPUT = sb.toString();
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new E5().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.lang.*;
import java.awt.*;
import java.awt.geom.*;
import java.math.*;
import java.text.*;
import java.math.BigInteger.*;
import java.util.Arrays;
public class CF111111
{
BufferedReader in;
StringTokenizer as;
int nums[],nums2[];
int[] nums1[];
boolean con = true;
ArrayList < Integer > ar = new ArrayList < Integer >();
ArrayList < Integer > fi = new ArrayList < Integer >();
Map<Integer,Integer > map = new HashMap<Integer, Integer>();
public static void main (String[] args)
{
new CF111111 ();
}
public int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
public int LIS(int arr[])
{
int n = arr.length;
int sun[] = new int [n];
int cur = 0;
for(int x = 0;x<n;x++)
{
int temp = Arrays.binarySearch(sun,0,cur,arr[x]);
if(temp < 0)
temp = -temp -1;
sun[temp] = arr[x];
if(temp == cur)
cur++;
}
return cur;
}
public CF111111 ()
{
try
{
in = new BufferedReader (new InputStreamReader (System.in));
int a = nextInt();
for(int xx1 = 0;xx1<a;xx1++)
{
int b = nextInt();
nums = new int [b];
for(int x = 0;x<b;x++)
{
nums[x] = nextInt();
}
int max = 0;
int max2 = -1;
for(int x = 0;x<b;x++)
{
if(nums[x] >= max)
{
max2 = max;
max = nums[x];
}
else if(nums[x] >= max2)
max2 = nums[x];
}
System.out.println(Math.min(max2, b-1)-1);
}
}
catch(IOException e)
{
}
}
String next () throws IOException
{
while (as == null || !as.hasMoreTokens ())
{
as = new StringTokenizer (in.readLine ().trim ());
}
return as.nextToken ();
}
long nextLong () throws IOException
{
return Long.parseLong (next ());
}
int nextInt () throws IOException
{
return Integer.parseInt (next ());
}
double nextDouble () throws IOException
{
return Double.parseDouble (next ());
}
String nextLine () throws IOException
{
return in.readLine ().trim ();
}
}
|
linear
|
1197_A. DIY Wooden Ladder
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE2 solver = new TaskE2();
solver.solve(1, in, out);
out.close();
}
static class TaskE2 {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int numTests = in.nextInt();
for (int test = 0; test < numTests; test++) {
int n = in.nextInt();
int m = in.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
}
}
if (m > n) {
int[] maxInColumn = new int[m];
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
maxInColumn[j] = Math.max(maxInColumn[j], a[i][j]);
}
}
Integer[] cols = new Integer[m];
for (int i = 0; i < m; i++) {
cols[i] = i;
}
Arrays.sort(cols, (u, v) -> -(maxInColumn[u] - maxInColumn[v]));
int[][] na = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
na[i][j] = a[i][cols[j]];
}
}
m = n;
a = na;
}
int[] buf = new int[n];
int[][] sums = new int[m][1 << n];
int[] sumsCur = new int[1 << n];
for (int j = 0; j < m; j++) {
for (int shift = 0; shift < n; shift++) {
for (int i = 0; i < n; i++) {
buf[i] = a[(i + shift) % n][j];
}
for (int mask = 1; mask < 1 << n; mask++) {
int k = Integer.numberOfTrailingZeros(mask);
sumsCur[mask] = sumsCur[mask ^ (1 << k)] + buf[k];
sums[j][mask] = Math.max(sums[j][mask], sumsCur[mask]);
}
}
}
int[] d = new int[1 << n];
for (int j = 0; j < m; j++) {
for (int mask = (1 << n) - 1; mask >= 0; mask--) {
for (int submask = mask; submask > 0; submask = (submask - 1) & mask) {
d[mask] = Math.max(d[mask], d[mask ^ submask] + sums[j][submask]);
}
}
}
int ans = 0;
for (int x : d) {
ans = Math.max(ans, x);
}
out.println(ans);
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.lang.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int m=ni();
long a[][]=new long[m][];
HashMap<Long,Integer> mp=new HashMap<>();
long TS=0;
long sm[]=new long[m];
for(int i=0;i<m;i++){
int sz=ni();
a[i]=new long[sz];
for(int j=0;j<sz;j++){
a[i][j]=nl();
mp.put(a[i][j],i);
sm[i]+=a[i][j];
}
TS+=sm[i];
}
if(TS%m!=0){
pw.println("No");
return;
}
TS/=m;
ArrayList<Node> ansForMask[]=new ArrayList[(1<<m)];
for(int i=0;i<(1<<m);i++) ansForMask[i]=new ArrayList<>();
ArrayList<Node> tempList=new ArrayList<>();
int vis[]=new int[m];
for(int i=0;i<m;i++){
out:for(int j=0;j<a[i].length;j++){
int mask=0;
tempList.clear();
long val=a[i][j],req=Long.MAX_VALUE;
int idx=i,idx2;
Arrays.fill(vis,0);
if(sm[i]==TS){
mask=1<<i;
if(ansForMask[mask].size()==0) ansForMask[mask].add(new Node(val,i,i));
continue;
}
while(vis[idx]==0){
req=TS-(sm[idx]-val);
if(!mp.containsKey(req)) continue out;
idx2=mp.get(req);
if(vis[idx]==1 || idx==idx2) continue out;
if(vis[idx2]==1) break;
// if(i==0 && j==1) pw.println(idx2+" "+req+" "+val);
vis[idx]=1;
mask+=(1<<idx);
tempList.add(new Node(req,idx2,idx));
idx=idx2;
val=req;
}
if(req!=a[i][j])continue out;
mask+=(1<<idx);
tempList.add(new Node(a[i][j],i,idx));
if(ansForMask[mask].size()==0){
// pw.println(Integer.toBinaryString(mask));
ansForMask[mask].addAll(tempList);
}
}
}
int dp[]=new int[1<<m];
dp[0]=1;
out: for(int mask=1;mask <(1<<m);mask++){
if(ansForMask[mask].size()!=0){
dp[mask]=1;
// pw.println(Integer.toBinaryString(mask)+" "+mask);
continue;
}
for(int s=mask;s>0;s=(s-1)&mask){
if(dp[s]==1 && dp[mask^s]==1){
dp[mask]=1;
ansForMask[mask].addAll(ansForMask[s]);
ansForMask[mask].addAll(ansForMask[mask^s]);
continue out;
}
}
}
if(dp[(1<<m)-1]==0){
pw.println("No");
return;
}
pw.println("Yes");
Pair ans[]=new Pair[m];
for(Node p : ansForMask[(1<<m)-1]){
ans[p.id1]=new Pair(p.c,p.id2);
}
for(int i=0;i<m;i++) pw.println(ans[i].c+" "+(ans[i].p+1));
}
class Pair {
long c;
int p;
public Pair(long c,int p){
this.c=c;
this.p=p;
}
}
class Node{
long c;
int id1;
int id2;
public Node(long c,int id1,int id2){
this.c=c;
this.id1=id1;
this.id2=id2;
}
}
long M = (long)1e9+7;
// END
PrintWriter pw;
StringTokenizer st;
BufferedReader br;
void run() throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
}
public static void main(String[] args) throws Exception {
new Main().run();
}
String ns() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
int ni() {
return Integer.parseInt(ns());
}
long nl() {
return Long.parseLong(ns());
}
double nd() {
return Double.parseDouble(ns());
}
}
|
np
|
1242_C. Sum Balance
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Arrays;
public class Main {
static Scanner in = new Scanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
long n = in.nextLong(), m = in.nextLong();
out.print(m / n + (m % n == 0 ? 0 : 1));
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
public String next() throws IOException {
if(!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
|
constant
|
1036_A. Function Height
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
import static java.lang.Math.*;
public class ProblemC {
public static void main(String[] args) {
FastScanner input = new FastScanner();
int n = input.nextInt();
int radius = input.nextInt();
ArrayList<Integer> diskXToFall = new ArrayList<Integer>();
for (int a = 0; a < n; a++) {
diskXToFall.add(input.nextInt());
}
ArrayList<P> stationaryDisks = new ArrayList<P>();
for (int a = 0; a < n; a++) {
double highCollision = radius;
for (P i : stationaryDisks) {
if (Math.abs(diskXToFall.get(a) - i.x) - 1e-8 <= 2 * radius) {
double hypot = 2 * radius;
double leg = Math.abs(diskXToFall.get(a) - i.x);
double yOffset = Math.sqrt(Math.abs(hypot * hypot - leg * leg));
highCollision = Math.max(highCollision, yOffset + i.y);
}
}
stationaryDisks.add(new P(diskXToFall.get(a), highCollision));
}
for(int a = 0; a < n; a++) {
System.out.print(stationaryDisks.get(a).y + " ");
}
}
static class P implements Comparable<P> {
final double x, y;
P(double x, double y) {
this.x = x;
this.y = y;
}
P sub(P that) {
return new P(x - that.x, y - that.y);
}
P add(P that) {
return new P(x + that.x, y + that.y);
}
double dot(P that) {
return x * that.x + y * that.y;
}
P scale(double s) {
return new P(x * s, y * s);
}
// Use hypot() only if intermediate overflow must be avoided; very slow
double length() {
return sqrt(x * x + y * y);
}
double length2() {
return x * x + y * y;
}
P leftNormal() {
return new P(-y, x);
} // rotateCCW(90deg)
P rightNormal() {
return new P(y, -x);
} // rotateCW(90deg)
P normalize() {
double n = length();
return n > 0 ? new P(x / n, y / n) : origin();
}
P scaleToLength(double l) {
return normalize().scale(l);
}
P project(P a) {
return scale(a.dot(this) / length2());
}
P reflect(P a) {
return project(a).scale(2.0).sub(a);
}
// use if sin, cos are known
P rotateCCW(double sinT, double cosT) {
return new P(x * cosT - y * sinT, x * sinT + y * cosT);
}
P rotateCW(double sinT, double cosT) {
return rotateCCW(-sinT, cosT);
}
P rotate(double theta) {
return rotateCCW(sin(theta), cos(theta));
}
// angle to horizontal (1, 0); result is in [-pi, pi] rad or (-180-180) deg
double theta() {
return atan2(y, x);
}
// angle between two vectors, result is in [0, pi] rad (0-180 deg)
double angleTo(P a) {
return acos(this.dot(a) / this.length() / a.length());
}
boolean isOrigin() {
return x == 0 && y == 0;
}
public String toString() {
return String.format("(%f,%f)", this.x, this.y);
}
static P read(Scanner s) {
return new P(s.nextDouble(), s.nextDouble());
}
static P origin() {
return new P(0, 0);
}
double det(P that) {
return this.x * that.y - this.y * that.x;
}
double crossproduct(P that) {
return this.det(that);
}
P half(P q) {
return normalize().add(q.normalize());
}
double dist(P to) {
return sub(to).length();
}
double signedParallelogramArea(P b, P c) {
return (b.sub(this).crossproduct(c.sub(this)));
}
boolean isCollinearWith(P b, P c) {
return abs(signedParallelogramArea(b, c)) <= EPS;
}
// is going from this to b to c a CCW turn? Do not use if points may be
// collinear
boolean isCCW(P b, P c) {
return signedParallelogramArea(b, c) > 0;
}
double signedTriangleArea(P b, P c) {
return signedParallelogramArea(b, c) / 2.0;
}
// memory-optimized version of this.sub(to).length2() that avoids an
// intermediate object
double dist2(P to) {
double dx = this.x - to.x;
double dy = this.y - to.y;
return dx * dx + dy * dy;
}
/**
* Compute x for a * x + b = 0 and ||x|| = C where 'this' is a. Care must be
* taken to handle the case where either a.x or a.y is near zero.
*/
P[] solveDotProductConstrainedByNorm(double b, double C) {
P a = this;
if (a.isOrigin())
throw new Error("degenerate case");
boolean transpose = abs(a.x) > abs(a.y);
a = transpose ? new P(a.y, a.x) : a;
Double[] x = solvequadratic(a.length2(), 2.0 * b * a.x, b * b - a.y * a.y * C * C);
P[] p = new P[x.length];
for (int i = 0; i < x.length; i++) {
double x1 = x[i];
double x2 = ((-b - a.x * x1) / a.y);
p[i] = transpose ? new P(x2, x1) : new P(x1, x2);
}
return p;
}
@Override
public int compareTo(P that) {
if (abs(this.x - that.x) > EPS)
return Double.compare(this.x, that.x);
return Double.compare(this.y, that.y);
}
}
static class HP extends P { // Hashable Point
HP(double x, double y) {
super(x, y);
}
@Override
public int hashCode() {
return Double.hashCode(x + 32768 * y);
}
@Override
public boolean equals(Object _that) {
HP that = (HP) _that;
return this.x == that.x && this.y == that.y;
}
}
/**
* Sort points by polar angle relative to center, using trig. This is a
* counter-clockwise sort with zero at 3 o'clock.
*/
static Comparator<P> makePolarAngleComparatorTrig(final P center) {
return new Comparator<P>() {
public int compare(P a, P b) {
double thetaa = a.sub(center).theta();
double thetab = b.sub(center).theta();
if (thetaa < 0)
thetaa += 2 * PI;
if (thetab < 0)
thetab += 2 * PI;
int c = Double.compare(thetaa, thetab);
if (c != 0)
return c;
return Double.compare(b.x, a.x); // arbitrary tie-breaker
}
};
}
/**
* Sort points by polar angle relative to center, w/o trig. This is a
* counter-clockwise sort with zero at 3 o'clock.
*/
static Comparator<P> makePolarAngleComparator(final P center) {
return new Comparator<P>() {
public int compare(P a, P b) {
// orientation() requires that a and b lie in the same half-plane
if (a.y >= center.y && b.y < center.y)
return -1;
if (b.y >= center.y && a.y < center.y)
return 1;
int orientation = (int) Math.signum(center.signedParallelogramArea(b, a));
if (orientation != 0)
return orientation;
return Double.compare(b.x, a.x); // arbitrary tie-breaker
}
};
}
/*
* Solve a * x^2 + b * x + c == 0 Returns 0, 1, or 2 solutions. If 2 solutions
* x1, x2, guarantees that x1 < x2
*/
static Double[] solvequadratic(double a, double b, double c) {
double D = b * b - 4 * a * c;
if (D < -EPS)
return new Double[] {};
D = max(D, 0);
if (D == 0)
return new Double[] { -b / 2.0 / a };
double d = sqrt(D);
// Numerically more stable, see
// https://en.wikipedia.org/wiki/Loss_of_significance#A_better_algorithm
if (signum(b) == 0)
return new Double[] { d / 2.0 / a, -d / 2.0 / a };
double x1 = (-b - signum(b) * d) / (2 * a);
double x2 = c / (a * x1);
return new Double[] { Math.min(x1, x2), Math.max(x1, x2) };
}
/*
* The Line/Circle classes provide a number of methods that require dealing with
* floating point precision issues. Default EPS to a suitable value, such as
* 1e-6, which should work for many problems in which the input coordinates are
* in integers and subsequently inexact floating point values are being
* computed.
*/
static double EPS = 1e-6;
/*
* A line denoted by two points p and q. For internal computations, we use the
* parametric representation of the line as p + t d where d = q - p. For
* convenience, we compute and store d in the constructor. Most methods hide the
* parametric representation of the line, but it is exposed via
* getPointFromParameter and intersectionParameters for those problems that need
* it.
*
* The line may be interpreted either as a line segment denoted by the two end
* points, or as the infinite line determined by these two points. Intersection
* methods are provided for both cases.
*/
static class Line {
P p, q, d;
Line(P p, P q) {
this.p = p;
this.q = q;
d = q.sub(p);
}
P getPointFromParameter(double t) {
return p.add(d.scale(t));
}
// reflect vector across vector (as if line originated at (0, 0))
P reflect(P d2) {
return d.reflect(d2);
}
// reflect point across (infinite) line
P reflectPoint(P r) {
return reflect(r.sub(p)).add(p);
}
// project p onto this (infinite) line. Returns point on line
P project(P a) {
return p.add(d.project(a.sub(p)));
}
// return distance of point P from this (infinite) line.
double distance(P a) {
return project(a).dist(a);
}
@Override
public String toString() {
return String.format("[%s => %s]", p, q);
}
/*
* Point of intersection of this line segment with another line segment. Returns
* only points that lie inside both line segments, else null.
*
* Result may include points "just outside" the bounds, given EPS.
*/
P intersectsInBounds(Line l) {
double[] st = intersectionParameters(l);
if (st == null)
return null;
// check that point of intersection is in direction 'd'
// and within segment bounds
double s = st[0];
double t = st[1];
if (s >= -EPS && s <= 1 + EPS && -EPS <= t && t <= 1 + EPS)
return getPointFromParameter(s);
return null;
}
/*
* Point of intersection of this (infinite) line with other (infinite) line.
* Return null if collinear.
*/
P intersects(Line l) {
double[] st = intersectionParameters(l);
if (st != null)
return getPointFromParameter(st[0]);
return null;
}
/*
* Intersect this line with that line Solves: this.p + s * this.d == l.p + t l.d
* Return null if lines are collinear Else returns [s, t].
*/
double[] intersectionParameters(Line l) {
P dneg = p.sub(q);
double D = l.d.det(dneg);
// Use Cramer's rule; see text
if (D == 0.0)
return null;
P rp = p.sub(l.p);
return new double[] { l.d.det(rp) / D, rp.det(dneg) / D };
}
/*
* Compute points of intersection of this infinite line with a circle. Computes
* projection 'x' of c.c onto line, then computes x +/- d.scaleToLength(h) where
* h is computed via Pythagoras. Sorted by decreasing 't' (as would be used in
* getPointFromParameter)
*
* May return two points even if line is a tangent.
*/
P[] intersectsCircle(Circle c) {
P x = project(c.c);
double D = x.dist(c.c);
// outside by more than EPS
if (D > c.R + EPS)
return new P[0];
double h = sqrt(max(0, c.R * c.R - D * D));
if (h == 0)
return new P[] { x }; // EPS (!?)
return new P[] { x.add(d.scaleToLength(h)), x.add(d.scaleToLength(-h)) };
}
/*
* Compute points of intersection of this infinite line with a circle.
*
* Solves a + t * b = c + r subject to ||r|| = R Returns zero, one, or two
* points on the periphery, e.g. c + r[0,1], sorted by decreasing 't'.
* Alternative version which requires solving quadratic equation.
*
* Careful: set EPS if you need to handle round-off error in discriminant.
*/
P[] intersectsCircleAlternative(Circle c) {
P ca = c.c.sub(p);
P d = q.sub(p);
Double[] t = solvequadratic(d.length2(), -2 * d.dot(ca), ca.length2() - c.R * c.R);
P[] r = new P[t.length];
for (int i = 0; i < t.length; i++)
r[i] = p.add(d.scale(t[i]));
return r;
}
/**
* Is r contained within the line segment spanned by p/q, including their
* endpoints?
*/
boolean isInBounds(P r) {
return abs(p.dist(q) - p.dist(r) - q.dist(r)) <= EPS;
}
/**
* Is r on the infinite line?
*/
boolean isOnLine(P r) {
return r.isCollinearWith(p, q);
}
}
/**
* Alternative line implementation using the "general form" equation.
*
* a * x + b * y + c = 0
*
* This is provided for problems in which a line may be given in general form in
* the input. Compared to class Line, GLine: - is shorter, particularly when
* only line/line and line/circle intersections are required. - does not support
* those functions of Line that relate to LineSegment.
*/
static class GLine {
// we represent a, b as a vector to benefit from the available dot/det routines.
P n; // n = new P(a, b) --- this is the (right) normal vector to the line
double c;
GLine(double a, double b, double c) {
this.n = new P(a, b);
if (a == 0 && b == 0)
throw new Error("a and b cannot both be zero");
this.c = c;
}
GLine(P p, P q) {
this(p.y - q.y, q.x - p.x, p.det(q));
}
P intersects(GLine that) {
double D = n.det(that.n);
if (D == 0.0)
return null;
return new P((this.n.y * that.c - that.n.y * this.c) / D, (that.n.x * this.c - this.n.x * that.c) / D);
}
double signedDistance(P p) {
return (n.dot(p) + c) / n.length();
}
double distance(P p) {
return abs(signedDistance(p));
}
// checks if on (infinite) line.
boolean isOnLine(P p) {
return signedDistance(p) <= EPS;
}
// checks if on the same side, no EPS
boolean onSameSide(P p, P q) {
return signum(signedDistance(p)) == signum(signedDistance(q));
}
// angle of inclination to horizontal; result is in [0, pi] rad
// XXX untested
double theta() {
double angle = atan2(n.x, -n.y);
return angle < 0 ? (angle + PI) : angle;
}
// XXX untested
boolean parallelWith(GLine that) {
return n.det(that.n) <= EPS;
}
// XXX untested
boolean perpendicularTo(GLine that) {
return n.dot(that.n) <= EPS;
}
// circle-line intersection, refactored from
// https://e-maxx-eng.appspot.com/geometry/circle-line-intersection.html
P[] intersectsCircle(Circle C) {
// shift line to center, this is undone by adding C.c before returning.
double c = n.dot(C.c) + this.c;
double n2 = n.length2();
double r = C.R;
P p = n.scale(-c / n2).add(C.c); // undo shift to center
if (c * c > r * r * n2 + EPS) {
return new P[] {};
} else if (abs(c * c - r * r * n2) < EPS) {
return new P[] { p };
} else {
double d = r * r - c * c / n2;
double m = sqrt(d / n2);
P q = n.rightNormal().scale(m);
return new P[] { p.add(q), p.sub(q) };
}
}
@Override
public String toString() {
return String.format("Line:(n=%s C=%f)", n, c);
}
}
static class Circle {
P c;
double R;
Circle(P c, double R) {
this.c = c;
this.R = R;
}
@Override
public String toString() {
return String.format("{%s, %.03f}", c, R);
}
/* Is this point inside the circle */
boolean isInside(P p) {
return R > p.dist(c) - EPS;
}
/* Is this point on the circle's periphery */
boolean isOnCircle(P p) {
return abs(p.dist(c) - R) <= EPS;
}
/*
* a line segment is outside a circle if both end points are outside and if any
* intersection points are outside the bounds of the line segment.
*/
boolean isOutside(Line l) {
if (isInside(l.p) || isInside(l.q))
return false;
P[] _is = l.intersectsCircle(this);
if (_is.length > 1)
for (P is : _is)
if (l.isInBounds(is))
return false;
return true;
}
/* Returns the tangent lines that the point p makes with this circle, if any. */
Line[] tangentLines(P p) {
// Let c +/- r be the tangent points. Then there's a 'd' such that
// p + d - r = c
// Since d r = 0, we multiply by r and get
// (p - c) r - ||r|| = 0 subject to ||r|| = R
P[] r = p.sub(c).solveDotProductConstrainedByNorm(-R * R, R);
Line[] tangents = new Line[r.length];
for (int i = 0; i < tangents.length; i++)
tangents[i] = new Line(p, c.add(r[i]));
return tangents;
}
/*
* Compute points of intersection of this circle (c1, r1) with that circle (c2,
* r2). Model as triangle equation m = c2 - c1 = r1 - r2 m = r1 - r2 -> m^2 =
* r1^2 + r2^2 - 2 r1 r2 (squaring) -> r1 r2 = (r1^2 + r2^2 - m^2)/2 and by
* multiplying by r1 we obtain m = r1 - r2 -> m r1 = r1^2 - r1 r2 -> m r1 = r1^2
* - (r1^2 + r2^2 - m^2)/2 -> m r1 + (r2^2 - r1^2 - m^2)/2 = 0 and ready for
* solveDotProductConstrainedByNorm
*
* Note that if the circles are (apprx) touching, this function may return 0, 1,
* or 2 intersection points, depending on which side of 0 the discriminant
* falls. You will not get NaN.
*
* If the circles coincidence (same center and radius) this will throw an
* 'degenerate case' error in solveDotProductConstrainedByNorm !!!
*/
P[] intersectsCircle(Circle that) {
double r1 = this.R;
double r2 = that.R;
P m = that.c.sub(this.c);
P[] r1sol = m.solveDotProductConstrainedByNorm((r2 * r2 - r1 * r1 - m.length2()) / 2, r1);
// compute [c +/- r1] to obtain intersection points
P[] is = new P[r1sol.length];
for (int i = 0; i < r1sol.length; i++)
is[i] = this.c.add(r1sol[i]);
return is;
}
/*
* Shorter version of intersectsCircle that solves quadratic equation inline.
* Assumes there are 2 intersection points. The vector 'mid' is where the
* altitude of the triangle formed by the centers and the intersection point
* hits the line connecting the centers. Its length is e. midn is normal to it
* and its length is f.
*/
P[] intersectsCircleAlternative(Circle that) {
P m = that.c.sub(this.c);
double b = this.R * this.R;
// div-by-zero if circles share center
double e = (m.length2() + b - that.R * that.R) / 2 / m.length();
double f = sqrt(b - e * e); // NaN if circles don't intersect
P[] is = new P[2];
P mid = this.c.add(m.scaleToLength(e));
P midn = m.rightNormal();
for (int i = 0; i < is.length; i++) {
is[i] = mid.add(midn.scaleToLength(f));
f *= -1;
}
return is;
}
// returns true if this circle is outside that circle
boolean isOutside(Circle that) {
return this.c.dist(that.c) > (this.R + that.R);
}
// returns true if this circle is entirely contained inside that circle
boolean isContainedIn(Circle that) {
// extend line from that.c to this.c by radius R
P m = this.c.sub(that.c);
return that.isInside(this.c.add(m.scaleToLength(this.R)));
}
/* Construct smallest circle that circumscribes 2 points a and b. */
static Circle getCircumCircle(P a, P b) {
P c = a.add(b).scale(.5);
return new Circle(c, c.dist(a));
}
/* Construct circle circumscribed by 3 points a, b, c */
static Circle getCircumCircle(P a, P b, P c) {
P B = b.sub(a);
P C = c.sub(a);
double d = 2 * B.crossproduct(C);
if (abs(d) < EPS) // points are collinear
return getCircumCircle(new P(min(a.x, min(b.x, c.x)), min(a.y, min(b.y, c.y))),
new P(max(a.x, max(b.x, c.x)), max(a.y, max(b.y, c.y))));
double z1 = B.length2();
double z2 = C.length2();
P cc = new P(C.y * z1 - B.y * z2, B.x * z2 - C.x * z1).scale(1.0 / d);
return new Circle(cc.add(a), cc.length());
}
/*
* Find minimum enclosing circle for a set of points. Peter, we need a source
* for this algorithm and its expected complexity.
*/
static Circle minEnclosingCircle(P[] p) {
if (p.length == 0)
return new Circle(new P(0, 0), 0);
if (p.length == 1)
return new Circle(p[0], 0);
Collections.shuffle(Arrays.asList(p));
Circle circle = getCircumCircle(p[0], p[1]);
for (int i = 2; i < p.length; i++) {
if (!circle.isInside(p[i])) {
circle = getCircumCircle(p[0], p[i]);
for (int j = 1; j < i; j++) {
if (!circle.isInside(p[j])) {
circle = getCircumCircle(p[j], p[i]);
for (int k = 0; k < j; k++) {
if (!circle.isInside(p[k])) {
circle = getCircumCircle(p[i], p[j], p[k]);
}
}
}
}
}
}
return circle;
}
}
/**
* Some basic operations on Polygons.
*/
static class Polygon {
P[] p; // open form, p[0] connects to p[n-1]
// Constructors clone original array/collection
Polygon(Collection<P> c) {
this.p = c.toArray(new P[c.size()]);
}
Polygon(P[] p) {
this.p = (P[]) p.clone();
}
/* Absolute of signed triangle areas */
double signedArea() {
double area = 0.0;
for (int i = 0; i < p.length; i++) {
area += p[i].det(p[(i + 1) % p.length]);
}
return area / 2.0;
}
double absoluteArea() {
return abs(signedArea());
}
/*
* Returns an P[] array representing an open shape that is the convex hull of
* the given array of points, or null if less than 2 points were given.
*/
public Polygon convexHull() {
if (p.length < 2)
return null;
// (0) find the lowest point, breaking ties to the right
final P min = Collections.min(Arrays.asList(p), new Comparator<P>() {
public int compare(P p1, P p2) {
int y = Double.valueOf(p1.y).compareTo(p2.y);
return y != 0 ? y : Double.valueOf(p1.x).compareTo(p2.x);
}
});
// (1) sort points by angle from pivot
Arrays.sort(p, new Comparator<P>() {
public int compare(P p1, P p2) {
double o = min.signedParallelogramArea(p1, p2); // crossproduct
if (o != 0)
return -(int) Math.signum(o);
// if collinear, use distance to break tie
return Double.valueOf(min.dist(p1)).compareTo(min.dist(p2));
}
});
// (3) create stack
Stack<P> hull = new Stack<P>();
assert p[0] == min;
hull.push(p[0]);
hull.push(p[1]);
// (4) select points that maintain left turns
for (int i = 2; i < p.length; i++) {
P next = p[i];
while (hull.size() >= 2) {
P snd = hull.get(hull.size() - 2);
P top = hull.peek();
if (snd.isCCW(top, next)) // keep
break;
hull.pop(); // discard
}
// keep current point
hull.push(next);
}
return new Polygon(hull);
}
/*
* "Point-in-Polygon" PIP tests. Return true if point is contained in this
* polygon
*
* All of these tests may return 0 or 1 for points on the boundary. A separate
* test is required to determine if a point is on the boundary.
*/
public boolean contains(P q) {
return contains_WN(q);
}
/*
* Crossing-number based algorith due to Wm. Randolph Franklin. Works only for
* simple polygons.
*/
private boolean contains_CN(P q) {
boolean c = false;
for (int i = 0, j = p.length - 1; i < p.length; j = i++) {
if ((((p[i].y <= q.y) && (q.y < p[j].y)) || ((p[j].y <= q.y) && (q.y < p[i].y)))
&& (q.x < (p[j].x - p[i].x) * (q.y - p[i].y) / (p[j].y - p[i].y) + p[i].x))
c = !c;
}
return c;
}
/*
* Winding numbers based algorithm, which also works for self-intersecting
* polygons. http://geomalgorithms.com/a03-_inclusion.html describes this as the
* always preferred algorithm.
*
* Return: wn = the winding number (=0 only when P is outside)
*/
public boolean contains_WN(P q) {
int wn = 0; // the winding number counter
// loop through all edges of the polygon
int n = p.length;
for (int i = 0; i < n; i++) { // edge from V[i] to V[i+1]
P p = this.p[i], pn = this.p[(i + 1) % n];
if (p.y <= q.y) { // start y <= P.y
if (pn.y > q.y) // an upward crossing
if (p.isCCW(pn, q)) // P left of edge
++wn; // have a valid up intersect
} else { // start y > P.y (no test needed)
if (pn.y <= q.y) // a downward crossing
if (!p.isCCW(pn, q)) // P right of edge
--wn; // have a valid down intersect
}
}
return wn != 0;
}
/**
* Is q on the boundary of this polygon?
*/
public boolean onBoundary(P q) {
int n = p.length;
for (int i = 0; i < n; i++) {
P pi = this.p[i], pj = this.p[(i + 1) % n];
if (new Line(pi, pj).isInBounds(q))
return true;
}
return false;
}
@Override
public String toString() {
return Arrays.toString(p);
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextLong();
}
return a;
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
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.math.BigInteger;
import java.util.StringTokenizer;
public class A {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
BigInteger a = new BigInteger(next());
System.out.println(BigInteger.valueOf(5).modPow(a, BigInteger.valueOf(100)));
pw.close();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
for (int i = 0; i < n; i++) b[i] = sc.nextInt();
int c[] = new int[2 * n];
c[0] = a[0];
for (int i = 1; i < n; i++) {
c[i * 2] = a[i];
c[i * 2 - 1] = b[i];
if (a[i] == 1 || b[i] == 1) {
System.out.print(-1);
System.exit(0);
}
}
c[2 * n - 1] = b[0];
if (a[0] == 1 || b[0] == 1) {
System.out.print(-1);
System.exit(0);
}
System.out.println(bin_search(c, m));
}
private static double bin_search(int[] c, int m) {
double start = 0;
double end = Integer.MAX_VALUE;
double mid;
while (start + 0.0000001 < end) {
mid = (start + end) / 2;
if (test(mid, m, c)) end = mid;
else start = mid;
}
return end;
}
private static boolean test(double fuel, int m, int[] c) {
for (int i = 0; i < c.length; i++) {
fuel -= (m + fuel) / c[i];
if (fuel < 0) {
return false;
}
}
return true;
}
}
|
nlogn
|
1010_A. Fly
|
CODEFORCES
|
import jdk.nashorn.internal.objects.NativeArray;
import javax.swing.JOptionPane ;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import java.sql.SQLSyntaxErrorException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Vector;
import static jdk.nashorn.internal.objects.NativeArray.sort;
import static jdk.nashorn.internal.runtime.ScriptObject.toPropertyDescriptor;
public class Dialog1 {
private static int n ;
private static String s ;
private static char[] a;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
n = input.nextInt() ;
s = input.next() ;
a = s.toCharArray();
for(int i = 0 ; i < 200 ; ++i) {
int cur = i ;
boolean fl = true ;
for(int j = 0 ; j < n ; ++j) {
if(a[j] == '+')
++cur ;
else
--cur ;
if(cur < 0)
fl = false ;
}
if(fl) {
System.out.print(cur);
return ;
}
}
}
}
|
linear
|
1159_A. A pile of stones
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
static Scanner sc;
static PrintWriter out;
public static void main(String[] args) {
sc = new Scanner(System.in);
out = new PrintWriter(System.out);
int t = 1;
if (true) {
t = sc.nextInt();
}
for(int i=0; i<t; i++) {
new Main().solve();
}
out.flush();
}
public void solve() {
long n = sc.nextInt();
if(n % 2 == 1) {
out.println("NO");
return;
}
for(long i=1; i*i*2 <= n; i++) {
if(i * i * 2 == n || i * i * 4 == n) {
out.println("YES");
return;
}
}
out.println("NO");
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer=null;
public static void main(String[] args) throws IOException
{
new Main().execute();
}
void debug(Object...os)
{
System.out.println(Arrays.deepToString(os));
}
int ni() throws IOException
{
return Integer.parseInt(ns());
}
long nl() throws IOException
{
return Long.parseLong(ns());
}
double nd() throws IOException
{
return Double.parseDouble(ns());
}
String ns() throws IOException
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(br.readLine());
return tokenizer.nextToken();
}
String nline() throws IOException
{
tokenizer=null;
return br.readLine();
}
//Main Code starts Here
int totalCases, testNum;
int sum;
int n;
int arr[];
void execute() throws IOException
{
totalCases = 1;
for(testNum = 1; testNum <= totalCases; testNum++)
{
if(!input())
break;
solve();
}
}
void solve() throws IOException
{
Arrays.sort(arr);
int count = 0;
int ans = 0;
for(int i = n-1;i>=0;i--)
{
count+= arr[i];
if(count>sum-count)
{
ans = n-i;
break;
}
}
System.out.println(ans);
}
boolean input() throws IOException
{
n = ni();
sum = 0;
arr = new int[n];
for(int i = 0;i<n;i++)
{
arr[i] = ni();
sum = sum+arr[i];
}
return true;
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
public class Array implements Runnable {
void solve() throws IOException {
int n = readInt();
int k = readInt();
int a[] = new int[n];
int startIdx = 0;
int endIdx = -1;
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0; i < n; i ++) {
a[i] = readInt();
if(map.containsKey(a[i]))
map.put(a[i], map.get(a[i]) + 1);
else
map.put(a[i], 1);
if(map.size() == k && endIdx == -1) {
endIdx = i;
break;
}
}
if(endIdx != -1) {
while(startIdx < n && map.get(a[startIdx])>1) {
map.put(a[startIdx], map.get(a[startIdx]) - 1);
startIdx ++;
}
startIdx ++;
endIdx ++;
} else
startIdx = -1;
out.println((startIdx)+" "+(endIdx));
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args) {
new Array().run();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
if (System.getProperty("ONLINE_JUDGE") != null) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("/Users/shenchen/input.txt"));
out = new PrintWriter("/Users/shenchen/output.txt");
}
Locale.setDefault(Locale.US);
solve();
in.close();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Throwable t) {
t.printStackTrace(System.err);
System.exit(-1);
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
import java.util.Scanner;
public class SportMafia {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int next = 1;
int current = 0;
int result = 0;
for(int i = 0; i < n; i++) {
if(current < k) {
current += next++;
} else {
current--;
result++;
}
}
System.out.println(result);
sc.close();
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
/**
* author: derrick20
* created: 3/20/21 7:13 PM
*/
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class E2_SquareFreeFast {
static FastScanner sc = new FastScanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
// generate();
int T = sc.nextInt();
int MAX = (int) 1e7;
int[] canonical = new int[MAX + 1];
canonical[1] = 1;
for (int factor = 2; factor <= MAX; factor++) {
if (canonical[factor] == 0) {
for (int mult = factor; mult <= MAX; mult += factor) {
int prev = canonical[mult / factor];
if (prev % factor == 0) {
canonical[mult] = prev / factor;
} else {
canonical[mult] = prev * factor;
}
}
}
}
int[] last = new int[MAX + 1];
while (T-->0) {
int N = sc.nextInt();
int K = sc.nextInt();
int[] a = new int[N + 1];
int[][] dp = new int[2][K + 1];
int[][] start = new int[2][K + 1];
int ptr = 0;
for (int i = 1; i <= N; i++) {
int nxt = 1 ^ ptr;
a[i] = canonical[sc.nextInt()];
for (int k = 0; k <= K; k++) {
if (start[ptr][k] > last[a[i]]) {
// extend it for free (unique)
dp[nxt][k] = dp[ptr][k];
start[nxt][k] = start[ptr][k];
} else {
// start anew
dp[nxt][k] = dp[ptr][k] + 1;
start[nxt][k] = i;
}
// Use a change (only if existing segment)
if (i > 1 && k > 0 && start[ptr][k - 1] <= last[a[i]]) {
// if this cost beats the old cost, or if it has a later start point, it's better.
if (dp[ptr][k - 1] < dp[nxt][k] || (dp[ptr][k - 1] == dp[nxt][k] && start[ptr][k - 1] > start[nxt][k])) {
dp[nxt][k] = dp[ptr][k - 1];
start[nxt][k] = start[ptr][k - 1];
}
}
}
// System.out.println(Arrays.toString(start[nxt]));
// System.out.println(Arrays.toString(dp[nxt]));
last[a[i]] = i;
ptr = nxt;
}
for (int v : a) {
last[v] = 0;
}
// always allowed to waste initial changes by starting offset, so mono decr
out.println(dp[ptr][K]);
}
out.close();
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
int nextInt() {
return (int) nextLong();
}
long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
double nextDouble() {
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
double cur = nextLong();
if (c != '.') {
return neg ? -cur : cur;
} else {
double frac = nextLong() / cnt;
return neg ? -cur - frac : cur + frac;
}
}
String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static void ASSERT(boolean assertion, String message) {
if (!assertion) throw new AssertionError(message);
}
static void ASSERT(boolean assertion) {
if (!assertion) throw new AssertionError();
}
}
|
cubic
|
1497E2
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int n = Reader.nextInt();
int[] arr = new int[n];
int initial = 0;
for (int i = 0; i < n; i++) arr[i] = Reader.nextInt();
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) if (arr[i] > arr[j]) initial++;
}
int m = Reader.nextInt();
boolean parity = initial % 2 == 0;
// System.out.println(parity ? "even": "odd");
for (int i = 0; i < m; i++) {
int l = Reader.nextInt();
int r = Reader.nextInt();
int elems = r - l + 1;
boolean change = (elems/2) % 2 == 0;
parity = parity == change;
System.out.println(parity ? "even": "odd");
}
}
}
/**
* Reader class based on the article at "https://www.cpe.ku.ac.th/~jim/java-io.html"
* */
class Reader{
private static BufferedReader reader;
private static StringTokenizer tokenizer;
static void init(InputStream inputStream){
reader = new BufferedReader(new InputStreamReader(inputStream));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
String read;
while (!tokenizer.hasMoreTokens()){
read = reader.readLine();
if (read == null || read.equals(""))
return "-1";
tokenizer = new StringTokenizer(read);
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException{
return Integer.parseInt(next());
}
// static long nextLong() throws IOException{
// return Long.parseLong(next());
// }
//Get a whole line.
// static String line() throws IOException{
// return reader.readLine();
// }
//
// static double nextDouble() throws IOException{return Double.parseDouble(next());}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.*;
public class b {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n = input.nextInt(), k = input.nextInt();
int[] data = new int[n];
for(int i = 0; i<n; i++)
data[i] = input.nextInt();
int[] freq = new int[100001];
int count = 0;
for(int i = 0; i<n; i++)
{
if(freq[data[i]] == 0)
count++;
freq[data[i]]++;
}
if(count<k)
System.out.println("-1 -1");
else
{
int start = 0;
for(int i = 0; i<n; i++)
{
//System.out.println(i + " " + count + " " + freq[data[i]]);
if(count > k)
{
freq[data[i]]--;
if(freq[data[i]] == 0)
count--;
}
else
{
if(freq[data[i]] > 1)
{
freq[data[i]]--;
}
else
{
start = i;
break;
}
}
}
int end = n-1;
for(int i = n-1; i>=0; i--)
{
if(freq[data[i]] == 1)
{
end = i;
break;
}
else
freq[data[i]]--;
}
start++;
end++;
if(start<= end)
System.out.println(start + " " + end);
else
System.out.println(-1 + " " + -1);
}
}
}
|
linear
|
224_B. Array
|
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(){
work();
out.flush();
}
long mod=998244353;
long gcd(long a,long b) {
return b==0?a:gcd(b,a%b);
}
void work() {
int n=in.nextInt();
int[] A=new int[n];
for(int i=0;i<n;i++)A[i]=in.nextInt();
HashMap<Integer,Integer> map=new HashMap<>();
HashMap<Integer,ArrayList<int[]>> rec=new HashMap<>();
for(int i=0;i<n;i++) {
for(int j=i,cur=0;j>=0;j--) {
cur+=A[j];
if(map.get(cur)==null) {
map.put(cur,i);
rec.put(cur,new ArrayList<>());
rec.get(cur).add(new int[] {j,i});
}else if(map.get(cur)<j) {
map.put(cur,i);
rec.get(cur).add(new int[] {j,i});
}
}
}
ArrayList<int[]> ret=null;
for(ArrayList<int[]> list:rec.values()) {
if(ret==null||ret.size()<list.size()) {
ret=list;
}
}
out.println(ret.size());
for(int[] r:ret) {
out.println((r[0]+1)+" "+(r[1]+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());
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
long a = in.nextLong();
long b = in.nextLong();
long res = 0;
while (b > 0) {
res += a / b;
long t = a % b;
a = b;
b = t;
}
out.println(res);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class con169_D {
private static final boolean DEBUG = false;
public static void main( final String[] args ) throws Exception {
final BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
final String line = br.readLine();
final StringTokenizer tok = new StringTokenizer( line );
final long L = Long.parseLong( tok.nextToken() );
final long R = Long.parseLong( tok.nextToken() );
System.out.println( solve( L, R ) );
}
public static long solve( final long L, final long R ) {
if ( L == R ) return L ^ R;
if ( DEBUG ) System.out.printf( "L=%d (%s), R=%d (%s)\n", L, Long.toBinaryString( L ), R,
Long.toBinaryString( R ) );
final int ld = length( L );
final int ldm1 = ld - 1;
final int rd = length( R );
if ( ld < rd ) {
long max = 1;
while ( length( max ) < rd ) {
max <<= 1;
}
long min = 1;
while ( length( min ) < rd - 1 ) {
min <<= 1;
++min;
}
if ( DEBUG ) System.out.printf( "min=%d (%s), max=%d (%s)\n", min, Long.toBinaryString( min ), max,
Long.toBinaryString( max ) );
return min ^ max;
} else {
final char[] minStr = Long.toBinaryString( L ).toCharArray();
final char[] maxStr = Long.toBinaryString( R ).toCharArray();
final char[] res = new char[minStr.length];
Arrays.fill( res, '0' );
{
int i = 0;
while ( i < res.length ) {
if ( minStr[ i ] == maxStr[ i ] ) {
res[ i ] = '0';
} else {
break;
}
++i;
}
if ( DEBUG ) System.out.println( "diff at pos: " + i );
if ( minStr[ i ] == '0' ) {
res[ i++ ] = '1';
for ( int j = i; j < res.length; ++j ) {
res[ j ] = '1';
}
} else {
throw new IllegalArgumentException();
}
}
return Long.parseLong( new String( res ), 2 );
}
}
private static int length( long l ) {
int res = 0;
while ( l > 0 ) {
++res;
l >>= 1;
}
return res;
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.lang.*;
import java.math.BigInteger;
import java.io.*;
import java.util.*;
public class Solution implements Runnable{
public static BufferedReader br;
public static PrintWriter out;
public static StringTokenizer stk;
public static boolean isStream = true;
public static void main(String[] args) throws IOException {
if (isStream) {
br = new BufferedReader(new InputStreamReader(System.in));
} else {
br = new BufferedReader(new FileReader("in.txt"));
}
out = new PrintWriter(System.out);
new Thread(new Solution()).start();
}
public void loadLine() {
try {
stk = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public String nextWord() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return stk.nextToken();
}
public Integer nextInt() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return Integer.valueOf(stk.nextToken());
}
public Long nextLong() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return Long.valueOf(stk.nextToken());
}
public Double nextDouble() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return Double.valueOf(stk.nextToken());
}
public Float nextFloat() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return Float.valueOf(stk.nextToken());
}
public void run() {
int n = nextInt();
int m = nextInt();
if (n > m) {
int sw = n;
n = m;
m = sw;
}
int[][] A = new int[1<<n][1<<n];
for (int m1 = 0; m1 < 1<<n; ++m1) { // Who goes out
for (int m2 = 0; m2 < 1<<n; ++m2) { // Who comes
int[] arr = new int[n]; // Who remains
for (int i = 0; i < n; ++i) {
arr[i] = (~(m1>>i))&1;
}
int[] m2a = new int[n];
for (int i = 0; i < n; ++i) {
m2a[i] = (m2>>i)&1;
}
int cnt = 0;
for (int i = 0; i < n; ++i) {
if (arr[i] == 1) {
if (i > 0 && m2a[i-1] == 1) {
continue;
}
if (i < n-1 && m2a[i+1] == 1) {
continue;
}
if (m2a[i] == 1) {
continue;
}
if (i < n-1) {
m2a[i+1] = 1;
} else {
m2a[i] = 1;
}
}
}
for (int i = 0; i < n; ++i) {
if (m2a[i] == 1) {
cnt++;
}
}
A[m1][m2] = cnt;
}
}
int MAX = 10000;
int[][][] dp = new int[m+1][1<<n][1<<n];
for (int i = 0; i < m+1; i++) {
for (int m1 = 0; m1 < 1<<n; ++m1) {
Arrays.fill(dp[i][m1], MAX);
}
}
dp[0][0][0] = 0;
for (int i = 0; i < m; i++) {
for (int m1 = 0; m1 < 1<<n; ++m1) {
for (int m2 = 0; m2 < 1<<n; ++m2) {
if (dp[i][m1][m2] != MAX) {
for (int nm1 = 0; nm1 < 1<<n; ++nm1) {
for (int nm2 = 0; nm2 < 1<<n; ++nm2) {
if ((m1 & nm1) == 0) {
int sm1 = m1|nm1;
int sm2 = m2|nm2;
int cnt = A[sm1][sm2];
dp[i+1][nm2][nm1] = Math.min(dp[i+1][nm2][nm1], dp[i][m1][m2]+cnt);
}
}
}
}
}
}
}
out.println(n*m-dp[m][0][0]);
out.flush();
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
/**
* @author Ran Bi (ran.bi@addepar.com)
*/
public class C {
public static void main(String[] arg) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.valueOf(in.readLine());
char[] s = in.readLine().toCharArray();
int i = 0, j = 0;
int[] ct = new int[256];
Set<Character> all = new HashSet<>();
for (char c : s) {
all.add(c);
}
int total = 0, res = Integer.MAX_VALUE;
while (j < s.length) {
while (total < all.size() && j < s.length) {
if (ct[s[j]] == 0) {
total++;
}
ct[s[j]]++;
j++;
}
res = Math.min(res, j - i);
while (total == all.size() && i < s.length) {
ct[s[i]]--;
if (ct[s[i]] == 0) {
total--;
}
i++;
if (total == all.size()) {
res = Math.min(res, j - i);
}
}
}
System.out.println(res);
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class C {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
List<String> commands = IntStream.range(0, n).boxed().map(x -> s.next()).collect(Collectors.toList());
List<Integer> ways = new ArrayList<>();
ways.add(1);
boolean lastWasS = false;
for (String command : commands) {
boolean isS = "s".equals(command);
if (lastWasS) {
for (int i = 1; i < ways.size(); ++i) {
int waysNumber = (ways.get(i-1) + ways.get(i)) % 1_000_000_007;
ways.set(i, waysNumber);
}
}
if (!isS) {
ways.add(0);
}
lastWasS = isS;
}
System.out.println(ways.stream().reduce(0, (a, b) -> (a + b) % 1_000_000_007));
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.util.*;
import javax.lang.model.util.ElementScanner6;
import java.io.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(inp, out);
out.close();
}
static class Solver {
class pair implements Comparable<pair>{
int i;
long dist;
public pair(int i,long dist)
{
this.i=i;
this.dist=dist;
}
public int compareTo(pair p)
{
return Long.compare(this.dist,p.dist);
}
}
class Node implements Comparable < Node > {
int i;
int cnt;
Node(int i, int cnt) {
this.i = i;
this.cnt = cnt;
}
public int compareTo(Node n) {
if (this.cnt == n.cnt) {
return Integer.compare(this.i, n.i);
}
return Integer.compare(this.cnt, n.cnt);
}
}
public boolean done(int[] sp, int[] par) {
int root;
root = findSet(sp[0], par);
for (int i = 1; i < sp.length; i++) {
if (root != findSet(sp[i], par))
return false;
}
return true;
}
public int findSet(int i, int[] par) {
int x = i;
boolean flag = false;
while (par[i] >= 0) {
flag = true;
i = par[i];
}
if (flag)
par[x] = i;
return i;
}
public void unionSet(int i, int j, int[] par) {
int x = findSet(i, par);
int y = findSet(j, par);
if (x < y) {
par[y] = x;
} else {
par[x] = y;
}
}
public long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
public boolean isPrime(int n)
{
for(int i=2;i<n;i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
public void minPrimeFactor(int n, int[] s) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
s[1] = 1;
s[2] = 2;
for (int i = 4; i <= n; i += 2) {
prime[i] = false;
s[i] = 2;
}
for (int i = 3; i <= n; i += 2) {
if (prime[i]) {
s[i] = i;
for (int j = 2 * i; j <= n; j += i) {
prime[j] = false;
s[j] = i;
}
}
}
}
public void findAllPrime(int n, ArrayList < Node > al, int s[]) {
int curr = s[n];
int cnt = 1;
while (n > 1) {
n /= s[n];
if (curr == s[n]) {
cnt++;
continue;
}
Node n1 = new Node(curr, cnt);
al.add(n1);
curr = s[n];
cnt = 1;
}
}
public int binarySearch(int n, int k) {
int left = 1;
int right = 100000000 + 5;
int ans = 0;
while (left <= right) {
int mid = (left + right) / 2;
if (n / mid >= k) {
left = mid + 1;
ans = mid;
} else {
right = mid - 1;
}
}
return ans;
}
public boolean checkPallindrom(String s) {
char ch[] = s.toCharArray();
for (int i = 0; i < s.length() / 2; i++) {
if (ch[i] != ch[s.length() - 1 - i])
return false;
}
return true;
}
public void remove(ArrayList < Integer > [] al, int x) {
for (int i = 0; i < al.length; i++) {
for (int j = 0; j < al[i].size(); j++) {
if (al[i].get(j) == x)
al[i].remove(j);
}
}
}
public long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public void printDivisors(long n, ArrayList < Long > al) {
// Note that this loop runs till square root
for (long i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
// If divisors are equal, print only one
if (n / i == i) {
al.add(i);
} else // Otherwise print both
{
al.add(i);
al.add(n / i);
}
}
}
}
public static long constructSegment(long seg[], long arr[], int low, int high, int pos) {
if (low == high) {
seg[pos] = arr[low];
return seg[pos];
}
int mid = (low + high) / 2;
long t1 = constructSegment(seg, arr, low, mid, (2 * pos) + 1);
long t2 = constructSegment(seg, arr, mid + 1, high, (2 * pos) + 2);
seg[pos] = t1 + t2;
return seg[pos];
}
public static long querySegment(long seg[], int low, int high, int qlow, int qhigh, int pos) {
if (qlow <= low && qhigh >= high) {
return seg[pos];
} else if (qlow > high || qhigh < low) {
return 0;
} else {
long ans = 0;
int mid = (low + high) / 2;
ans += querySegment(seg, low, mid, qlow, qhigh, (2 * pos) + 1);
ans += querySegment(seg, mid + 1, high, qlow, qhigh, (2 * pos) + 2);
return ans;
}
}
public static int lcs(char[] X, char[] Y, int m, int n) {
if (m == 0 || n == 0)
return 0;
if (X[m - 1] == Y[n - 1])
return 1 + lcs(X, Y, m - 1, n - 1);
else
return Integer.max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));
}
public static long recursion(long start, long end, long cnt[], int a, int b) {
long min = 0;
long count = 0;
int ans1 = -1;
int ans2 = -1;
int l = 0;
int r = cnt.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (cnt[mid] >= start) {
ans1 = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
l = 0;
r = cnt.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (cnt[mid] <= end) {
ans2 = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
if (ans1 == -1 || ans2 == -1 || ans2 < ans1) {
// System.out.println("min1 "+min);
min = a;
return a;
} else {
min = b * (end - start + 1) * (ans2 - ans1 + 1);
}
if (start == end) {
// System.out.println("min "+min);
return min;
}
long mid = (end + start) / 2;
min = Long.min(min, recursion(start, mid, cnt, a, b) + recursion(mid + 1, end, cnt, a, b));
// System.out.println("min "+min);
return min;
}
public int dfs_util(ArrayList < Integer > [] al, boolean vis[], int x, int[] s, int lvl[]) {
vis[x] = true;
int cnt = 1;
for (int i = 0; i < al[x].size(); i++) {
if (!vis[al[x].get(i)]) {
lvl[al[x].get(i)] = lvl[x] + 1;
cnt += dfs_util(al, vis, al[x].get(i), s, lvl);
}
}
s[x] = cnt;
return s[x];
}
public void dfs(ArrayList[] al, int[] s, int[] lvl) {
boolean vis[] = new boolean[al.length];
for (int i = 0; i < al.length; i++) {
if (!vis[i]) {
lvl[i] = 1;
dfs_util(al, vis, i, s, lvl);
}
}
}
public int[] computeLps(String s)
{
int ans[] =new int[s.length()];
char ch[] = s.toCharArray();
int n = s.length();
int i=1;
int len=0;
ans[0]=0;
while(i<n)
{
if(ch[i]==ch[len])
{
len++;
ans[i]=len;
i++;
}
else
{
if(len!=0)
{
len=ans[len-1];
}
else
{
ans[i]=len;
i++;
}
}
}
return ans;
}
private void solve(InputReader inp, PrintWriter out1) {
int n = inp.nextInt();
int m = inp.nextInt();
long k = inp.nextLong();
long arr[] = new long[n];
for(int i=0;i<n;i++)
{
arr[i] = inp.nextLong();
}
long ans=0;
for(int i=0;i<m;i++)
{
long sum=0;
for(int j=i;j<n;j++)
{
if(j%m==i)
{
if(sum<0)
{
sum=0;
}
sum-=k;
}
sum+=arr[j];
ans=Math.max(ans,sum);
}
}
System.out.println(ans);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
class ele implements Comparable < ele > {
int value;
int i;
boolean flag;
public ele(int value, int i) {
this.value = value;
this.i = i;
this.flag = false;
}
public int compareTo(ele e) {
return Integer.compare(this.value, e.value);
}
}
|
quadratic
|
1197_D. Yet Another Subarray Problem
|
CODEFORCES
|
import java.util.*;
import java.math.*;
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
Scanner c = new Scanner(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new File("output.txt"));
int N=c.nextInt();
int M=c.nextInt();
int A[][]=new int[N][M];
for(int i=0;i<N;i++)
Arrays.fill(A[i],Integer.MAX_VALUE/100);
int K=c.nextInt();
for(int i=0;i<K;i++)
{
int x=c.nextInt()-1;
int y=c.nextInt()-1;
for(int i1=0;i1<N;i1++)
{
for(int j1=0;j1<M;j1++)
A[i1][j1]=Math.min(A[i1][j1],Math.abs(i1-x)+Math.abs(j1-y));
}
}
int maxi=0;
int maxj=0;
for(int i=0;i<N;i++)
{
for(int j=0;j<M;j++)
{
if(A[i][j]>A[maxi][maxj])
{
maxi=i;
maxj=j;
}
}
}
out.println((maxi+1)+" "+(maxj+1));
out.close();
}
}
//must declare new classes here
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
public class D5 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int a = input.nextInt(), v = input.nextInt();
int l = input.nextInt(), d = input.nextInt(), w = input.nextInt();
double lo = 0, hi = v;
for(int iter = 0; iter < 1000; iter++)
{
double mid = (lo+hi)/2;
if(can(mid, a, d, w)) lo = mid;
else hi = mid;
}
//System.out.println(lo);
double t1 = lo / a;
double gone = .5 * t1 * t1 * a;
if(lo > w)
{
gone += -a * .5 * (lo - w) / a * (lo - w) / a + lo * (lo - w) / a;
t1 += (lo - w) / a;
}
t1 += (d - gone) / lo;
//System.out.println(t1);
double v0 = Math.min(lo, w);
double togo = l - d;
double toAdd = (-v0 + Math.sqrt(v0 * v0 + 4 * togo * .5 * a)) / a;
if(toAdd * a + v0 > v)
{
double tt = (v - v0) / a;
t1 += tt;
togo -= .5 * a * tt * tt + v0 * tt;
t1 += togo / v;
}
else t1 += toAdd;
System.out.println(t1);
}
static boolean can(double v, double a, double d, double max)
{
double t1 = v / a;
double distGone = .5 * a * t1 * t1;
if(v > max)
{
t1 = (v - max) / a;
distGone += -.5 * a * t1 * t1 + v * t1;
}
return distGone <= d;
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class A {
static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st = new StringTokenizer("");
static String readString() throws Exception {
while(!st.hasMoreTokens())
st = new StringTokenizer(stdin.readLine());
return st.nextToken();
}
static int readInt() throws Exception {
return Integer.parseInt(readString());
}
static long readLong() throws Exception {
return Long.parseLong(readString());
}
public static void main(String[] args) throws Exception{
long a = readLong();
long b = readLong();
System.out.println(rec(a,b));
}
private static long rec(long a, long b) {
if(a == 1){
return b;
}
if(a >= b){
return a/b + rec(a%b, b);
}
return rec(b, a);
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.util.*;
import java.io.*;
// Solution
public class Main
{
public static void main (String[] argv)
{
new Main();
}
boolean test = false;
int n;
long mod = 1000000007;
public Main() {
FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
//FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in")));
long x = in.nextLong();
long k = in.nextLong();
if (x == 0) {
System.out.println(0);
return;
}
if (k == 0) {
x %= mod;
System.out.println((2*x%mod));
return;
}
x %= mod;
long f = pow(2, k);
long ans = ((2 * f * x % mod - f + 1) % mod + mod) % mod;
System.out.println(ans);
}
private long pow(long x, long y) {
long ans = 1;
while (y > 0) {
if (y % 2 == 1)
ans = ans * x % mod;
x = x * x % mod;
y /= 2;
}
return ans;
}
private long gcd(long x, long y) {
if (y == 0) return x;
return gcd(y, x % y);
}
private int max(int a, int b) {
return a > b ? a : b;
}
private int min(int a, int b) {
return a > b ? b : a;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader(BufferedReader in)
{
br = in;
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
String line = br.readLine();
if (line == null || line.length() == 0) return "";
st = new StringTokenizer(line);
}
catch (IOException e)
{
return "";
//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)
{
return "";
//e.printStackTrace();
}
return str;
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.Random;
import java.util.StringTokenizer;
public final class C {
static class Node {
int val;
String path;
Node node;
Node(String p, int t) {
path = p;
val = t;
}
}
public static void main(String[] args) {
final FastScanner fs = new FastScanner();
final int t = fs.nextInt();
final StringBuilder sb = new StringBuilder();
for (int test = 0; test < t; test++) {
final int n = fs.nextInt();
final Deque<Node> dq = new ArrayDeque<>();
dq.offerLast(new Node("", 0));
for (int i = 0; i < n; i++) {
final int next = fs.nextInt();
if (dq.getFirst().val + 1 != next) {
if (next == 1) {
final Node peek = dq.getFirst();
final String p = peek.path.isEmpty() ? String.valueOf(peek.val)
: (peek.path + '.' + peek.val);
dq.addFirst(new Node(p, 1));
} else {
while (dq.getFirst().val + 1 != next) {
dq.removeFirst();
}
dq.getFirst().val++;
}
} else {
dq.getFirst().val++;
}
add(sb, dq.getFirst(), dq.getFirst().val);
}
}
System.out.println(sb);
}
private static void add(StringBuilder sb, Node node, int val) {
final String p = node.path.isEmpty() ? String.valueOf(val)
: (node.path + '.' + val);
sb.append(p);
sb.append('\n');
}
static final class Utils {
private static class Shuffler {
private static void shuffle(int[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
private static void shuffle(long[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
private static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
private static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
}
public static void shuffleSort(int[] arr) {
Shuffler.shuffle(arr);
Arrays.sort(arr);
}
public static void shuffleSort(long[] arr) {
Shuffler.shuffle(arr);
Arrays.sort(arr);
}
private Utils() {}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
private String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] nextIntArray(int n) {
final int[] a = new int[n];
for (int i = 0; i < n; i++) { a[i] = nextInt(); }
return a;
}
long[] nextLongArray(int n) {
final long[] a = new long[n];
for (int i = 0; i < n; i++) { a[i] = nextLong(); }
return a;
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class P111C{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-9;
int h, w;
void run(){
h=sc.nextInt();
w=sc.nextInt();
solve();
}
void shuffle(int[] is){
Random rand=new Random();
for(int i=is.length-1; i>=1; i--){
int j=rand.nextInt(i+1);
int t=is[i];
is[i]=is[j];
is[j]=t;
}
}
void solve(){
n=w*h;
g=new long[n];
int[] dx={0, 0, -1, 1};
int[] dy={-1, 1, 0, 0};
for(int y=0; y<h; y++){
for(int x=0; x<w; x++){
for(int k=0; k<4; k++){
int x2=x+dx[k];
int y2=y+dy[k];
if(x2>=0&&x2<w&&y2>=0&&y2<h){
g[y*w+x]|=1L<<(y2*w+x2);
}
}
}
}
candidate=new int[n];
xs=new Xorshift();
mds=(1L<<n)-1;
mds(0, 0, 0);
println((n-Long.bitCount(mds))+"");
}
int n;
long[] g;
long mds;
int[] candidate;
Xorshift xs;
void mds(long choosed, long removed, long covered){
if(Long.bitCount(choosed)>=Long.bitCount(mds))
return;
if(covered==((1L<<n)-1)){
if(Long.bitCount(choosed)<Long.bitCount(mds))
mds=choosed;
return;
}
{
long s=covered;
for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){
int i=Long.numberOfTrailingZeros(remained);
s|=(1L<<i)|g[i];
}
if(s!=((1L<<n)-1)){
return;
}
}
int index=0;
int k=-1;
for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){
int i=Long.numberOfTrailingZeros(remained);
if((covered>>>i&1)==1){
if(Long.bitCount(g[i]&~covered)==0){
mds(choosed, removed|(1L<<i), covered);
return;
}else if(Long.bitCount(g[i]&~covered)==1
&&(g[i]&~covered&~removed)!=0){
mds(choosed, removed|(1L<<i), covered);
return;
}
}else{
if(Long.bitCount(g[i]&~removed)==0){
mds(choosed|(1L<<i), removed|(1L<<i), covered|(1L<<i)|g[i]);
return;
}else if(Long.bitCount(g[i]&~removed)==1
&&((g[i]&~removed)|(g[i]&~covered))==(g[i]&~removed)){
int j=Long.numberOfTrailingZeros(g[i]&~removed);
mds(choosed|(1L<<j), removed|(1L<<i)|(1L<<j), covered
|(1L<<j)|g[j]);
return;
}
}
// if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered))
// k=i;
if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)){
index=0;
candidate[index++]=i;
k=i;
}else if(Long.bitCount(g[i]&~covered)==Long.bitCount(g[k]&~covered)){
candidate[index++]=i;
}
}
if(k==-1)
return;
// k=candidate[xs.nextInt(index)];
mds(choosed|(1L<<k), removed|(1L<<k), covered|(1L<<k)|g[k]);
mds(choosed, removed|(1L<<k), covered);
}
class Xorshift{
int x, y, z, w;
public Xorshift(){
x=123456789;
y=362436069;
z=521288629;
w=88675123;
}
public Xorshift(int seed){
x=_(seed, 0);
y=_(x, 1);
z=_(y, 2);
w=_(z, 3);
}
int _(int s, int i){
return 1812433253*(s^(s>>>30))+i+1;
}
// 32bit signed
public int nextInt(){
int t=x^(x<<11);
x=y;
y=z;
z=w;
return w=w^(w>>>19)^t^(t>>>8);
}
// error = O(n*2^-32)
public int nextInt(int n){
return (int)(n*nextDouble());
}
// [0, 1) (53bit)
public double nextDouble(){
int a=nextInt()>>>5, b=nextInt()>>>6;
return (a*67108864.0+b)*(1.0/(1L<<53));
}
}
void println(String s){
System.out.println(s);
}
void print(String s){
System.out.print(s);
}
void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args){
Locale.setDefault(Locale.US);
new P111C().run();
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class A
{
String line;
StringTokenizer inputParser;
BufferedReader is;
FileInputStream fstream;
DataInputStream in;
String FInput="";
void openInput(String file)
{
if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
else
{
try{
fstream = new FileInputStream(file);
in = new DataInputStream(fstream);
is = new BufferedReader(new InputStreamReader(in));
}catch(Exception e)
{
System.err.println(e);
}
}
}
void readNextLine()
{
try {
line = is.readLine();
inputParser = new StringTokenizer(line, " ");
//System.err.println("Input: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
catch (NullPointerException e)
{
line=null;
}
}
int NextInt()
{
String n = inputParser.nextToken();
int val = Integer.parseInt(n);
//System.out.println("I read this number: " + val);
return val;
}
long NextLong()
{
String n = inputParser.nextToken();
long val = Long.parseLong(n);
//System.out.println("I read this number: " + val);
return val;
}
String NextString()
{
String n = inputParser.nextToken();
return n;
}
void closeInput()
{
try {
is.close();
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
public static void main(String [] argv)
{
//String filePath="input.txt";
//String filePath="D:\\_d\\learn\\coursera\\algorithms and design II\\data\\knapsack2.txt";
String filePath=null;
if(argv.length>0)filePath=argv[0];
new A(filePath);
}
public void readFInput()
{
for(;;)
{
try
{
readNextLine();
FInput+=line+" ";
}
catch(Exception e)
{
break;
}
}
inputParser = new StringTokenizer(FInput, " ");
}
public A(String inputFile)
{
openInput(inputFile);
readNextLine();
int N=NextInt(), M=NextInt(), K=NextInt();
int [] v = new int[N];
readNextLine();
for(int i=0; i<N; i++)
{
v[i]=NextInt();
}
Arrays.sort(v);
M-=(K-1);
int id=N-1;
int ret=0;
while(M>1&&id>=0)
{
M++;
M-=v[id--];
ret++;
}
if(id<0&&M>1)ret=-1;
System.out.println(ret);
closeInput();
}
public static void out(Object s)
{
try
{
FileWriter fstream = new FileWriter("output.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(s.toString());
out.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
BufferedReader in;
StringTokenizer str = null;
PrintWriter out;
private String next() throws Exception{
if (str == null || !str.hasMoreElements())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
private int nextInt() throws Exception{
return Integer.parseInt(next());
}
private long nextLong() throws Exception{
return Long.parseLong(next());
}
private double nextDouble() throws Exception{
return Double.parseDouble(next());
}
public void run() throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
long n = nextLong();
if (n == 1) {
System.out.println(0);
return;
}
long k = nextLong();
long t = 1-(k-1) + k*(k+1)/2-1;
if (t < n){
System.out.println(-1);
return;
}
long l = 0;
long r = k;
while(r - l > 1) {
long m = (r + l)/2;
long s = 1 - m + k*(k+1)/2 - (k-m)*(k-m+1)/2;
//System.out.println(m + " " + s + " " + n);
if (s >= n){
r = m;
}else{
l = m;
}
}
System.out.println(r);
out.close();
}
public static void main(String[] args) throws Exception{
new Main().run();
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args){
long MOD = 1000000007;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[][]dp = new long[n][5010];
char[] program = new char[n];
for(int i = 0; i < n; i++){
program[i] = sc.next().charAt(0);
}
dp[0][0] = 1;
long[] acc = new long[5010];
acc[0] = 1;
for(int i = 1 ; i < n; i++){
for(int j = 0; j< 5010; j++){
if(program[i-1] == 'f'){
if(j - 1 >= 0){
dp[i][j] = dp[i-1][j-1];
}
}else{
dp[i][j] = acc[j];
}
}
acc[5009] = dp[i][5009];
for(int j = 5008; j >= 0; j--){
acc[j] = (acc[j + 1] + dp[i][j]) % MOD;
}
}
System.out.println(acc[0]);
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.