src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CFA {
private void work() throws IOException {
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(
System.in)));
while (sc.hasNextInt()) {
int n = sc.nextInt();
int a = n;
int b = n / 10;
int c;
if (n < 0) {
n = -n;
c = -((n / 100) * 10 + n % 10);
} else {
c = (n / 100) * 10 + n % 10;
}
System.out.println(Math.max(a, Math.max(b, c)));
}
System.out.close();
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) throws IOException {
new CFA().work();
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class CodehorsesTshirts {
/************************ SOLUTION STARTS HERE ************************/
private static void solve() {
int n = nextInt();
HashMap<String, Integer> a = new HashMap<>();
HashMap<String, Integer> b = new HashMap<>();
for(int i = 0; i < n; i++)
a.merge(nextLine(), 1, Integer::sum);
for(int i = 0; i < n; i++)
b.merge(nextLine(), 1, Integer::sum);
b.forEach((k , v) -> {
if(a.containsKey(k))
a.put(k, a.get(k) - Math.min(v , a.get(k)));
});
int cost = a.values().stream().reduce(0, Integer::sum);
println(cost);
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE **********************/
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
st = null;
solve();
reader.close();
writer.close();
}
static BufferedReader reader;
static PrintWriter writer;
static StringTokenizer st;
static String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
static String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
static int nextInt() {return Integer.parseInt(next());}
static long nextLong() {return Long.parseLong(next());}
static double nextDouble(){return Double.parseDouble(next());}
static char nextChar() {return next().charAt(0);}
static int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;}
static long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;}
static int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;}
static long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;}
static void print(Object o) { writer.print(o); }
static void println(Object o){ writer.println(o);}
/************************ TEMPLATE ENDS HERE ************************/
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
int[] arr = new int[size];
int i = 0;
while( size != 0 )
{
arr[i] = keyboard.nextInt();
size--;
i++;
}
//System.out.print("size " + arr.length );
Arrays.sort(arr);
int index = 0;
boolean val = false;
int ans = 0;
for ( i = 0; i< arr.length-1 ; i++ )
{
//System.out.print(" arr[i] " + arr[i] + " arr[i+1] " + arr[i+1] + "\n" );
if( arr[i] != arr[i+1] )
{
val = true;
//System.out.print("Changed val to true");
index = i+1;
System.out.println(arr[index]);
return;
}
}
if (size == 1 || ( val == false))
{
System.out.println("NO");
}
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.util.*;
public class A{
public static int mod = 1000000007;
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
char s[] = new char[n];
for(int i = 0; i < n; i++)
s[i] = sc.next().charAt(0);
int dp[][] = new int[5001][5001];
int sum[][] = new int[5001][5001];
dp[0][0] = 1;
sum[0][0] = 1;
for(int i = 1; i < n; i++){
for(int j = n - 1; j >= 0; j--){
if(s[i-1] == 'f' && j > 0){
dp[i][j] = dp[i-1][j-1] % mod;
}else if(s[i-1] == 's'){
dp[i][j] = sum[i-1][j] % mod;
}
sum[i][j] = (sum[i][j+1] + dp[i][j]) % mod;
}
}
System.out.println(sum[n-1][0]);
}
}
|
quadratic
|
909_C. Python Indentation
|
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.io.StreamTokenizer;
import java.util.Arrays;
public class B {
// -- DEBUG switch --
static final boolean DBG = false;
static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static int[] e = new int[100001];
public static void main(String[] args) throws IOException {
int n = i(), k = i(), cnt = 0;
int[] a = new int[n+1];
for (int i=1; i<=n; i++){
a[i] = i();
if (e[a[i]] == 0)
cnt++;
e[a[i]]++;
}
if (k > cnt){
pw.println("-1 -1");
pw.close();
return;
}
if (cnt == n){
pw.print("1 " + k);
pw.close();
return;
}
if (k == 1){
pw.println("1 1");
pw.close();
return;
}
Arrays.fill(e, 0);
int i = 1, j = 0, unik = 0, start = 0, end = 0, len = n, m = 0;
if (e[a[i]] == 0){
unik++;
}
e[a[i]]++;
while (i+1<=n && a[i+1] == a[i]){
i = i+1;
}
j = i+1;
while (j <= n){
if (e[a[j]] == 0){
unik++;
if (unik == k){
while (e[a[i]] > 1){
e[a[i]]--;
i++;
while (i+1<=n && a[i+1] == a[i]){
i = i+1;
}
}
m = j - i + 1;
if (m < len){
start = i; end = j; len = m;
if (m == k)
break;
}
while (i <=n && unik == k){
e[a[i]]--;
if (e[a[i]] == 0)
unik--;
i++;
while (i+1<=n && a[i+1] == a[i]){
i = i+1;
}
}
}
}
e[a[j]]++;
while (j+1<=n && a[j+1] == a[j]){
j++;
}
j++;
}
pw.println(start + " " + end);
pw.close();
}
static int i() throws IOException{
st.nextToken();
return (int)st.nval;
}
static long l() throws IOException {
st.nextToken();
return (long)st.nval;
}
static double d() throws IOException {
st.nextToken();
return st.nval;
}
static String s() throws IOException{
st.nextToken();
return st.sval;
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
// package codeforce.Training1900;
import java.io.PrintWriter;
import java.util.*;
//https://codeforces.com/problemset/problem/1141/F2
public class SameSumBlocks {
// MUST SEE BEFORE SUBMISSION
// check whether int part would overflow or not, especially when it is a * b!!!!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
// int t = sc.nextInt();
int t = 1;
for (int i = 0; i < t; i++) {
solve(sc, pw);
}
pw.close();
}
static void solve(Scanner in, PrintWriter out){
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
Map<Long, List<int[]>> mp = new HashMap<>();
long[] pre = new long[n + 1];
for (int i = 1; i <= n; i++) {
pre[i] = pre[i - 1] + arr[i - 1];
}
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
long sz = pre[j + 1] - pre[i];
if (!mp.containsKey(sz)) mp.put(sz, new ArrayList<>());
mp.get(sz).add(new int[]{i, j});
}
}
int max = 0;
List<int[]> ans = new ArrayList<>();
for(List<int[]> ls : mp.values()){
Collections.sort(ls, (a, b) -> {
if (a[1] == b[1]) return b[0] - a[0];
return a[1] - b[1];
});
List<int[]> tt = new ArrayList<>();
int cnt = 0;
int pr = -1;
for (int i = 0; i < ls.size(); i++) {
int[] get = ls.get(i);
if (get[0] <= pr) continue;
cnt++;
tt.add(get);
pr = get[1];
}
if (max < cnt){
ans = tt;
max = cnt;
}
}
out.println(max);
for(int[] v : ans){
out.println((v[0] + 1) + " " + (v[1] + 1));
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.*;
public class codeee {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if(n==1){System.out.println(1); return;}
int []mas=new int[n];
int sum=0;
for (int i = 0; i < n; i++) {
mas[i]=sc.nextInt();
sum+=mas[i];
}
Arrays.sort(mas);
int sum1=0;
int ans=0;
for(int i=0;i<n;i++){
sum1+=mas[n-i-1];
if(sum1>(sum-sum1)){
ans=i;
break;
}
}
System.out.println(ans+1);
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
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;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
ArrayList<Integer>[] g;
int n, m;
boolean[][] have;
int[] x;
int[] y;
boolean[] used;
int stop;
public void solve(int testNumber, FastScanner in, PrintWriter out) {
n = in.nextInt();
g = new ArrayList[n];
for (int i = 0; i < n; i++)
g[i] = new ArrayList<>();
have = new boolean[n][n];
m = in.nextInt();
for (int i = 0; i < m; i++) {
int a = in.nextInt();
int b = in.nextInt();
--a;
--b;
g[a].add(b);
have[a][b] = true;
}
int res = Integer.MAX_VALUE;
for (int center = 0; center < n; center++)
res = Math.min(res, solve(center));
out.print(res);
}
int solve(int v) {
stop = v;
int withV = 0;
int add = 0;
for (int i = 0; i < n; i++)
if (i != v)
if (have[v][i])
withV++;
else
add++;
for (int i = 0; i < n; i++)
if (i != v)
if (have[i][v])
withV++;
else
add++;
if (have[v][v])
withV++;
else
add++;
x = new int[n];
y = new int[n];
used = new boolean[n];
Arrays.fill(x, -1);
Arrays.fill(y, -1);
int matched = 0;
for (int i = 0; i < n; i++)
if (i != v && x[i] == -1) {
Arrays.fill(used, false);
if (dfs(i))
matched++;
}
add += n - 1 - matched;
add += m - withV - matched;
return add;
}
boolean dfs(int v) {
if (used[v])
return false;
used[v] = true;
for (int to : g[v])
if (to != stop && y[to] == -1) {
x[v] = to;
y[to] = v;
return true;
}
for (int to : g[v])
if (to != stop && dfs(y[to])) {
x[v] = to;
y[to] = v;
return true;
}
return false;
}
}
class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
}
|
cubic
|
387_D. George and Interesting Graph
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class test1
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[]=new int[n];
int b[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=in.nextInt();
b[i]=a[i];
}
Arrays.sort(b);
int count=0;
for(int i=0;i<n;i++)
if(a[i]!=b[i])
count++;
if(count<=2)
System.out.println("YES");
else
System.out.println("NO");
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.util.*;
public class A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long A = in.nextLong();
long B = in.nextLong();
System.out.println(f(A,B));
}
static long f(long A, long B) {
if(A==0) return 0;
if(A < B) return f(B,A);
else {
long k = A/B;
return k+f(A-B*k, B);
}
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
public class G {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni(), K = ni(), C = ni(), D = ni();
int[] a = na(K);
int[] from = new int[m];
int[] to = new int[m];
for (int i = 0; i < m; i++) {
from[i] = ni() - 1;
to[i] = ni() - 1;
}
int[][] g = packU(n, from, to);
List<Edge> es = new ArrayList<>();
int time = 100;
for(int i = 0;i < n;i++){
for(int j = 0;j < time-1;j++){
es.add(new Edge(i*time+j, i*time+j+1, 99, C));
}
}
for(int i = 0;i < n;i++){
for(int e : g[i]){
for(int j = 0;j < time-1;j++){
for(int k = 0;k < n;k++){
es.add(new Edge(i*time+j, e*time+j+1, 1, C+D*(2*k+1)));
}
}
}
}
int src = time*n, sink = src+1;
for(int i = 0;i < K;i++){
es.add(new Edge(src, (a[i]-1)*time+0, 1, 0));
}
for(int i = 0;i < time;i++){
es.add(new Edge(0*time+i, sink, 99, 0));
}
out.println(solveMinCostFlowWithSPFA(compileWD(sink+1, es), src, sink, 99));
}
public static class Edge
{
public int from, to;
public int capacity;
public int cost;
public int flow;
public Edge complement;
// public int iniflow;
public Edge(int from, int to, int capacity, int cost) {
this.from = from;
this.to = to;
this.capacity = capacity;
this.cost = cost;
}
}
public static Edge[][] compileWD(int n, List<Edge> edges)
{
Edge[][] g = new Edge[n][];
// cloning
for(int i = edges.size()-1;i >= 0;i--){
Edge origin = edges.get(i);
Edge clone = new Edge(origin.to, origin.from, origin.capacity, -origin.cost);
clone.flow = origin.capacity;
clone.complement = origin;
origin.complement = clone;
edges.add(clone);
}
int[] p = new int[n];
for(Edge e : edges)p[e.from]++;
for(int i = 0;i < n;i++)g[i] = new Edge[p[i]];
for(Edge e : edges)g[e.from][--p[e.from]] = e;
return g;
}
// NOT VERIFIED
public static Edge[][] compileWU(int n, List<Edge> edges)
{
Edge[][] g = new Edge[n][];
// cloning
for(int i = edges.size()-1;i >= 0;i--){
Edge origin = edges.get(i);
Edge back = new Edge(origin.to, origin.from, origin.capacity, origin.cost);
edges.add(back);
}
for(int i = edges.size()-1;i >= 0;i--){
Edge origin = edges.get(i);
Edge clone = new Edge(origin.to, origin.from, origin.capacity, -origin.cost);
clone.flow = origin.capacity;
clone.complement = origin;
origin.complement = clone;
edges.add(clone);
}
int[] p = new int[n];
for(Edge e : edges)p[e.from]++;
for(int i = 0;i < n;i++)g[i] = new Edge[p[i]];
for(Edge e : edges)g[e.from][--p[e.from]] = e;
return g;
}
public static class DQ {
public int[] q;
public int n;
protected int pt, ph;
public DQ(int n){ this.n = Integer.highestOneBit(n)<<1; q = new int[this.n]; pt = ph = 0; }
public void addLast(int x){ q[ph] = x; ph = ph+1&n-1; }
public void addFirst(int x){ pt = pt+n-1&n-1; q[pt] = x; }
public int pollFirst(){ int ret = q[pt]; pt = pt+1&n-1; return ret; }
public int pollLast(){ ph = ph+n-1&n-1; int ret = q[ph]; return ret; }
public int getFirst(){ return q[pt]; }
public int getFirst(int k){ return q[pt+k&n-1]; }
public int getLast(){ return q[ph+n-1&n-1]; }
public int getLast(int k){ return q[ph+n-k-1&n-1]; }
public void clear(){ pt = ph = 0; }
public int size(){ return ph-pt+n&n-1; }
public boolean isEmpty(){ return ph==pt; }
}
public static long solveMinCostFlowWithSPFA(Edge[][] g, int source, int sink, long all)
{
int n = g.length;
long mincost = 0;
final int[] d = new int[n];
DQ q = new DQ(n);
boolean[] inq = new boolean[n];
while(all > 0){
// shortest path src->sink
Edge[] inedge = new Edge[n];
Arrays.fill(d, Integer.MAX_VALUE / 2);
d[source] = 0;
q.addLast(source);
while(!q.isEmpty()){
int cur = q.pollFirst();
inq[cur] = false;
for(Edge ne : g[cur]){
if(ne.capacity - ne.flow > 0){
int nd = d[cur] + ne.cost;
if(d[ne.to] > nd){
inedge[ne.to] = ne;
d[ne.to] = nd;
if(!inq[ne.to]){
q.addLast(ne.to);
inq[ne.to] = true;
}
}
}
}
}
if(inedge[sink] == null)break;
long minflow = all;
long sumcost = 0;
for(Edge e = inedge[sink];e != null;e = inedge[e.from]){
if(e.capacity - e.flow < minflow)minflow = e.capacity - e.flow;
sumcost += e.cost;
}
mincost += minflow * sumcost;
for(Edge e = inedge[sink];e != null;e = inedge[e.from]){
e.flow += minflow;
e.complement.flow -= minflow;
}
all -= minflow;
}
return mincost;
}
static int[][] packU(int n, int[] from, int[] to) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int f : from)
p[f]++;
for (int t : to)
p[t]++;
for (int i = 0; i < n; i++)
g[i] = new int[p[i]];
for (int i = 0; i < from.length; i++) {
g[from[i]][--p[from[i]]] = to[i];
g[to[i]][--p[to[i]]] = from[i];
}
return g;
}
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 G().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)); }
}
|
cubic
|
1187_G. Gang Up
|
CODEFORCES
|
import java.io.*;
import java.util.HashSet;
import java.util.StringTokenizer;
public class GB_A {
FastScanner in;
PrintWriter out;
public static void main(String[] arg) {
new GB_A().run();
}
public void solve() throws IOException {
int n = in.nextInt();
int r = in.nextInt();
int[] a = new int[n];
double[] ans = new double[n];
a[0] = in.nextInt();
ans[0] = r;
for (int i = 1; i < n; i++) {
a[i] = in.nextInt();
double max = r;
for (int j = i - 1; j >= 0; j--) {
if (Math.abs(a[i] - a[j]) <= 2 * r) {
double d = Math.sqrt(4 * r * r - (a[i]- a[j]) * (a[i] - a[j])) + ans[j];
max = Math.max(max, d);
}
}
ans[i] = max;
}
for (int i = 0; i < n; i++) {
out.println(ans[i]);
}
}
public void run() {
try {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(BufferedReader bufferedReader) {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class A implements Runnable {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
@Override
public void run() {
try {
long startTime = System.currentTimeMillis();
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");
}
tok = new StringTokenizer("");
Locale.setDefault(Locale.US);
solve();
in.close();
out.close();
long endTime = System.currentTimeMillis();
long totalMemory = Runtime.getRuntime().totalMemory();
long freeMemory = Runtime.getRuntime().freeMemory();
System.err.println("Time = " + (endTime - startTime) + " ms");
System.err.println("Memory = " + ((totalMemory - freeMemory) / 1024) + " KB");
} catch (Throwable e) {
e.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());
}
void debug(Object... o) {
if (!ONLINE_JUDGE) {
System.err.println(Arrays.deepToString(o));
}
}
public static void main(String[] args) {
new Thread(null, new A(), "", 256 * 1024 * 1024).start();
}
static class Utils {
private Utils() {}
public static void mergeSort(int[] a) {
mergeSort(a, 0, a.length - 1);
}
private static void mergeSort(int[] a, int leftIndex, int rightIndex) {
final int MAGIC_VALUE = 50;
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergeSort(a, leftIndex, middleIndex);
mergeSort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
int[] leftArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
}
//------------------------------------------------------------------------------
void solve() throws IOException {
int n = readInt();
int[] a = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
a[i] = readInt();
sum += a[i];
}
Utils.mergeSort(a);
int s = 0, c = 0;
for (int i = n-1; i >= 0; i--) {
s += a[i];
c++;
if (2 * s > sum) {
break;
}
}
out.println(c);
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
PrintWriter out = new PrintWriter(System.out);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer("");
String next() throws IOException {
if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); }
return tok.nextToken();
}
int ni() throws IOException { return Integer.parseInt(next()); }
long nl() throws IOException { return Long.parseLong(next()); }
void solve() throws IOException {
int n=ni();
int[]A=new int[n];
for (int x=0;x<n;x++) A[x]=ni();
Arrays.sort(A);
ArrayList<Integer>B=new ArrayList();
B.add(A[0]);
int ans=1;
Outer:
for (int x=1;x<n;x++) {
for (int y=0;y<B.size();y++) {
if (A[x]%B.get(y)==0) continue Outer;
}
ans++;
B.add(A[x]);
}
System.out.println(ans);
}
public static void main(String[] args) throws IOException {
new Main().solve();
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Subtractions
{
/************************ SOLUTION STARTS HERE ***********************/
static long modifiedEuclidGCD(int a , int b) {
return b == 0 ? 0 : (a / b) + modifiedEuclidGCD(b, a % b);
}
private static void solve(FastScanner s1, PrintWriter out){
int T = s1.nextInt();
while(T-->0)
out.println(modifiedEuclidGCD(s1.nextInt(), s1.nextInt()));
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE *********************/
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;}
long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;}
int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;}
long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/************************ TEMPLATE ENDS HERE ************************/
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
private static void solve(InputReader in, OutputWriter out) {
int n = in.nextInt();
List<List<Integer>> g = new ArrayList<>(n + 1);
for (int i = 0; i < n + 1; i++) {
g.add(new LinkedList<>());
}
int degree1 = 0, degree2 = 0, root = 0;
for (int i = 0; i < n - 1; i++) {
int a = in.nextInt();
int b = in.nextInt();
g.get(a).add(b);
g.get(b).add(a);
if (g.get(a).size() > degree1) {
if (a == root) {
degree1 = g.get(a).size();
} else {
degree2 = degree1;
degree1 = g.get(a).size();
root = a;
}
} else if (g.get(a).size() > degree2) {
degree2 = g.get(a).size();
}
if (g.get(b).size() > degree1) {
if (b == root) {
degree1 = g.get(b).size();
} else {
degree2 = degree1;
degree1 = g.get(b).size();
root = b;
}
} else if (g.get(b).size() > degree2) {
degree2 = g.get(b).size();
}
}
if (degree2 > 2) {
out.print("No");
} else {
out.println("Yes");
List<Integer> leaves = new LinkedList<>();
for (int i = 1; i <= n; i++) {
if (i != root) {
if (g.get(i).size() == 1) {
leaves.add(i);
}
}
}
out.println(leaves.size());
for (int i : leaves) {
out.println(root + " " + i);
}
}
}
private static void shuffleArray(int[] array) {
int index;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
index = random.nextInt(i + 1);
if (index != i) {
array[index] ^= array[i];
array[i] ^= array[index];
array[index] ^= array[i];
}
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
solve(in, out);
in.close();
out.close();
}
private static class InputReader {
private BufferedReader br;
private StringTokenizer st;
InputReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
st = null;
}
String nextLine() {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String line = nextLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
byte nextByte() {
return Byte.parseByte(next());
}
short nextShort() {
return Short.parseShort(next());
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class OutputWriter {
BufferedWriter bw;
OutputWriter(OutputStream os) {
bw = new BufferedWriter(new OutputStreamWriter(os));
}
void print(int i) {
print(Integer.toString(i));
}
void println(int i) {
println(Integer.toString(i));
}
void print(long l) {
print(Long.toString(l));
}
void println(long l) {
println(Long.toString(l));
}
void print(double d) {
print(Double.toString(d));
}
void println(double d) {
println(Double.toString(d));
}
void print(boolean b) {
print(Boolean.toString(b));
}
void println(boolean b) {
println(Boolean.toString(b));
}
void print(char c) {
try {
bw.write(c);
} catch (IOException e) {
e.printStackTrace();
}
}
void println(char c) {
println(Character.toString(c));
}
void print(String s) {
try {
bw.write(s);
} catch (IOException e) {
e.printStackTrace();
}
}
void println(String s) {
print(s);
print('\n');
}
void close() {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
linear
|
981_C. Useful Decomposition
|
CODEFORCES
|
import java.util.*;
public class Counterexample483A
{
public static void main(String[] args)
{
// Set up scanner
Scanner sc = new Scanner(System.in);
// System.out.println("Enter l");
long l = sc.nextLong();
// System.out.println("Enter r");
long r = sc.nextLong();
if (l==r || l+1 == r)
{
System.out.println(-1);
return;
}
if (l+2 == r && l%2 == 1)
{
System.out.println(-1);
return;
}
if (l%2 == 0)
{
System.out.println(l + " " + (l+1) + " " + (l+2));
return;
}
System.out.println((l+1) + " " + (l+2) + " " + (l+3));
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int MOD = in.nextInt();
int[][] C = new int[n + 1][n + 1];
C[0][0] = 1;
for (int i = 1; i < C.length; i++) {
C[i][0] = 1;
for (int j = 1; j < C.length; j++) {
C[i][j] = C[i - 1][j] + C[i - 1][j - 1];
if (C[i][j] >= MOD) {
C[i][j] -= MOD;
}
}
}
int[] p2 = new int[n + 1];
p2[0] = 1;
for (int i = 1; i < p2.length; i++) {
p2[i] = 2 * p2[i - 1] % MOD;
}
int[][] d = new int[n + 1][n + 1];
d[0][0] = 1;
// Total.
for (int i = 1; i <= n; i++) {
// Switched on manually.
for (int j = 1; j <= i; j++) {
// Switched on manually in the first block.
for (int t = 1; t <= j; t++) {
if (t == i - 1) {
continue;
}
d[i][j] = (int) ((d[i][j] + (long) C[j][t] * p2[t - 1] % MOD * d[i - t - (i == t ? 0 : 1)][j - t]) % MOD);
}
}
}
int ans = 0;
for (int k = 1; k <= n; k++) {
ans += d[n][k];
if (ans >= MOD) {
ans -= MOD;
}
}
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());
}
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class B {
public static PrintWriter out;
public static BufferedReader bf;
public static int n;
public static int[] a;
public static void main(String[] args) throws Exception {
bf = new BufferedReader(new InputStreamReader(System.in));
// Scanner scan = new Scanner(System.in);
out = new PrintWriter(new OutputStreamWriter(System.out));
n = Integer.parseInt(bf.readLine());
a = new int[n];
Arrays.fill(a, Integer.MAX_VALUE);
if((n/2) % 2 != 0) {
out.println("! " + (-1));
out.flush();
out.close(); System.exit(0);
}
ask(0);
ask(opp(0));
int low = 0;
int high = opp(0);
while(true) {
int test = (low + high)/2;
ask(test);
ask(opp(test));
int l_1 = a[low];
int l_2 = a[test];
int r_1 = a[opp(low)];
int r_2 = a[opp(test)];
if(1L*(l_1 - r_1)*(l_2 - r_2) < 0L) {
high = test;
}
else low = test;
}
// StringTokenizer st = new StringTokenizer(bf.readLine());
// int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
// int n = Integer.parseInt(st.nextToken());
// int n = scan.nextInt();
//out.close(); System.exit(0);
}
public static int ask(int i) throws Exception { // 0 thru n-1;
out.println("? " + (i+1));
out.flush();
int k = Integer.parseInt(bf.readLine());
a[i] = k;
if(a[i] == a[opp(i)]) {
out.println("! " + (i+1));
out.flush();
out.close(); System.exit(0);
}
return k;
}
public static int opp(int k) {
return ((k + n/2) % n);
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.util.Scanner;
public class A {
/**
* @param args
*/
public static void main(String[] args) {
Account acnt = new Account();
acnt.solve();
acnt.print();
}
}
class Account {
Account() {
Scanner scr = new Scanner(System.in);
n = scr.nextInt();
}
void solve() {
if (n > 0) {
ans = n;
}
else {
int nn = -n;
int ans1 = nn/10;
int ans2 = nn % 10 + (nn/100)*10;
if (ans1 < ans2){
ans = -ans1;
}
else {
ans = -ans2;
}
}
}
void print(){
System.out.println(ans);
}
int ans;
int n;
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import javafx.util.Pair;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main implements Runnable
{
boolean multiple = false;
long MOD;
@SuppressWarnings({"Duplicates", "ConstantConditions"})
void solve() throws Exception
{
int k = sc.nextInt();
long tar = 0;
long[][] arr = new long[k][];
long[] sum = new long[k];
HashMap<Long, Pair<Integer, Integer>> map = new HashMap<>();
for (int i = 0; i < k; i++)
{
int ni = sc.nextInt();
arr[i] = new long[ni];
for (int j = 0; j < ni; j++)
{
sum[i] += (arr[i][j] = sc.nextInt());
map.put(arr[i][j], new Pair<>(i, j));
}
tar += sum[i];
}
if (tar % k != 0) { System.out.println("No"); return; }
tar /= k;
works = new HashMap<>();
for (int i = 0; i < k; i++)
{
outer: for (int j = 0; j < arr[i].length; j++)
{
long val = arr[i][j];
long want = tar - sum[i] + val;
if (!map.containsKey(want)) continue;
// ArrayList<pli> list = new ArrayList<>();
int key = 1 << i;
int next = map.get(want).getKey();
// int prev = i;
HashSet<Integer> seen = new HashSet<>();
seen.add(i);
while (true)
{
if (seen.contains(next))
{
if (next == i && want == arr[i][j])
works.put(key, (((long) i) << 32) + ((long) j));
break;
}
// list.add(new pli(want, prev));
val = arr[next][map.get(want).getValue()];
want = tar - sum[next] + val;
if (!map.containsKey(want)) continue outer;
key |= 1 << next;
// prev = next;
seen.add(next);
next = map.get(want).getKey();
}
}
}
// dp.put(0, new ArrayList<>());
dp = new long[1 << k];
done = new boolean[1 << k];
yes = new boolean[1 << k];
yes[0] = done[0] = true;
long ans = r((1 << k) - 1);
long[] val = new long[k];
int[] pos = new int[k];
if (!yes[(1 << k) - 1]) System.out.println("No");
else
{
// System.out.println(ans);
// System.out.println(map);
System.out.println("Yes");
while (ans >> 32 != 0)
{
long p = works.get((int)(ans >> 32));
int i = (int)(p >> 32), j = (int)(p & ((1L<<32)-1));
long VAL = arr[i][j];
long want = tar - sum[i] + VAL;
int key = 1 << i;
int next = map.get(want).getKey();
int prev = i;
while (true)
{
if (next == i)
{
val[map.get(want).getKey()] = want;
pos[map.get(want).getKey()] = prev + 1;
if (want == arr[i][j])
works.put(key, (((long)i)<<32) + ((long)j));
break;
}
val[map.get(want).getKey()] = want;
pos[map.get(want).getKey()] = prev + 1;
VAL = arr[next][map.get(want).getValue()];
want = tar - sum[next] + VAL;
key |= 1 << next;
prev = next;
next = map.get(want).getKey();
}
ans = dp[(int)(ans & ((1L << 32)- 1))];
}
for (int i = 0; i < k; i++)
System.out.println(val[i] + " " + pos[i]);
}
}
HashMap<Integer, Long> works;
long[] dp;
boolean[] done, yes;
long r(int mask)
{
if (done[mask]) return dp[mask];
done[mask] = true;
for (int s = mask; s != 0; s = (s-1) & mask)
if (works.keySet().contains(s))
{
int tempMask = mask;
for (int i = 0; i < 16; i++)
if ((s & (1 << i)) != 0)
tempMask ^= 1 << i;
r(tempMask);
if (yes[tempMask])
{
yes[mask] = true;
return dp[mask] = (((long)s) << 32) + tempMask;
}
}
return 0;
}
class pii { int f, s; pii(int k, int v) { f = k; s = v; } }
class pli { long f; int s; pli(long k, int v) { f = k; s = v; } public String toString() { return "(" + f + ", " + s + ")"; } }
StringBuilder ANS = new StringBuilder();
void p(Object s) { ANS.append(s); } void p(double s) {ANS.append(s); } void p(long s) {ANS.append(s); } void p(char s) {ANS.append(s); }
void pl(Object s) { ANS.append(s); ANS.append('\n'); } void pl(double s) { ANS.append(s); ANS.append('\n'); } void pl(long s) { ANS.append(s); ANS.append('\n'); } void pl(char s) { ANS.append(s); ANS.append('\n'); } void pl() { ANS.append(('\n')); }
/*I/O, and other boilerplate*/ @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);sc = new FastScanner(in);if (multiple) { int q = sc.nextInt();for (int i = 0; i < q; i++) solve(); } else solve(); System.out.print(ANS); } catch (Throwable uncaught) { Main.uncaught = uncaught; } finally { out.close(); }} public static void main(String[] args) throws Throwable{ Thread thread = new Thread(null, new Main(), "", (1 << 26));thread.start();thread.join();if (Main.uncaught != null) {throw Main.uncaught;} } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) {this.in = in;}public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); }return st.nextToken(); }public int nextInt() throws Exception { return Integer.parseInt(nextToken()); }public long nextLong() throws Exception { return Long.parseLong(nextToken()); }public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); }
}
|
np
|
1242_C. Sum Balance
|
CODEFORCES
|
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
Arrays.sort(a);
//boolean
int t=1,c=0;
for(int i=1;i<n;i++){
if(a[i]==a[i-1])
{
if(i-2>=0&&a[i-2]==a[i-1]-1){
System.out.println("cslnb");
return;
}
c++;
}
if(a[i]==a[i-1]&&a[i]==0){
System.out.println("cslnb");
return;
}
}
if(c>1)
{
System.out.println("cslnb");
return;
}
for(int i=0;i<n;i++){
if((a[i]-i)%2!=0)
t=t^1;
}
if(t==1)
System.out.println("cslnb");
else
System.out.println("sjfnb");
}
}
|
linear
|
1190_B. Tokitsukaze, CSL and Stone Game
|
CODEFORCES
|
import java.awt.List;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class T {
static Scanner in = new Scanner();
static PrintWriter out = new PrintWriter(System.out);
static boolean adj[][];
static int n, m, from;
static long memo[][];
static long Num_Cycle;
public static void main(String[] args) throws IOException {
n = in.nextInt();
m = in.nextInt();
adj = new boolean[n][n];
memo = new long[n][1 << n];
for (int i = 0; i < m; i++) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
adj[u][v] = adj[v][u] = true;
}
for (long arr[] : memo) {
Arrays.fill(arr, -1);
}
Num_Cycle = 0L;
for (int i = 0; i < n; i++) {
from = i;
Num_Cycle += dp(from, (1 << i));
}
out.println(Num_Cycle / 2);
out.flush();
out.close();
}
static long dp(int start, int mask) {
if (memo[start][mask] != -1) {
return (memo[start][mask]);
}
long ans = 0L;
if (adj[start][from] && Integer.bitCount(mask) >= 3) {// Cycle has
// atleast 3
// node and 3
// edges
ans++;
}
for (int i = from + 1; i < n; i++) {
if (adj[start][i] && ((mask & (1 << i)) == 0)) {
ans += dp(i, mask | (1 << i));
}
}
return memo[start][mask] = ans;
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String file) throws FileNotFoundException {
br = new BufferedReader(new FileReader(file));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
String nextLine() throws IOException {
return br.readLine();
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class EdE {
static long[] mods = {1000000007, 998244353, 1000000009};
static long mod = mods[0];
public static MyScanner sc;
public static PrintWriter out;
static long[][][] paths;
static long[] powers501;
public static void main(String[] havish) throws Exception{
// TODO Auto-generated method stub
sc = new MyScanner();
out = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
paths = new long[n+1][m+1][4]; //up down left right;
powers501 = new long[5];
powers501[0] = 1;
for(int j = 1;j<5;j++){
powers501[j] = 501L*powers501[j-1];
}
long[][][]dp = new long[n+1][m+1][k/2+2];
for(int i = 1;i<=n;i++){
for(int j = 1;j<=m-1;j++){
int val = sc.nextInt();
paths[i][j][3] = val;
paths[i][j+1][2] = val;
// paths.put(powers501[3]*i + powers501[2]*j + powers501[1]*i + powers501[0]*(j+1), val);
// paths.put(powers501[3]*i + powers501[2]*(j+1) + powers501[1]*i + powers501[0]*j, val);
}
}
for(int i = 1;i<=n-1;i++){
for(int j = 1;j<=m;j++){
int val = sc.nextInt();
// paths.put(powers501[3]*(i+1) + powers501[2]*j + powers501[1]*i + powers501[0]*j, val);
// paths.put(powers501[3]*i + powers501[2]*j + powers501[1]*(i+1) + powers501[0]*j, val);
paths[i][j][1] = val;
paths[i+1][j][0] = val;
}
}
for(int j = 1;j<=n;j++){
for(int i = 1;i<=m;i++){
Arrays.fill(dp[j][i], Integer.MAX_VALUE);
dp[j][i][0] = 0;
}
}
for(int steps = 1;steps<k/2+2;steps++){
for(int i = 1;i<=n;i++){
for(int j = 1;j<=m;j++){
if (i-1 > 0) {
dp[i][j][steps] = Math.min(dp[i-1][j][steps-1] + getVal(i, j, i-1, j), dp[i][j][steps]);
}
if (j-1 > 0) {
dp[i][j][steps] = Math.min(dp[i][j-1][steps-1] + getVal(i, j, i, j-1), dp[i][j][steps]);
}
if (i+1 <= n) {
dp[i][j][steps] = Math.min(dp[i+1][j][steps-1] + getVal(i, j, i+1, j), dp[i][j][steps]);
}
if (j+1 <= m) {
dp[i][j][steps] = Math.min(dp[i][j+1][steps-1] + getVal(i, j, i, j+1), dp[i][j][steps]);
}
}
}
}
if (k%2 == 1){
for(int j = 1;j<=n;j++){
for(int s = 1;s<=m;s++){
out.print(-1 + " ");
}
out.println();
}
}
else{
for(int j = 1;j<=n;j++){
for(int s = 1;s<=m;s++){
out.print(dp[j][s][k/2]*2L + " ");
}
out.println();
}
}
out.close();
}
public static long getVal(int x1, int y1, int x2, int y2) {
if (x2 == x1+1)
return paths[x1][y1][1];
else if (x1 == x2+1)
return paths[x1][y1][0];
else if (y2 == y1 + 1)
return paths[x1][y1][3];
else
return paths[x1][y1][2];
}
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
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
double a = (double)read.nextInt();
double v = (double)read.nextInt();
double l = (double)read.nextInt();
double d = (double)read.nextInt();
double w = (double)read.nextInt();
double t=0;
if(w>=v){
double d1=v*v/(2*a);
if(d1>l){
t+= Math.sqrt(2*l/a);
}
else{
t+= v/a + (l-d1)/v;
}
}
else{
double temp = (v-w)/a;
double d1 = v*v/(2*a);
double d2 = d - v*temp + a*temp*temp/2;
if(d1>d2){
double temp2 = Math.sqrt(2*a*d);
if(temp2<w){
w=temp2;
temp=(v-w)/a;
t+= temp2/a;
}
else{
double vx=Math.sqrt(v*v/2+a*d2);
t+= (vx/a) + ((vx-w)/a);
}
}
else{
t+= (v/a) + ((d2-d1)/v) + (temp);
}
double d3 = d + w*temp + a*temp*temp/2;
if(d3>l){
t+= (-w+Math.sqrt(w*w+2*a*(l-d)))/a;
}
else{
t+= (temp) + ((l-d3)/v);
}
}
System.out.printf("%.6f", t);
read.close();
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class Main {
private static StreamTokenizer in;
private static PrintWriter out;
private static int nextInt() throws Exception {
in.nextToken();
return (int)in.nval;
}
private static String nextString() throws Exception {
in.nextToken();
return in.sval;
}
public static void main(String[] args) throws Exception {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
int n = nextInt();
byte f = (byte)nextInt();
byte s = (byte)nextInt();
byte t = (byte)nextInt();
boolean bf = false;
boolean bs = false;
boolean bt = false;
if((f&1) == 0){bf = true;}
if((s&1) == 0){bs = true;}
if((t&1) == 0){bt = true;}
//System.out.println(bf+""+bs+""+bt);
if((!bf)&&bs&&bt){System.out.println(1);return;}
if(bf&&(!bs)&&bt){System.out.println(2);return;}
if(bf&&bs&&(!bt)){System.out.println(3);return;}
if(bf&&!bs&&!bt){System.out.println(1);return;}
if(!bf&&bs&&!bt){System.out.println(2);return;}
if(!bf&&!bs&&bt){System.out.println(3);return;}
for(int i = 4; i<=n; i++){
byte g = (byte) nextInt();
if(((g+f)&1) == 1){System.out.println(i); return;}
}
out.flush();
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import javax.print.DocFlavor;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Round584_a {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
int a[] = new int[n];
for(int i=0 ; i<n ; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(a);
boolean vis[] = new boolean[n];
int count = 0;
for(int i=0 ; i<n ; i++) {
if(!vis[i]) {
for(int j=i ; j<n ; j++) {
if(!vis[j]) {
if(a[j]%a[i] == 0) {
vis[j] = true;
}
}
}
count++;
}
}
System.out.println(count);
}
}
/*import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Round584_a {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
}
}*/
|
quadratic
|
1209_A. Paint the Numbers
|
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 (memo1[idx][remCnt][remSum] != -1)
return memo1[idx][remCnt][remSum];
int ans = dp1(idx + 1, remCnt, remSum);
if (g[idx] == 0 && t[idx] <= remSum && remCnt>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) {
int all = remCnt1 + remCnt2;
if (all == 0)
return remSum == 0 ? 1 : 0;
if (idx == n || remSum == 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 (t[idx] <= remSum) {
if (g[idx] == 1 && remCnt1 > 0)
ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]);
else if (g[idx] == 2 && remCnt2 > 0)
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.util.*;
import java.io.*;
public class p3sol{
static char[] c;
static int[][] dp;
static int mod = (int)1e9 + 7;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
c = new char[n];
for(int i = 0; i < n; i++)
c[i] = br.readLine().charAt(0);
dp = new int[n + 1][n + 1];
dp[0][0] = 1;
for(int i = 0; i < n - 1; i++){
if(c[i] == 's'){
int prev = 0;
for(int j = i; j >= 0; j--){
prev += dp[i][j];
prev %= mod;
dp[i + 1][j] += prev;
dp[i + 1][j] %= mod;
}
}
else{
for(int j = 1; j <= n; j++){
dp[i + 1][j] += dp[i][j - 1];
dp[i + 1][j] %= mod;
}
}
}
int ans = 0;
for(int i = 0; i < n; i++){
ans += dp[n - 1][i];
ans %= mod;
}
// print(dp);
System.out.println(ans);
br.close();
}
public static void print(int[][] a){
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[0].length; j++)
System.out.print(a[i][j] + " ");
System.out.println("");
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
public class BT {
static BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer str;
static String SK;
static String next() throws IOException {
while ((str == null) || (!str.hasMoreTokens())) {
SK = in.readLine();
if (SK == null)
return null;
str = new StringTokenizer(SK);
}
return str.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static void main(String[] args) throws IOException {
int n, k;
n = nextInt();
k = nextInt();
HashSet<Integer> hs = new HashSet<Integer>();
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
int[] ar = new int[n];
int ii = 0, jj = -1;
for (int i = 0; i < n; i++) {
ar[i] = nextInt();
Integer iii = hm.get(ar[i]);
if(iii!=null)
hm.put(ar[i], ++iii); else hm.put(ar[i], 1);
hs.add(ar[i]);
if (hs.size() == k) {
jj = i;
break;
}
}
if (jj == -1) {
System.out.println(-1 + " " + (-1));
System.exit(0);
}
for (int i = 0; i < ar.length; i++) {
Integer iii = hm.get(ar[i]);
if (iii != null && iii - 1 > 0) {
hm.put(ar[i], --iii);
ii++;
} else {
break;
}
}
System.out.println((ii+1) + " " + (jj+1));
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author codeKNIGHT
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n=in.nextInt(),k=in.nextInt()-1,i;
scores a[]=new scores[n];
for(i=0;i<n;i++)
a[i]=new scores(in.nextInt(),in.nextInt());
Arrays.sort(a);
int c=1;
for(i=k-1;i>=0;i--)
{
if(a[i].p==a[k].p&&a[i].t==a[k].t)
c++;
else break;
}
for(i=k+1;i<n;i++)
{
if(a[i].p==a[k].p&&a[i].t==a[k].t)
c++;
else break;
}
out.println(c);
}
class scores implements Comparable<scores>
{
int p,t;
public scores(int p,int t)
{
this.p=p;
this.t=t;
}
public int compareTo(scores a)
{
if(a.p>this.p)
return 1;
if(a.p==this.p&&a.t<this.t)
return 1;
return -1;
}
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.io.FileNotFoundException;
import java.util.Scanner;
public class P1177A {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
// Scanner in = new Scanner(new File("input.txt"));
System.out.println(solve(in.nextLong()));
}
private static String solve(long k) {
long digitCnt = 1;
long nine = 9;
while (k > nine * digitCnt) {
k -= nine * digitCnt;
nine *= 10;
digitCnt++;
}
long num = nine / 9 - 1 + (k - 1) / digitCnt + 1;
return String.valueOf(String.valueOf(num).charAt((int) ((k - 1) % digitCnt)));
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
/**
* Created by Baelish on 8/28/2018.
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class F_DSU {
public static void main(String[] args)throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = in.nextInt();
int brr[] = new int[2*n];
for (int i = 0; i < 2*n; i+= 2) {
brr[i] = in.nextInt();
brr[i+1] = in.nextInt();
}
arr = shrink(brr);
int imap[] = new int[2*n];
for (int i = 0; i < 2*n; i++) {
imap[arr[i]] = brr[i];
}
int idx = binarySearch(arr.length);
if(idx >= arr.length) pw.println(-1);
else pw.println(imap[idx]);
pw.close();
}
static int n, arr[];
static int binarySearch(int H) {
int lo = 0, hi = H, mid;
while (lo < hi) {
mid = (lo + hi) / 2;
if (check(mid)) hi = mid;
else lo = mid + 1;
}
if(lo > 0 && check(lo-1)) return lo-1;
return lo;
}
static boolean check(int m){
DSU dsu = new DSU(2*n);
for (int i = 0; i < n; i++) {
int u = arr[2*i], v = arr[2*i+1];
if(u > m) return false;
if(v > m){
if(++dsu.cycle[dsu.find(u)] >= 2) return false;
}
else{
if(!dsu.union(u, v)){
if(++dsu.cycle[dsu.find(u)] >= 2) return false;
}
else{
if(dsu.cycle[dsu.find(u)] >= 2) return false;
}
}
}
return true;
}
static class DSU{
int parent[], cycle[], n;
DSU(int N){
n = N;
parent = new int[N];
cycle = new int[N];
for(int i = 0; i < N; i++){
parent[i] = i;
}
}
DSU(int [] p){
parent = p; n = p.length;
}
int find(int i) {
int p = parent[i];
if (i == p) return i;
return parent[i] = find(p);
}
boolean equiv(int u, int v){
return find(u) == find(v);
}
boolean union(int u, int v){
u = find(u); v = find(v);
if(u != v) {
parent[u] = parent[v];
cycle[v] += cycle[u];
}
return u != v;
}
int count(){
int cnt = 0;
for(int i = 0; i < n; i++){
if(i == find(i)) cnt++;
}
return cnt;
}
}
public static int[] shrink(int[] a) {
int n = a.length;
long[] b = new long[n];
for(int i = 0;i < n;i++)b[i] = (long)a[i]<<32|i;
Arrays.sort(b);
int[] ret = new int[n];
int p = 0;
for(int i = 0;i < n;i++) {
if(i>0 && (b[i]^b[i-1])>>32!=0)p++;
ret[(int)b[i]] = p;
}
return ret;
}
static void debug(Object...obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
static final int ints[] = new int[128];
public FastReader(InputStream is){
for(int i='0';i<='9';i++) ints[i]=i-'0';
this.is = is;
}
public int readByte(){
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while((b = readByte()) != -1 && isSpaceChar(b));
return b;
}
public String next(){
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt(){
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = (num<<3) + (num<<1) + ints[b];
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
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<<3) + (num<<1) + ints[b];
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
/* public char nextChar() {
return (char)skip();
}*/
public char[] next(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 buff[] = new char[1005];
public char[] nextCharArray(){
int b = skip(), p = 0;
while(!(isSpaceChar(b))){
buff[p++] = (char)b;
b = readByte();
}
return Arrays.copyOf(buff, p);
}*/
}
}
|
quadratic
|
1027_F. Session in BSU
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
Arrays.sort(a);
int ans = 0, r = k, p = n-1;
while (r < m && p >= 0) {
r = r - 1 + a[p];
p--;
ans++;
}
if (r < m) out.println("-1");
else out.println(ans);
out.flush();
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
//package test_1177a;
import java.util.Scanner;
import java.util.Scanner;
public class test1177b{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
long k = sc.nextLong();
long k1 =0,k2 = 0;
long p = 1;
String str="";
for (int i=1; i<=12;i++){
if (k>= k1 && k <= k1 + p * 9 *i){
// Нашли порядок
long kk = ((k - k1) % i);
k2 = p + (k - k1) / i -1;
if (kk != 0) k2 ++;
str =""+ k2;
if(str.length() > i) {
k2--;
str =""+ k2;
kk =0;
}
if(kk > 0){
System.out.println(str.charAt((int)kk-1));
}else{
System.out.println(str.charAt(i-1));
}
break;
}else {
k1 += p * 9 *i;
p = p * 10;
}
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Set;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.TreeSet;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Zakhar Voit
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Set <Integer> vis = new TreeSet<Integer>();
Arrays.sort(a);
int ans = 0;
for (int i = 0; i < n; i++) {
if (!(a[i] % k == 0 && vis.contains(a[i] / k))) {
++ans;
vis.add(a[i]);
}
}
out.println(ans);
}
}
class Scanner {
BufferedReader in;
StringTokenizer tok;
public Scanner(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
tok = new StringTokenizer("");
}
public String nextToken() {
if (!tok.hasMoreTokens()) {
try {
String newLine = in.readLine();
if (newLine == null)
throw new InputMismatchException();
tok = new StringTokenizer(newLine);
} catch (IOException e) {
throw new InputMismatchException();
}
return nextToken();
}
return tok.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import static java.lang.Math.*;
public class Main {
private FastScanner scanner = new FastScanner();
public static void main(String[] args) {
new Main().solve();
}
private void solve() {
int n = scanner.nextInt();
Map<Integer, Integer> cnt = new HashMap<>();
for (int i = 0; i < n; i++) {
String s = scanner.nextLine();
LinkedList<Character> st = new LinkedList<>();
for (char c : s.toCharArray()) {
if (c == ')' && !st.isEmpty() && st.getLast() == '(') {
st.pollLast();
continue;
}
st.addLast(c);
}
int t = st.size();
Set<Character> set = new HashSet<>(st);
if (set.size() > 1) {
continue;
}
if (set.isEmpty()) {
cnt.put(0, cnt.getOrDefault(0, 0) + 1);
continue;
}
if (st.getLast() == '(') {
cnt.put(t, cnt.getOrDefault(t, 0) + 1);
} else {
cnt.put(-t, cnt.getOrDefault(-t, 0) + 1);
}
}
long ans = 0;
for (int next : cnt.keySet()) {
if (next == 0) {
ans += (long) cnt.get(next) * (cnt.get(next) - 1) + cnt.get(next);
} else if (next > 0) {
int t = next * -1;
if (cnt.containsKey(t)) {
ans += (long) cnt.get(next) * cnt.get(t);
}
}
}
System.out.print(ans);
}
class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 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();
}
int nextInt() {
return Integer.parseInt(next());
}
Integer[] nextA(int n) {
Integer a[] = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
linear
|
990_C. Bracket Sequences Concatenation Problem
|
CODEFORCES
|
/**
* BaZ :D
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main
{
static Reader scan;
static PrintWriter pw;
static int n,k,left[],right[],arr[];
static long MOD = 1000000007,count[],dp[];
public static void main(String[] args) {
new Thread(null,null,"BaZ",1<<25)
{
public void run()
{
try
{
solve();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static void solve() throws IOException
{
scan = new Reader();
pw = new PrintWriter(System.out,true);
StringBuilder sb = new StringBuilder();
n = ni();
k = ni();
int stack[] = new int[1000001];
int top = -1;
arr = new int[n];
left = new int[n];
right = new int[n];
for(int i=0;i<n;++i) {
arr[i] = ni();
while(top>=0 && arr[stack[top]]<=arr[i])
top--;
if(top==-1)
left[i] = 0;
else left[i] = stack[top]+1;
stack[++top] = i;
}
top = -1;
for(int i=n-1;i>=0;--i) {
while(top>=0 && arr[stack[top]]<arr[i])
top--;
if(top==-1)
right[i] = n-1;
else right[i] = stack[top]-1;
stack[++top] = i;
}
//pa("left", left);
//pa("right", right);
dp = new long[n+1];
for(int i=0;i<=n;++i) {
if(i<k)
continue;
dp[i] = dp[i-k+1] + (i-k+1);
}
count = new long[n];
long ans = 0;
for(int i=0;i<n;++i) {
int len = right[i]-left[i]+1;
int lef = i-left[i];
int rig = right[i]-i;
long count = dp[len] - dp[lef] - dp[rig];
if(count>=MOD)
count%=MOD;
ans += count*arr[i];
if(ans>=MOD)
ans%=MOD;
}
pl(ans);
pw.flush();
pw.close();
}
static int ni() throws IOException
{
return scan.nextInt();
}
static long nl() throws IOException
{
return scan.nextLong();
}
static double nd() throws IOException
{
return scan.nextDouble();
}
static void pl()
{
pw.println();
}
static void p(Object o)
{
pw.print(o+" ");
}
static void pl(Object o)
{
pw.println(o);
}
static void psb(StringBuilder sb)
{
pw.print(sb);
}
static void pa(String arrayName, Object arr[])
{
pl(arrayName+" : ");
for(Object o : arr)
p(o);
pl();
}
static void pa(String arrayName, int arr[])
{
pl(arrayName+" : ");
for(int o : arr)
p(o);
pl();
}
static void pa(String arrayName, long arr[])
{
pl(arrayName+" : ");
for(long o : arr)
p(o);
pl();
}
static void pa(String arrayName, double arr[])
{
pl(arrayName+" : ");
for(double o : arr)
p(o);
pl();
}
static void pa(String arrayName, char arr[])
{
pl(arrayName+" : ");
for(char o : arr)
p(o);
pl();
}
static void pa(String listName, List list)
{
pl(listName+" : ");
for(Object o : list)
p(o);
pl();
}
static void pa(String arrayName, Object[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(Object o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, int[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(int o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, long[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(long o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, char[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(char o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, double[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(double o : arr[i])
p(o);
pl();
}
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
}
|
linear
|
1037_F. Maximum Reduction
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class ProblemaNoldbaha implements Runnable{
public static void main(String[] args) throws IOException {
new Thread(new ProblemaNoldbaha()).start();
}
BufferedReader br;
StringTokenizer in;
PrintWriter out;
public String nextToken() throws IOException{
while (in == null || !in.hasMoreTokens()){
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public int nextInt() throws IOException{
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException{
return Double.parseDouble(nextToken());
}
public void solve() throws IOException{
int n = nextInt();
int k = nextInt();
int[] prime = new int[1000];
int l = 0;
for (int i = 2; i <= n; i++) {
boolean f = false;
for (int j = 2; j < i; j++) {
if (i % j == 0){
f = true;
break;
}
}
if (!f){
prime[l] = i;
l++;
}
}
int count = 0;
for (int i = 2; i < l; i++) {
boolean f = false;
for (int j = 0; j < l - 1; j++) {
if (prime[j] + prime[j + 1] + 1 == prime[i]){
f = true;
break;
}
}
if (f) count++;
}
if (count >= k){
out.println("YES");
}
else{
out.println("NO");
}
}
public void run(){
try{
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
catch(IOException e){
e.printStackTrace();
System.exit(1);
}
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CFJava {
private static void println(Integer n) {
System.out.println(n);
}
private static void println(String s) {
System.out.println(s);
}
private static void print(Integer n) {
System.out.print(n);
}
private static void print(String s) {
System.out.print(s);
}
public static void main(String[] args) throws IOException {
MyScanner scanner = new MyScanner();
int n = scanner.nextInt();
int k = scanner.nextInt();
Integer[] a = scanner.getIntArray(n);
Arrays.sort(a);
TreeSet<Integer> res = new TreeSet<Integer>();
for (Integer i: a){
if (!res.contains(i/k)||(i%k!=0))
res.add(i);
}
println(res.size());
}
}
class Pair {
public int x;
public int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
class MyScanner {
private BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private String[] buffer;
private int pos = 0;
public Integer nextInt() throws IOException {
if (buffer == null) {
buffer = in.readLine().split(" ");
pos = 0;
}
if (buffer.length <= pos) {
buffer = in.readLine().split(" ");
pos = 0;
}
pos++;
return Integer.parseInt(buffer[pos - 1]);
}
public String nextString() throws IOException {
if (buffer == null) {
buffer = in.readLine().split(" ");
pos = 0;
}
if (buffer.length <= pos) {
buffer = in.readLine().split(" ");
pos = 0;
}
pos++;
return buffer[pos - 1];
}
public ArrayList<Integer> getIntList(Integer n) throws IOException {
ArrayList<Integer> result = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++)
result.add(nextInt());
return result;
}
public Integer[] getIntArray(Integer n) throws IOException {
Integer[] result = new Integer[n];
for (int i = 0; i < n; i++)
result[i]= (nextInt());
return result;
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
BufferedReader in;
StringTokenizer str = null;
PrintWriter out;
private String next() throws Exception{
while (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());
}
final int oo = Integer.MAX_VALUE;
int [][]s;
int n, ALL;
public void run() throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
n = nextInt();
char []a = next().toCharArray();
s = new int[n][52];
boolean []set = new boolean[52];
for(int i = 0; i < n; ++i) {
int pos = get(a[i]);
if (!set[pos]) {
++ALL;
set[pos] = true;
}
for(int j = 0; j < 52; ++j) {
if (i > 0) {
s[i][j] += s[i-1][j];
}
if (j == pos) {
s[i][j]++;
}
}
}
int ret = oo;
for(int i = 0; i < n; ++i) {
ret = Math.min(ret, get(i));
}
out.println(ret);
out.close();
}
private int get(int i) {
int lo = i - 1, hi = n;
while(hi - lo > 1) {
int m = lo + (hi - lo) / 2;
int c = 0;
for(int j = 0; j < 52; ++j) {
if (sum(j, i, m) > 0) {
++c;
}
}
if (c < ALL) {
lo = m;
} else {
hi = m;
}
}
if (hi != n) {
return hi - i + 1;
}
return oo;
}
private int sum(int pos, int l, int r) {
int ret = s[r][pos];
if (l > 0) ret -= s[l - 1][pos];
return ret;
}
private int get(char x) {
if ('a' <= x && x <= 'z') return (int)(x - 'a');
return (int)(x - 'A' + 26);
}
public static void main(String[] args) throws Exception{
new Main().run();
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/** Created by huhansan on 2017/10/9. */
public class CF_8C implements Runnable {
int[] step = new int[1 << 24]; //每个状态所需要的步数
int[] steplast = new int[1 << 24]; //当前状态上一个
int n;
int vs[] = new int[24];
int vd[][] = new int[24][24];
int x_bag, y_bag;
int x[] = new int[24], y[] = new int[24];
/** */
private void solve() throws IOException {
x_bag = nextInt();
y_bag = nextInt();
n = nextInt();
for (int i = 0; i < n; i++) {
x[i] = nextInt();
y[i] = nextInt();
}
//计算所有物品单取的全值和 任意两件物品一起取的权值
for (int i = 0; i < n; i++) {
vs[i] = 2 * ((x[i] - x_bag) * (x[i] - x_bag) + (y[i] - y_bag) * (y[i] - y_bag));
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
vd[i][j] =
(x[i] - x_bag) * (x[i] - x_bag)
+ (y[i] - y_bag) * (y[i] - y_bag)
+ (x[j] - x_bag) * (x[j] - x_bag)
+ (y[j] - y_bag) * (y[j] - y_bag)
+ (x[i] - x[j]) * (x[i] - x[j])
+ (y[i] - y[j]) * (y[i] - y[j]);
}
}
//记录达到每一个状态所需的最小步数和最后一次取得物品
for (int i = 1; i < 1 << n; i++) {
int j, k = 0, l, m, lastState;
for (j = 1; (i & j) == 0 && j < 1 << n; j <<= 1) {
k++;
}
lastState = i & (~j);
step[i] = step[lastState] + vs[k];
steplast[i] = lastState;
m = k;
for (l = j << 1; l < 1 << n; l <<= 1) {
m++;
if ((lastState & l) != 0) {
if (step[i] > step[lastState & (~l)] + vd[k][m]) {
step[i] = step[lastState & (~l)] + vd[k][m];
steplast[i] = lastState & (~l);
}
}
}
// System.out.println(steplast[i]+"---"+i+"---"+step[i]);
}
writer.println(step[(1 << n) - 1]);
int i = (1 << n) - 1;
writer.print("0 ");
while (i != 0) {
for (int j = 1, m = 1; j <= i; j <<= 1, m++) {
if ((j & (i ^ steplast[i])) != 0) {
writer.print(m + " ");
}
}
writer.print("0 ");
i = steplast[i];
}
}
public static void main(String[] args) {
new CF_8C().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
/**
@author KhanhNguyenn
*/
public class C{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
// sub-problem: 2 orders to merge together x1,x2,..,xn and y1,y2,..,ym
// Dựa vào bài toán chia kẹp Euler, ta chứng minh dc số cách merge là
// (m+n)C(m-1)=(m+n)C(n+1)
static class Task{
int M;
public void solve(InputReader in, PrintWriter out) {
int n= in.nextInt(); M= in.nextInt();
if(n<=1){
out.println(n);
return;
}
int[] pow2= new int[n+1];
pow2[0]=1;
for(int i=1;i<=n;i++) pow2[i]=mul(2,pow2[i-1]);
// calculate nCk
// nCk= (n-1)C(k-1)+ (n-1)Ck
int[][] Ckn= new int[n+1][n+1];
for(int i=0;i<=n;i++){
Ckn[i][i]=1; Ckn[0][i]=1;
for(int j=i-1;j>=1;j--){
Ckn[j][i]= add(Ckn[j-1][i-1],Ckn[j][i-1]);
}
}
int ans=0;
int[][] dp= new int[n+1][n+1];
dp[1][1]=1;
//dp[i][j]: number of ways to turn on first i , using j manually
for(int i=2;i<=n;i++){
dp[i][i]= pow2[i-1];
for(int j=1;j<=i-1;j++){
for(int k=1;k<=j;k++){
dp[i][j]= add(dp[i][j],mul(mul(pow2[k-1],dp[i-k-1][j-k]),Ckn[k][j]));
}
}
}
for(int i=0;i<=n;i++) ans= add(ans,dp[n][i]);
out.println(ans);
}
public int add(int a, int b){
a+=b;
if(a>=M) a-=M;
return a;
}
public int mul(int a, int b){
long res= (long)a*(long)b;
res %=M;
return (int)res;
}
}
static class Pair {
public String x;
public int y;
public Pair(String x, int y){
this.x = x;
this.y=y;
}
// @Override
// public int compareTo(Pair o) {
// if (this.x > o.x){
// return 1;
// }
// else if (this.x < o.x){
// return -1;
// }
// else{
// return Integer.compare(this.y, o.y);
// }
// }
}
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble(){
return Double.parseDouble(nextToken());
}
public long nextLong(){
return Long.parseLong(nextToken());
}
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class PhoenixAndComputers {
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 mod = Integer.parseInt(st.nextToken());
long[][] dp = new long[n+2][n+1];
long[] pow = new long[n+1];
pow[0] = 1;
for (int i=1; i <= n; i++){
pow[i] = pow[i-1]*2;
pow[i] %= mod;
}
long[][] choose = new long[n*2+1][n+1];
for (int i=0; i <= n; i++){
choose[i][i] = 1;
}
for (int i=1; i <= n*2; i++){
for (int j=0; j <= n; j++){
choose[i][j] = choose[i-1][j];
if (j > 0){
choose[i][j] += choose[i-1][j-1];
}
choose[i][j] %= mod;
}
}
dp[0][0] = 1;
for (int i=0; i < n; i++){ // number of computers on
for (int j=0; j <= i; j++){ // number manually turned on
for (int k=1; k+i <= n; k++){ // number of computers manually turned on in next "block"
dp[i+k+1][j+k] += (pow[k-1] * choose[j+k][k])%mod * dp[i][j];
dp[i+k+1][j+k] %= mod;
}
}
}
long ans = 0;
for (int j=0; j <= n; j++){
ans += dp[n+1][j];
ans %= mod;
}
System.out.println(ans);
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.util.Scanner;
public class Main2 {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
long s = input.nextLong();
long e = input.nextLong();
System.out.println(count(s,e));
}
public static long count(long s,long e){
int ncount = 0;
long es = e;
while(es != 0){
es /= 2;
ncount++;
}
while(ncount >= 0){
if(((s>>ncount-1)&1) == 1 && ((e>>ncount-1)&1) == 0 || ((s>>ncount-1)&1) == 0 && ((e>>ncount-1)&1) == 1){
break;
}
ncount--;
}
if(ncount >= 0){
return (long)Math.pow(2, ncount)-1;
}else{
return 0;
}
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class A
{
public static void main(String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
System.out.println(rec(in.nextLong(), in.nextLong()));
}
private static long rec(long a, long b)
{
return b == 0 ? 0 : a/b + rec(b, a%b);
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
boolean[] isF = new boolean[n];
for (int i = 0; i < n; i++) {
isF[i] = in.readCharacter() == 'f';
}
int[][] mem = new int[n + 1][n + 1];
mem[n][0] = 1;
for (int idx = n - 1; idx >= 0; idx--) {
for (int indentLevel = 0; indentLevel < n; indentLevel++) {
mem[idx + 1][indentLevel + 1] += mem[idx + 1][indentLevel];
mem[idx + 1][indentLevel + 1] %= MiscUtils.MOD7;
int res = isF[idx] ?
mem[idx + 1][indentLevel + 1] - mem[idx + 1][indentLevel] :
mem[idx + 1][indentLevel];
mem[idx][indentLevel] = (res + MiscUtils.MOD7) % MiscUtils.MOD7;
}
}
out.printLine(mem[0][0]);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class MiscUtils {
public static final int MOD7 = (int) (1e9 + 7);
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
//I'm Whiplash99
import java.io.*;
import java.util.*;
public class C
{
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N;
int T=Integer.parseInt(br.readLine().trim());
StringBuilder sb=new StringBuilder();
while (T-->0)
{
N=Integer.parseInt(br.readLine().trim());
int[] a=new int[N];
for(i=0;i<N;i++) a[i]=Integer.parseInt(br.readLine().trim());
int end=1;
int[][] ans=new int[N][N+10];
ans[0][0]=1;
for(i=1;i<N;i++)
{
while (true)
{
if(ans[i-1][end]==a[i]-1) break;
end--;
}
for(int j=0;j<end;j++) ans[i][j]=ans[i-1][j];
ans[i][end]=a[i];
end++;
}
for(i=0;i<N;i++)
{
for(int j=0;j<N&&ans[i][j]!=0;j++)
{
sb.append(ans[i][j]);
if(ans[i][j+1]!=0) sb.append('.');
}
sb.append("\n");
}
}
System.out.println(sb);
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class AA {
static class Pair implements Comparable<Pair> {
public int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair p) {
if (p.x != x)
return x - p.x;
return y - p.y;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int t = in.nextInt() * 2;
List<Pair> l = new ArrayList<Pair>();
for (int i = 0; i < n; i++) {
int c = in.nextInt() * 2;
int a = in.nextInt();
l.add(new Pair(c - a, c + a));
}
Collections.sort(l);
int ret = 2;
for (int i = 1; i < n; i++) {
if (l.get(i).x - l.get(i-1).y > t)
ret += 2;
else if (l.get(i).x - l.get(i-1).y == t)
ret += 1;
}
System.out.println(ret);
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {
}
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
int MAXDEG = 5;
void gen() throws FileNotFoundException {
PrintWriter out = new PrintWriter("input.txt");
int n = 100000;
Random rnd = new Random();
out.println(n);
for (int i = 0; i < n; i++) {
out.println("R" + (rnd.nextInt(1000000) + 1) + "C" + (rnd.nextInt(1000000) + 1));
}
out.close();
}
void gen2() throws FileNotFoundException {
PrintWriter out = new PrintWriter("input.txt");
int n = 100000;
Random rnd = new Random();
out.println(n);
for (int i = 0; i < n; i++) {
int len = rnd.nextInt(MAXDEG) + 1;
String pref = "";
for (int j = 0; j < len; j++)
pref += (char) (rnd.nextInt(26) + 'A');
out.println(pref + (rnd.nextInt(1000000) + 1));
}
out.close();
}
private void run() throws IOException {
// gen2();
// if (true) return;
// System.setOut(new PrintStream("output.txt"));
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = nextInt();
int[] sumDegs = new int[MAXDEG + 1];
sumDegs[0] = 1;
int deg = 1;
for (int i = 1; i <= MAXDEG; i++) {
deg *= 26;
sumDegs[i] = sumDegs[i - 1] + deg;
}
for (int i = 0; i < n; i++) {
String s = nextLine();
String pref = "";
int endPos = -1;
for (int j = 0; j < s.length(); j++) {
if (!isLet(s.charAt(j))) {
endPos = j;
break;
}
pref += s.charAt(j);
}
int num = -1;
try {
num = Integer.parseInt(s.substring(endPos));
} catch (Exception e) {
}
if (num != -1) {
int col = sumDegs[pref.length() - 1];
int val = 0;
for (int j = 0; j < pref.length(); j++) {
val = val * 26 + (pref.charAt(j) - 'A');
}
col += val;
out.println("R" + num + "C" + col);
} else {
int row = Integer.parseInt(s.substring(1, s.indexOf('C')));
int col = Integer.parseInt(s.substring(s.indexOf('C') + 1));
int len = MAXDEG;
while (col < sumDegs[len])
len--;
len++;
col -= sumDegs[len - 1];
String res = "";
while (col > 0) {
res = (char) (col % 26 + 'A') + res;
col /= 26;
}
while (res.length() < len)
res = "A" + res;
out.println(res + row);
}
}
in.close();
out.close();
}
private boolean isLet(char c) {
return c >= 'A' && c <= 'Z';
}
void chk(boolean b) {
if (b)
return;
System.out.println(new Error().getStackTrace()[1]);
exit(999);
}
void deb(String fmt, Object... args) {
System.out.printf(Locale.US, fmt + "%n", args);
}
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.KeyPair;
import java.util.*;
public class Main {
static long[][] c ;
static long[] arr;
static long n , m , k;
static long dp[][][];
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int n = Reader.nextInt();
int[] arr = new int[n];
int[] mark = new int[n];
for (int i = 0 ; i < n ; i++){
arr[i] = Reader.nextInt();
}
Arrays.sort(arr);
int[] v = new int[n];
int ans = 0;
for (int i = 0 ; i < n ; i++){
if (v[i]==0){
for (int j = i ; j < n ; j++){
if (arr[j]%arr[i]==0){
v[j] = arr[i];
}
}
}
}
TreeSet<Integer> s = new TreeSet<>();
for (int i = 0 ; i < n ;i++){
s.add(v[i]);
}
System.out.println(s.size());
}
public static void sortbyColumn_asc(int arr[][], int col)
{
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator<int[]>() {
@Override
// Compare values according to columns
public int compare(final int[] entry1,
final int[] entry2) {
// To sort in descending order revert
// the '>' Operator
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
}); // End of function call sort().
}
public static void sortbyColumn_dsc(int arr[][], int col)
{
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator<int[]>() {
@Override
// Compare values according to columns
public int compare(final int[] entry1,
final int[] entry2) {
// To sort in descending order revert
// the '>' Operator
if (entry1[col] > entry2[col])
return -1;
else
return 1;
}
}); // End of function call sort().
}
static void swap(char[] arr , int i , int j){
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
static void swap(int[] arr , int i , int j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
class Node implements Comparable<Node>{
int a , b;
Node(int a , int b){
this.a = a;
this.b = b;
}
public int compareTo(Node o) {
if (this.a == o.a){
return this.b - o.b;
}
return this.a - o.a;
}
}
class Edge implements Comparable<Edge>{
int x , y , w;
public Edge(int x, int y, int w) {
this.x = x;
this.y = y;
this.w = w;
}
@Override
public int compareTo(Edge o) {
return this.w - o.w;
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int ans = 0;
int t= sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
int nn = sc.nextInt();
ans+=a;
if(b<c){
ans += (t-nn) * (c - b);
}
}
System.out.println(ans);
}
}
|
linear
|
964_B. Messages
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.*;
public class Main{
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();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] nextArray(long n) {
long[] a = new long[(int) n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static class FastWriter extends PrintWriter {
FastWriter(){
super(System.out);
}
void println(int[] array) {
for(int i=0; i<array.length; i++) {
print(array[i]+" ");
}
println();
}
void println(long [] array) {
for(int i=0; i<array.length; i++) {
print(array[i]+" ");
}
println();
}
}
static int x,y;
public static void main(String[] args){
FastScanner in = new FastScanner();
FastWriter out = new FastWriter();
int n=in.nextInt();
int m=in.nextInt();
int k=in.nextInt();
int[][] right=new int[n][m-1];
int[][] down=new int[n-1][m];
for (int i = 0; i < n; i++) {
right[i]=in.nextArray(m-1);
}
for (int i = 0; i < n - 1; i++) {
down[i]=in.nextArray(m);
}
if(k%2!=0){
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.print("-1 ");
}
out.println();
}
}else {
int[][] dp=new int[n][m];
int[][] dp1=new int[n][m];
for (int i = 0; i < k / 2; i++) {
for (int j = 0; j < n; j++) {
for (int l = 0; l < m; l++) {
int ans=Integer.MAX_VALUE;
if(j>0){
ans=Math.min(ans,dp[j-1][l]+down[j-1][l]);
}
if(l>0){
ans=Math.min(ans,dp[j][l-1]+right[j][l-1]);
}
if(j!=n-1){
ans=Math.min(ans,dp[j+1][l]+down[j][l]);
}
if(l!=m-1){
ans=Math.min(ans,dp[j][l+1]+right[j][l]);
}
dp1[j][l]=ans;
}
}
dp=dp1;
dp1=new int[n][m];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.println((2*dp[i][j])+" ");
}
out.println();
}
}
out.close();
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Three{
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
PrintWriter out = new PrintWriter(System.out);
pair[] points = new pair [3];
for (int i = 0; i < 3; ++i) {
int x = in.nextInt();
int y = in.nextInt();
points[i] = new pair (x, y);
}
Arrays.sort(points);
int MaxY = Math.max(Math.max(points[0].y, points[1].y), points[2].y);
int MinY = Math.min(Math.min(points[0].y, points[1].y), points[2].y);
out.println(MaxY - MinY + points[2].x - points[0].x + 1);
for (int i = MinY; i <= MaxY; ++i)
out.println(points[1].x + " " + i);
for (int i = points[0].x; i < points[1].x; ++i)
out.println(i + " " + points[0].y);
for (int i = points[1].x + 1; i <= points[2].x; ++i)
out.println(i + " " + points[2].y);
out.close();
}
public static class pair implements Comparable<pair> {
int x, y;
public pair (int x_, int y_) {
x = x_; y = y_;
}
@Override
public int compareTo(pair o) {
return x - o.x;
}
}
}
|
nlogn
|
1086_A. Connect Three
|
CODEFORCES
|
/**
* Created with IntelliJ IDEA.
* User: yuantian
* Date: 3/24/13
* Time: 2:18 AM
* Copyright (c) 2013 All Right Reserved, http://github.com/tyuan73
*/
import java.util.*;
public class Pipeline {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long n = in.nextLong();
long k = in.nextLong();
if (n == 1) {
System.out.println(0);
return;
}
if (k >= n) {
System.out.println(1);
return;
}
long total = (k + 2) * (k - 1) / 2 - (k - 2);
if (total < n) {
System.out.println(-1);
return;
}
/**
* non-binary search version, O(n)
* it will failed because of "over time limit erro" on this case:
* 499999998500000001 1000000000 => 999955279
*
total = 1;
for(int i = (int)k; i >= 2; i--) {
total += i - 1;
if(total >= n) {
System.out.println(k-i+1);
return;
}
}
*/
/**
* binary search search version. O(lgn)
*/
int i = 2, j = (int) k;
while (i < j) {
int m = (i + j + 1) / 2;
total = (k + m) * (k - m + 1) / 2 - (k - m);
if (total < n)
j = m - 1;
else
i = m;
}
System.out.println(k - i + 1);
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ProblemA {
private final BufferedReader in;
private final PrintStream out;
private StringTokenizer tok = new StringTokenizer("");
private String nextLine = null;
public static void main(String[] args) throws Exception {
new ProblemA();
}
private ProblemA() throws Exception {
in = new BufferedReader(new InputStreamReader(System.in));
out = System.out;
start();
end();
}
private int nextInt() {
return Integer.parseInt(nextWord());
}
private String nextWord() {
if (tok.hasMoreTokens()) {
return tok.nextToken();
} else {
while (!tok.hasMoreTokens()) {
try {
nextLine = in.readLine();
if (nextLine == null) {
return null;
} else {
tok = new StringTokenizer(nextLine);
}
} catch (IOException ex) {
Logger.getLogger(ProblemA.class.getName()).log(Level.SEVERE, null, ex);
}
}
return tok.nextToken();
}
}
private void start() {
int n = nextInt();
int[] a = new int[n];
boolean allOne = true;
for (int i = 0; i < n; i++) {
a[i] = nextInt();
if (a[i] != 1) {
allOne = false;
}
}
Arrays.sort(a);
int[] res = new int[n];
res[0] = 1;
for (int i = 1; i < n; i++) {
res[i] = a[i - 1];
}
if (allOne) {
for (int i = 0; i < n - 1; i++) {
out.print(a[i] + " ");
}
out.print(2);
} else {
for (int i = 0; i < n; i++) {
out.print(res[i] + " ");
}
}
}
private void end() {
out.close();
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.String.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//(new FileReader("input.in"));
StringBuilder out = new StringBuilder();
StringTokenizer tk;
long n = parseLong(in.readLine());
System.out.println("25");
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.IOException;
import java.util.StringTokenizer;
/*
* @author Tnascimento
*/
public class MaeDosDragoes {
// public static StringTokenizer tokenizer;
// public static BufferedReader reader;
public static PrintWriter saida = new PrintWriter(System.out, false);
// public static String proximo() {
// while (tokenizer == null || !tokenizer.hasMoreElements()) {
// try {
// tokenizer = new StringTokenizer(reader.readLine());
// } catch (RuntimeException e) {
// e.printStackTrace();
// }
// }
// return tokenizer.nextToken();
// }
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());
}
}
public static void main(String[] args) {
FastScanner fastScanner = new FastScanner();
int proximoInt = fastScanner.nextInt();
double proximoDouble = fastScanner.nextInt();
long[] graph = new long[proximoInt];
for(Integer i = 0; i < proximoInt; i++) {
for(Integer j =0; j < proximoInt; j++) {
Integer val = fastScanner.nextInt();
if (val.equals(1) || i.equals(j)) {
graph[i] |= 1L << j;
}
}
}
int szLeft = proximoInt/2;
int szRight = proximoInt - szLeft;
int[] dp = new int[1 << szLeft];
int maxMask = 1 << szLeft;
for(int mask = 1; mask <maxMask; mask++) {
int curMask = mask;
for(int j = 0; j < szLeft; j++) {
if (((1 << j) & mask) > 0) {
curMask &= graph[j + szRight] >> szRight;
dp[mask] = Math.max(dp[mask], dp[mask ^ (1 << j)]);
}
}
if (mask == curMask) {
dp[mask] = Math.max(dp[mask],Integer.bitCount(mask));
}
}
int ans = 0;
int rmaxMask = 1 << szRight;
for(int mask = 0; mask < rmaxMask; mask++) {
int curMask = mask;
int oMask = maxMask -1;
for(int j = 0; j < szRight; j++) {
if (((1 << j) & mask) > 0) {
curMask &= (graph[j] & (rmaxMask-1));
oMask &= graph[j] >> szRight;
}
}
if (curMask != mask) continue;
ans = Math.max(ans, Integer.bitCount(mask) + dp[oMask]);
}
proximoDouble/=ans;
saida.println(proximoDouble * proximoDouble * (ans * (ans-1))/2);
saida.flush();
}
}
|
np
|
839_E. Mother of Dragons
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.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
*
* @author lucasr
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyScanner in = new MyScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
EPhoenixAndComputers solver = new EPhoenixAndComputers();
solver.solve(1, in, out);
out.close();
}
static class EPhoenixAndComputers {
public static MyScanner sc;
public static PrintWriter out;
public void solve(int testNumber, MyScanner sc, PrintWriter out) {
EPhoenixAndComputers.sc = sc;
EPhoenixAndComputers.out = out;
int n = sc.nextInt();
long M = sc.nextLong();
MathLib.MOD = M;
long[][] comb = MathLib.getComb(n + 5);
long[] pots2 = MathLib.getPots(2, n + 2);
long[] inv = new long[n + 5];
for (int i = 1; i < inv.length; i++) {
inv[i] = MathLib.inverse(i);
}
long[][] ret = new long[n + 1][n + 1]; // size, cant
for (int size = 0; size <= n; size++) {
if (size <= 1) {
ret[size][size] = 1;
} else if (size == 2) {
ret[size][2] = 2;
} else {
long[] me = ret[size];
me[size] = pots2[size - 1];
for (int i = 1; i + 1 < size; i++) {
int prev = i, next = size - i - 1;
long tmp = pots2[i - 1];
for (int c = 0; c <= next; c++) {
long tot = (ret[next][c] * comb[c][c + prev]) % MathLib.MOD;
tot = (tot * tmp) % MathLib.MOD;
me[prev + c] += tot;
me[prev + c] %= MathLib.MOD;
}
}
}
}
long ans = 0;
for (int i = 0; i <= n; i++) {
ans += ret[n][i];
}
ans %= MathLib.MOD;
out.println(ans);
}
}
static class MathLib {
public static long MOD = 1000000007;
public static long mult(long x, long y) {
return (x * y) % MOD;
}
public static long pow(long base, long exp) {
if (exp == 0) return 1;
if ((exp & 1) == 1) return mult(base, pow(base, exp - 1));
return pow(mult(base, base), exp / 2);
}
public static long inverse(long x) {
return pow(x, MOD - 2);
}
public static long[] getPots(long base, int max) {
long[] ret = new long[max + 1];
ret[0] = 1;
for (int i = 1; i <= max; i++) {
ret[i] = mult(ret[i - 1], base);
}
return ret;
}
public static long[][] getComb(int max) {
long[][] ret = new long[max + 1][max + 1];
for (int n = 0; n <= max; n++) {
ret[0][n] = ret[n][n] = 1;
for (int k = 1; k < n; k++) {
ret[k][n] = (ret[k - 1][n - 1] + ret[k][n - 1]) % MOD;
}
}
return ret;
}
}
static class MyScanner {
private BufferedReader br;
private StringTokenizer tokenizer;
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
// upsolve with rainboy
import java.io.*;
import java.util.*;
public class CF1187G extends PrintWriter {
CF1187G() { super(System.out); }
static class Scanner {
Scanner(InputStream in) { this.in = in; } InputStream in;
int k, l; byte[] bb = new byte[1 << 15];
byte getc() {
if (k >= l) {
k = 0;
try { l = in.read(bb); } catch (IOException e) { l = 0; }
if (l <= 0) return -1;
}
return bb[k++];
}
int nextInt() {
byte c = 0; while (c <= 32) c = getc();
int a = 0;
while (c > 32) { a = a * 10 + c - '0'; c = getc(); }
return a;
}
}
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1187G o = new CF1187G(); o.main(); o.flush();
}
static final int INF = 0x3f3f3f3f;
ArrayList[] aa_;
int n_, m_;
int[] pi, dd, bb;
int[] uu, vv, uv, cost;
int[] cc;
void init() {
aa_ = new ArrayList[n_];
for (int u = 0; u < n_; u++)
aa_[u] = new ArrayList<Integer>();
pi = new int[n_];
dd = new int[n_];
bb = new int[n_];
qq = new int[nq];
iq = new boolean[n_];
uu = new int[m_];
vv = new int[m_];
uv = new int[m_];
cost = new int[m_];
cc = new int[m_ * 2];
m_ = 0;
}
void link(int u, int v, int cap, int cos) {
int h = m_++;
uu[h] = u;
vv[h] = v;
uv[h] = u ^ v;
cost[h] = cos;
cc[h << 1 ^ 0] = cap;
aa_[u].add(h << 1 ^ 0);
aa_[v].add(h << 1 ^ 1);
}
int[] qq;
int nq = 1, head, cnt;
boolean[] iq;
void enqueue(int v) {
if (iq[v])
return;
if (head + cnt == nq) {
if (cnt * 2 <= nq)
System.arraycopy(qq, head, qq, 0, cnt);
else {
int[] qq_ = new int[nq *= 2];
System.arraycopy(qq, head, qq_, 0, cnt);
qq = qq_;
}
head = 0;
}
qq[head + cnt++] = v; iq[v] = true;
}
int dequeue() {
int u = qq[head++]; cnt--; iq[u] = false;
return u;
}
boolean spfa(int s, int t) {
Arrays.fill(pi, INF);
pi[s] = 0;
head = cnt = 0;
enqueue(s);
while (cnt > 0) {
int u = dequeue();
int d = dd[u] + 1;
ArrayList<Integer> adj = aa_[u];
for (int h_ : adj)
if (cc[h_] > 0) {
int h = h_ >> 1;
int p = pi[u] + ((h_ & 1) == 0 ? cost[h] : -cost[h]);
int v = u ^ uv[h];
if (pi[v] > p || pi[v] == p && dd[v] > d) {
pi[v] = p;
dd[v] = d;
bb[v] = h_;
enqueue(v);
}
}
}
return pi[t] != INF;
}
void push(int s, int t) {
int c = INF;
for (int u = t, h_, h; u != s; u ^= uv[h]) {
h = (h_ = bb[u]) >> 1;
c = Math.min(c, cc[h_]);
}
for (int u = t, h_, h; u != s; u ^= uv[h]) {
h = (h_ = bb[u]) >> 1;
cc[h_] -= c; cc[h_ ^ 1] += c;
}
}
void push1(int s, int t) {
for (int u = t, h_, h; u != s; u ^= uv[h]) {
h = (h_ = bb[u]) >> 1;
cc[h_]--; cc[h_ ^ 1]++;
}
}
int edmonds_karp(int s, int t) {
while (spfa(s, t))
push1(s, t);
int c = 0;
for (int h = 0; h < m_; h++)
c += cost[h] * cc[h << 1 ^ 1];
return c;
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int[] ii = new int[k];
for (int h = 0; h < k; h++)
ii[h] = sc.nextInt() - 1;
ArrayList[] aa = new ArrayList[n];
for (int i = 0; i < n; i++)
aa[i] = new ArrayList<Integer>();
for (int h = 0; h < m; h++) {
int i = sc.nextInt() - 1;
int j = sc.nextInt() - 1;
aa[i].add(j);
aa[j].add(i);
}
int t = n + k + 1;
n_ = n * t + 1;
m_ = k + (m * 2 * k + n) * (t - 1);
init();
for (int i = 0; i < n; i++) {
ArrayList<Integer> adj = aa[i];
for (int s = 0; s < t - 1; s++) {
int u = i * t + s;
for (int j : adj) {
int v = j * t + s + 1;
for (int x = 1; x <= k; x++)
link(u, v, 1, c + (x * 2 - 1) * d);
}
}
}
for (int i = 0; i < n; i++)
for (int s = 0; s < t - 1; s++) {
int u = i * t + s, v = u + 1;
link(u, v, k, i == 0 ? 0 : c);
}
for (int h = 0; h < k; h++)
link(n_ - 1, ii[h] * t + 0, 1, 0);
println(edmonds_karp(n_ - 1, 0 * t + t - 1));
}
}
|
cubic
|
1187_G. Gang Up
|
CODEFORCES
|
import java.util.Map;
import java.io.IOException;
import java.util.TreeMap;
import java.util.InputMismatchException;
import java.io.PrintStream;
import java.io.OutputStream;
import java.util.ArrayDeque;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Queue;
import java.util.Collection;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author karan173
*/
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();
}
}
class TaskB
{
int val[];
int p[];
int aneigh[], bneight[], deg[];
public void solve(int testNumber, FastReader in, PrintWriter out)
{
int n = in.ni ();
val = new int[n];
int a = in.ni ();
int b = in.ni ();
Map<Integer, Integer> set = new TreeMap<Integer, Integer> ();
p = in.iArr (n);
for (int i = 0; i < n; i++)
{
set.put (p[i], i);
}
aneigh = new int[n];
bneight = new int[n];
deg = new int[n];
for (int i = 0; i < n; i++)
{
aneigh[i] = val[i] = bneight[i] = -1;
deg[i] = 0;
}
Queue<Integer> queue = new ArrayDeque<Integer> ();
for (int i = 0; i < n; i++)
{
Integer x1 = set.get (a - p[i]);
Integer x2 = set.get (b - p[i]);
if (x1 != null)
{
aneigh[i] = x1;
deg[i]++;
}
if (x2 != null && a != b)
{
bneight[i] = x2;
deg[i]++;
}
if (deg[i] == 1)
{
queue.add (i);
}
}
while (!queue.isEmpty ())
{
int idx = queue.remove ();
if (deg[idx] != 1)
{
continue;
}
int aa = aneigh[idx];
int bb = bneight[idx];
if (aa != -1)
{
val[idx] = val[aa] = 0;
deg[aa]--;
deg[idx]--;
aneigh[aa] = -1;
aneigh[idx] = -1;
if (deg[aa] == 1)
{
int zz = bneight[aa];
bneight[zz] = -1;
deg[zz]--;
if(deg[zz] == 1)
queue.add (zz);
}
}
else
{
val[idx] = val[bb] = 1;
deg[bb]--;
deg[idx]--;
bneight[idx] = bneight[bb] = -1;
if (deg[bb] == 1)
{
//queue.add (bb);
int zz = aneigh[bb];
aneigh[zz] = -1;
deg[zz]--;
if(deg[zz] == 1)
queue.add (zz);
}
}
}
for (int i = 0; i < n; i++)
{
if (val[i] == -1 && cantBePaired(i))
{
out.println ("NO");
return;
}
}
//every person has two neighbours
out.println ("YES");
for (int i = 0; i < n; i++)
{
out.print (val[i] + " ");
}
out.println ();
}
private boolean cantBePaired(int i)
{
int aa = aneigh[i];
int bb = bneight[i];
if (aa != -1 && val[aa] == -1)
{
return false;
}
if (bb != -1 && val[bb] == -1)
{
return false;
}
return true;
}
}
class FastReader
{
public InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastReader(InputStream stream)
{
this.stream = stream;
}
public FastReader()
{
}
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 ni()
{
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read ();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
} while (!isSpaceChar (c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
{
return filter.isSpaceChar (c);
}
return isWhitespace (c);
}
public static boolean isWhitespace(int c)
{
return c==' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] iArr(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = ni ();
}
return a;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.InputMismatchException;
public class R2_D2_A {
public static void main(String[] args) {
// BufferedReader in = new BufferedReader(new
// InputStreamReader(System.in));
InputReader in = new InputReader(System.in);
int n = in.readInt();
int a = in.readInt();
int b = in.readInt();
Integer[] inp = new Integer[n];
for (int i = 0; i < inp.length; i++) {
inp[i] = in.readInt();
}
Arrays.sort(inp);
int petya = inp[inp.length-a];
int next = inp[inp.length-a-1];
int diff = petya - next;
System.out.println(diff);
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1000];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public 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
|
169_A. Chores
|
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]);
if(ans>=MOD)
ans-=MOD;
return memo2[idx][remCnt1][remCnt2][remSum] = ans;
}
private static int dp3(int cnt0, int cnt1, int cnt2, int last) {
if (cnt0 < 0 || cnt1 < 0 || cnt2 < 0)
return 0;
if (cnt0 + cnt1 + cnt2 == 0)
return 1;
if (memo3[last][cnt0][cnt1][cnt2] != -1)
return memo3[last][cnt0][cnt1][cnt2];
long ans = 0;
if (last != 0)
ans += dp3(cnt0 - 1, cnt1, cnt2, 0);
if (last != 1)
ans += dp3(cnt0, cnt1 - 1, cnt2, 1);
if (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.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Main(),"Main",1<<26).start();
}
public void run()
{
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = sc.nextInt();
int a[] = new int[n];
for(int i = 0; i < n; ++i)
a[i] = sc.nextInt();
int cnt = 0;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < i; ++j) {
if(a[i] < a[j])
cnt ^= 1;
}
}
int m = sc.nextInt();
for(int i = 0; i < m; ++i) {
int l = sc.nextInt();
int r = sc.nextInt();
long size = (long)(r - l + 1);
long subarr = size * (size - 1) / 2;
int type = (int)(subarr % 2);
if(type == 1) {
cnt ^= 1;
}
if(cnt == 0)
w.println("even");
else
w.println("odd");
}
w.close();
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class F
{
static Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int n,m,res=0;
static int[][] a=new int[20][10005],Min=new int[20][20],Min1=new int[20][20];
static int[][][] f=new int[1<<16][20][20];
static int GetBit(int x,int k)
{
return (x>>k)&1;
}
static int TurnBit(int x,int k)
{
return x^(1<<k);
}
public static void main(String[] args)
{
n=in.nextInt();
m=in.nextInt();
for(int i=0;i<n;i++)
for(int j=1;j<=m;j++)
a[i][j]=in.nextInt();
if(n==1)
{
res=(int)1e9;
for(int i=1;i<m;i++)
res=Math.min(res,Math.abs(a[0][i]-a[0][i+1]));
out.print(res);
out.close();
return;
}
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
Min[i][j]=Min1[i][j]=(int)1e9;
for(int t=1;t<=m;t++)
Min[i][j]=Math.min(Min[i][j],Math.abs(a[i][t]-a[j][t]));
for(int t=1;t<m;t++)
Min1[i][j]=Math.min(Min1[i][j],Math.abs(a[i][t]-a[j][t+1]));
}
for(int i=0;i<n;i++)
f[1<<i][i][i]=(int)1e9;
for(int mask=0;mask<(1<<n);mask++)
if(Integer.bitCount(mask)>1)
for(int i=0;i<n;i++)
if(GetBit(mask,i)==1)
for(int j=0;j<n;j++)
if(i!=j&&GetBit(mask,j)==1)
{
for(int t=0;t<n;t++)
if(j!=t&&GetBit(mask,t)==1)
f[mask][i][j]=Math.max(f[mask][i][j],Math.min(f[TurnBit(mask,j)][i][t],Min[j][t]));
if(mask==(1<<n)-1)
res=Math.max(res,Math.min(f[mask][i][j],Min1[j][i]));
}
out.print(res);
out.close();
}
}
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class SolutionB {
BufferedReader in;
StringTokenizer str;
PrintWriter out;
String SK;
String next() throws IOException {
while ((str == null) || (!str.hasMoreTokens())) {
SK = in.readLine();
if (SK == null)
return null;
str = new StringTokenizer(SK);
}
return str.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
char[] charArray() throws IOException{
return next().toCharArray();
}
public static void main(String[] args) throws IOException {
new SolutionB().run();
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
//in = new BufferedReader(new FileReader("input.txt"));
//out = new PrintWriter("output.txt");
solve();
out.close();
}
void solve() throws IOException {
//out.println(Long.MAX_VALUE);
long n = nextLong();
long k = nextLong();
long m=num1(k);
if(m<n){
out.println(-1);
return;
}
if(m==n){
out.println(k-1);
return;
}
long ans=binS(n,k);
out.println(k-ans);
}
long num1(long k){
long r=k*(k+1)/2-1;
r=r-(k-2);
return r;
}
long num2(long k){
return num1(k)-1;
}
long binS(long n, long k) {
long start, end, mid;
start = 2;
end = k;
long ret=-1;
while (start <= end) {
mid = (start + end) / 2;
if (num1(k)-num2(mid) == n) {
return mid;
} else if (num1(k)-num2(mid) < n) {
end = mid - 1;
} else {
ret=mid;
start = mid + 1;
}
}
return ret;
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
static class Fast {
StringTokenizer st;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
}
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static Fast scn = new Fast();
public static void main(String args[]) throws Exception {
int t = 1;
while(t-- > 0){
func();
}
bw.close();
}
private static void func() throws Exception{
int n = scn.nextInt();
int m = scn.nextInt();
int k = scn.nextInt();
int[][] hori = new int[n][m - 1];
int[][] vert = new int[n - 1][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m - 1; j++){
hori[i][j] = scn.nextInt();
}
}
for(int i = 0; i < n - 1; i++){
for(int j = 0; j < m; j++){
vert[i][j] = scn.nextInt();
}
}
if(k % 2 != 0){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
bw.append(-1 + " ");
}
bw.append("\n");
}
return;
}
int[][][] strg = new int[n][m][k + 1];
// for(int i = 0; i < n; i++){
// for(int j = 0; j < m; j++){
// for(int x = 0; x < k; x++)
// }
// }
int[][] answer = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
answer[i][j] = steps(i, j, hori, vert, k, strg);
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
bw.append(answer[i][j] + " ");
}
bw.append("\n");
}
}
static int steps(int x, int y, int[][] hori, int[][] vert, int k, int[][][] strg){
if(k == 0)
return 0;
if(strg[x][y][k] != 0)
return strg[x][y][k];
int xmove = x;
int ymove = y;
int ans = 0;
int val = Integer.MAX_VALUE;
if(y < hori[0].length){
xmove = x;
ymove = y + 1;
val = Math.min(val, steps(xmove, ymove, hori, vert, k - 2, strg) + (2 * hori[x][y]));
}
if(y - 1 >= 0){
xmove = x;
ymove = y - 1;
val = Math.min(val, steps(xmove, ymove, hori, vert, k - 2, strg) + (2 * hori[x][y - 1]));
// val = hori[x][y - 1];
}
if(x - 1 >= 0){
xmove = x - 1;
ymove = y;
val = Math.min(val, steps(xmove, ymove, hori, vert, k - 2, strg) + (2 * vert[x - 1][y]));
// val = vert[x - 1][y];
}
if(x < vert.length){
xmove = x + 1;
ymove = y;
val = Math.min(val, steps(xmove, ymove, hori, vert, k - 2, strg) + (2 * vert[x][y]));
// val = vert[x + 1][y];
}
// System.out.println(val);
ans += val;
return strg[x][y][k] = ans;
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
public class P1 {
public static void main(String[] args) {
System.out.println("25");
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.util.*;
public class TaskA {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
Arrays.sort(a);
int sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}
int take = 0, num = 0;
for (int i = n - 1; i > -1; i--) {
num++;
take += a[i];
sum -= a[i];
if (take > sum) {
break;
}
}
System.out.println(num);
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
//package educational.round34;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Random;
public class D {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
int[] xs = new int[3*n];
for(int i = 0;i < n;i++){
xs[3*i] = a[i];
xs[3*i+1] = a[i]-1;
xs[3*i+2] = a[i]+1;
}
xs = shuffle(xs, new Random());
int[] imap = shrinkX(xs);
BigInteger ans = BigInteger.valueOf(0L);
{
int[] ft = new int[3*n+3];
for(int i = 0;i < n;i++){
int y = Arrays.binarySearch(imap, a[i]);
int num =
i - sumFenwick(ft, y + 1) + sumFenwick(ft, y - 2);
ans = ans.add(BigInteger.valueOf((long)a[i] * num));
addFenwick(ft, y, 1);
}
}
{
int[] ft = new int[3*n+3];
for(int i = n-1;i >= 0;i--){
int y = Arrays.binarySearch(imap, a[i]);
int num =
n-1-i - sumFenwick(ft, y + 1) + sumFenwick(ft, y - 2);
ans = ans.subtract(BigInteger.valueOf((long)a[i] * num));
addFenwick(ft, y, 1);
}
}
out.println(ans);
}
public static int sumFenwick(int[] ft, int i)
{
int sum = 0;
for(i++;i > 0;i -= i&-i)sum += ft[i];
return sum;
}
public static void addFenwick(int[] ft, int i, int v)
{
if(v == 0 || i < 0)return;
int n = ft.length;
for(i++;i < n;i += i&-i)ft[i] += v;
}
public static int[] shuffle(int[] a, Random gen){ for(int i = 0, n = a.length;i < n;i++){ int ind = gen.nextInt(n-i)+i; int d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; }
public static int[] shrinkX(int[] a) {
int n = a.length;
long[] b = new long[n];
for (int i = 0; i < n; i++)
b[i] = (long) a[i] << 32 | i;
Arrays.sort(b);
int[] ret = new int[n];
int p = 0;
ret[0] = (int) (b[0] >> 32);
for (int i = 0; i < n; i++) {
if (i > 0 && (b[i] ^ b[i - 1]) >> 32 != 0) {
p++;
ret[p] = (int) (b[i] >> 32);
}
a[(int) b[i]] = p;
}
return Arrays.copyOf(ret, p + 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 D().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)); }
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class TwoSquares {
int INF = 1000;
void solve() {
int[][] s1 = new int[4][2];
for (int i = 0; i < 4; i++) {
s1[i][0] = in.nextInt();
s1[i][1] = in.nextInt();
}
int[][] s2 = new int[4][2];
for (int i = 0; i < 4; i++) {
s2[i][0] = in.nextInt();
s2[i][1] = in.nextInt();
}
if (ok(s1, s2)) {
out.println("Yes");
return;
}
rotate(s1);
rotate(s2);
if (ok(s2, s1)) {
out.println("Yes");
return;
}
out.println("No");
}
void rotate(int[][] s) {
for (int i = 0; i < 4; i++) {
int x = s[i][0], y = s[i][1];
s[i][0] = x - y;
s[i][1] = x + y;
}
}
boolean ok(int[][] s1, int[][] s2) {
int xmin = INF, xmax = -INF, ymin = INF, ymax = -INF;
for (int i = 0; i < 4; i++) {
xmin = Math.min(xmin, s1[i][0]);
xmax = Math.max(xmax, s1[i][0]);
ymin = Math.min(ymin, s1[i][1]);
ymax = Math.max(ymax, s1[i][1]);
}
for (int i = 0; i < 4; i++) {
if (s2[i][0] >= xmin && s2[i][0] <= xmax && s2[i][1] >= ymin && s2[i][1] <= ymax) return true;
}
int[] mid2 = new int[]{s2[0][0] + s2[2][0], s2[0][1] + s2[2][1]};
return mid2[0] >= xmin * 2 && mid2[0] <= xmax * 2 && mid2[1] >= ymin * 2 && mid2[1] <= ymax * 2;
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new TwoSquares().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
|
constant
|
994_C. Two Squares
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class A {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
String s=r.readLine();
int n=Integer.parseInt(s);
System.out.println(n*3/2);
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/*
* @author Ivan Pryvalov (ivan.pryvalov@gmail.com)
*/
public class Codeforces_R136_Div1_A implements Runnable{
private void solve() throws IOException {
int n = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = scanner.nextInt();
}
boolean sorted = true;
for (int i = 0; i < a.length; i++) {
if (!isOk(a, i)){
sorted = false;
}
}
if (sorted){
out.println("YES");
return;
}
List<Integer> idx = new ArrayList<Integer>();
for(int i=0; i<n; i++){
if (!isOk(a, i)){
idx.add(i);
}
}
if (idx.size() > 6){
out.println("NO");
return;
}
for(int i=0; i<idx.size(); i++){
for(int j=0; j<n; j++){
swap(a, idx.get(i), j);
if (isOk(a, idx) && isOk(a, j)){
out.println("YES");
return;
}
swap(a, idx.get(i), j);
}
}
out.println("NO");
}
private boolean isOk(int[] a, int i) {
boolean ordered = true;
if (i>0 && !(a[i-1] <= a[i])){
ordered = false;
}
if (i<a.length-1 && !(a[i]<=a[i+1])){
ordered = false;
}
return ordered;
}
private boolean isOk(int[] a, List<Integer> idx) {
for(int i : idx){
if (!isOk(a, i))
return false;
}
return true;
}
private void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
/////////////////////////////////////////////////
final int BUF_SIZE = 1024 * 1024 * 8;//important to read long-string tokens properly
final int INPUT_BUFFER_SIZE = 1024 * 1024 * 8 ;
final int BUF_SIZE_INPUT = 1024;
final int BUF_SIZE_OUT = 1024;
boolean inputFromFile = false;
String filenamePrefix = "A-small-attempt0";
String inSuffix = ".in";
String outSuffix = ".out";
//InputStream bis;
//OutputStream bos;
PrintStream out;
ByteScanner scanner;
ByteWriter writer;
// @Override
public void run() {
try{
InputStream bis = null;
OutputStream bos = null;
//PrintStream out = null;
if (inputFromFile){
File baseFile = new File(getClass().getResource("/").getFile());
bis = new BufferedInputStream(
new FileInputStream(new File(
baseFile, filenamePrefix+inSuffix)),
INPUT_BUFFER_SIZE);
bos = new BufferedOutputStream(
new FileOutputStream(
new File(baseFile, filenamePrefix+outSuffix)));
out = new PrintStream(bos);
}else{
bis = new BufferedInputStream(System.in, INPUT_BUFFER_SIZE);
bos = new BufferedOutputStream(System.out);
out = new PrintStream(bos);
}
scanner = new ByteScanner(bis, BUF_SIZE_INPUT, BUF_SIZE);
writer = new ByteWriter(bos, BUF_SIZE_OUT);
solve();
out.flush();
}catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public interface Constants{
final static byte ZERO = '0';//48 or 0x30
final static byte NINE = '9';
final static byte SPACEBAR = ' '; //32 or 0x20
final static byte MINUS = '-'; //45 or 0x2d
final static char FLOAT_POINT = '.';
}
public static class EofException extends IOException{
}
public static class ByteWriter implements Constants {
int bufSize = 1024;
byte[] byteBuf = new byte[bufSize];
OutputStream os;
public ByteWriter(OutputStream os, int bufSize){
this.os = os;
this.bufSize = bufSize;
}
public void writeInt(int num) throws IOException{
int byteWriteOffset = byteBuf.length;
if (num==0){
byteBuf[--byteWriteOffset] = ZERO;
}else{
int numAbs = Math.abs(num);
while (numAbs>0){
byteBuf[--byteWriteOffset] = (byte)((numAbs % 10) + ZERO);
numAbs /= 10;
}
if (num<0)
byteBuf[--byteWriteOffset] = MINUS;
}
os.write(byteBuf, byteWriteOffset, byteBuf.length - byteWriteOffset);
}
/**
* Please ensure ar.length <= byteBuf.length!
*
* @param ar
* @throws IOException
*/
public void writeByteAr(byte[] ar) throws IOException{
for (int i = 0; i < ar.length; i++) {
byteBuf[i] = ar[i];
}
os.write(byteBuf,0,ar.length);
}
public void writeSpaceBar() throws IOException{
byteBuf[0] = SPACEBAR;
os.write(byteBuf,0,1);
}
}
public static class ByteScanner implements Constants{
InputStream is;
public ByteScanner(InputStream is, int bufSizeInput, int bufSize){
this.is = is;
this.bufSizeInput = bufSizeInput;
this.bufSize = bufSize;
byteBufInput = new byte[this.bufSizeInput];
byteBuf = new byte[this.bufSize];
}
public ByteScanner(byte[] data){
byteBufInput = data;
bufSizeInput = data.length;
bufSize = data.length;
byteBuf = new byte[bufSize];
byteRead = data.length;
bytePos = 0;
}
private int bufSizeInput;
private int bufSize;
byte[] byteBufInput;
byte by=-1;
int byteRead=-1;
int bytePos=-1;
byte[] byteBuf;
int totalBytes;
boolean eofMet = false;
private byte nextByte() throws IOException{
if (bytePos<0 || bytePos>=byteRead){
byteRead = is==null? -1: is.read(byteBufInput);
bytePos=0;
if (byteRead<0){
byteBufInput[bytePos]=-1;//!!!
if (eofMet)
throw new EofException();
eofMet = true;
}
}
return byteBufInput[bytePos++];
}
/**
* Returns next meaningful character as a byte.<br>
*
* @return
* @throws IOException
*/
public byte nextChar() throws IOException{
while ((by=nextByte())<=0x20);
return by;
}
/**
* Returns next meaningful character OR space as a byte.<br>
*
* @return
* @throws IOException
*/
public byte nextCharOrSpacebar() throws IOException{
while ((by=nextByte())<0x20);
return by;
}
/**
* Reads line.
*
* @return
* @throws IOException
*/
public String nextLine() throws IOException {
readToken((byte)0x20);
return new String(byteBuf,0,totalBytes);
}
public byte[] nextLineAsArray() throws IOException {
readToken((byte)0x20);
byte[] out = new byte[totalBytes];
System.arraycopy(byteBuf, 0, out, 0, totalBytes);
return out;
}
/**
* Reads token. Spacebar is separator char.
*
* @return
* @throws IOException
*/
public String nextToken() throws IOException {
readToken((byte)0x21);
return new String(byteBuf,0,totalBytes);
}
/**
* Spacebar is included as separator char
*
* @throws IOException
*/
private void readToken() throws IOException {
readToken((byte)0x21);
}
private void readToken(byte acceptFrom) throws IOException {
totalBytes = 0;
while ((by=nextByte())<acceptFrom);
byteBuf[totalBytes++] = by;
while ((by=nextByte())>=acceptFrom){
byteBuf[totalBytes++] = by;
}
}
public int nextInt() throws IOException{
readToken();
int num=0, i=0;
boolean sign=false;
if (byteBuf[i]==MINUS){
sign = true;
i++;
}
for (; i<totalBytes; i++){
num*=10;
num+=byteBuf[i]-ZERO;
}
return sign?-num:num;
}
public long nextLong() throws IOException{
readToken();
long num=0;
int i=0;
boolean sign=false;
if (byteBuf[i]==MINUS){
sign = true;
i++;
}
for (; i<totalBytes; i++){
num*=10;
num+=byteBuf[i]-ZERO;
}
return sign?-num:num;
}
/*
//TODO test Unix/Windows formats
public void toNextLine() throws IOException{
while ((ch=nextChar())!='\n');
}
*/
public double nextDouble() throws IOException{
readToken();
char[] token = new char[totalBytes];
for (int i = 0; i < totalBytes; i++) {
token[i] = (char)byteBuf[i];
}
return Double.parseDouble(new String(token));
}
}
public static void main(String[] args) {
new Codeforces_R136_Div1_A().run();
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ZYCSwing
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
private static final int MOD = (int) 1e9 + 7;
private static final int N = 5000;
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int[] dp = new int[N];
Arrays.fill(dp, 0);
dp[0] = 1;
String pre = null, ch;
for (int i = 0; i < n; ++i) {
ch = in.next();
if (i > 0) {
if (pre.equals("s")) {
int j = N - 1;
while (dp[j] == 0) {
--j;
}
long sum = 0;
for (; j >= 0; --j) {
sum += dp[j];
sum %= MOD;
dp[j] = (int) sum;
}
} else {
for (int k = N - 1; k > 0; --k) {
dp[k] = dp[k - 1];
}
dp[0] = 0;
}
}
pre = ch;
}
long sum = 0;
for (int i = 0; i < N; ++i) {
sum += dp[i];
sum %= MOD;
}
out.println(sum);
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.OutputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Alex
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
double special(int[] loyalties, int[] levels, int playerlevelsum) {
int poss = 1 << loyalties.length;
double res = 0;
for(int pos = 0; pos < poss; pos++) {
double occurs = 1;
int happy = 0;
int badlevelssum = 0;
for(int i = 0; i < loyalties.length; i++) {
if(((pos >> i) & 1) == 1) { //happy senator
happy++;
occurs *= (double) loyalties[i] / 100;
} else { //unhappy senator
badlevelssum += levels[i];
occurs *= (double) (100 - loyalties[i]) / 100;
}
}
double winprob = (happy <= levels.length / 2) ? (double) playerlevelsum / (playerlevelsum + badlevelssum) : 1;
res += occurs * winprob;
}
return res;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int senators = in.readInt(); // n, [1, 8]
int sweets = in.readInt(); // k, [1, 8]
int playerlevelsum = in.readInt(); // A, [1, 9999]
int[] levels = new int[senators]; // [1, 9999]
int[] loyalties = new int[senators]; // [0, 100] divisible by 10
IOUtils.readIntArrays(in, levels, loyalties);
ArrayList<ArrayList<Integer>> possibilities = new ArrayList<>(Arrays.asList(new ArrayList<>()));
for(int senator = 0; senator < senators; senator++) {
ArrayList<ArrayList<Integer>> newpossibilities = new ArrayList<>();
for(ArrayList<Integer> al : possibilities) {
int sumsofar = 0;
for(int val : al) sumsofar += val;
int minadd = senator == senators - 1 ? sweets - sumsofar : 0;
for(int moar = minadd; moar <= sweets - sumsofar; moar++) {
ArrayList<Integer> copy = new ArrayList<>(al);
copy.add(moar);
newpossibilities.add(copy);
}
}
possibilities = newpossibilities;
}
double res = 0;
for(ArrayList<Integer> al : possibilities) {
int[] newloyalties = new int[senators];
for(int i = 0; i < senators; i++) newloyalties[i] = Math.min(100, loyalties[i] + 10 * al.get(i));
double special = special(newloyalties, levels, playerlevelsum);
double tot = special;
res = Math.max(res, tot);
}
out.printLine(res);
}
}
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 int readInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if(c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while(!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if(filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void 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();
}
}
static class IOUtils {
public static void readIntArrays(InputReader in, int[]... arrays) {
for(int i = 0; i < arrays[0].length; i++) {
for(int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readInt();
}
}
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
public class A {
public static void main(String[] args) {
JS in = new JS();
int n = in.nextInt();
int m1 = 0;
int s1 = 0;
int l1 = 0;
int ss1 = 0;
int sss1 = 0;
int ssss1 = 0;
int ll1 = 0;
int lll1 = 0;
int llll1 = 0;
int m2 = 0;
int s2 = 0;
int l2 = 0;
int ss2 = 0;
int sss2 = 0;
int ssss2 = 0;
int ll2 = 0;
int lll2 = 0;
int llll2 = 0;
for(int i = 0; i < n; i++) {
String s = in.next();
if(s.equals("S")) s1++;
else if(s.equals("M"))m1++;
else if(s.equals("L"))l1++;
else if(s.equals("XS")) ss1++;
else if(s.equals("XXS")) sss1++;
else if(s.equals("XXXS")) ssss1++;
else if(s.equals("XL")) ll1++;
else if(s.equals("XXL")) lll1++;
else if(s.equals("XXXL")) llll1++;
}
for(int i = 0; i < n; i++) {
String s = in.next();
if(s.equals("S")) s2++;
else if(s.equals("M"))m2++;
else if(s.equals("L"))l2++;
else if(s.equals("XS")) ss2++;
else if(s.equals("XXS")) sss2++;
else if(s.equals("XXXS")) ssss2++;
else if(s.equals("XL")) ll2++;
else if(s.equals("XXL")) lll2++;
else if(s.equals("XXXL")) llll2++;
}
int res = 0;
int res1 = 0;
res1 += Math.abs(m2-m1);
res1 += Math.abs(s2-s1);
res1 += Math.abs(l2-l1);
res += res1/2;
res1 = 0;
res1 += Math.abs(ss2-ss1);
res1 += Math.abs(ll2-ll1);
res += res1/2;
res1 = 0;
res1 += Math.abs(sss2-sss1);
res1 += Math.abs(lll2-lll1);
res += res1/2;
res1 = 0;
res1 += Math.abs(ssss2-ssss1);
res1 += Math.abs(llll2-llll1);
res += res1/2;
res1 = 0;
System.out.println(res);
}
static class JS{
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public JS() {
in = new BufferedInputStream(System.in, BS);
}
public JS(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
/**
* Works good for CF
*
* @author cykeltillsalu
*/
public class A111_div2 {
// some local config
static boolean test = false;
static String testDataFile = "testdata.txt";
static String feedFile = "feed.txt";
CompetitionType type = CompetitionType.CF;
private static String ENDL = "\n";
// solution
private void solve() throws Throwable {
int n = iread();
int[] vals = new int[n];
double tot = 0;
for (int i = 0; i < n; i++) {
int value = iread();
vals[i] = value;
tot += value;
}
Arrays.sort(vals);
int pick = 0;
int worth = 0;
for (int i = vals.length - 1; i >= 0; i--) {
worth += vals[i];
pick ++;
if(worth > tot/2.0d){
break;
}
}
out.write(pick + ENDL);
out.flush();
}
public int iread() throws Exception {
return Integer.parseInt(wread());
}
public double dread() throws Exception {
return Double.parseDouble(wread());
}
public long lread() throws Exception {
return Long.parseLong(wread());
}
public String wread() throws IOException {
StringBuilder b = new StringBuilder();
int c;
c = in.read();
while (c >= 0 && c <= ' ')
c = in.read();
if (c < 0)
return "";
while (c > ' ') {
b.append((char) c);
c = in.read();
}
return b.toString();
}
public static void main(String[] args) throws Throwable {
if (test) { // run all cases from testfile:
BufferedReader testdataReader = new BufferedReader(new FileReader(testDataFile));
String readLine = testdataReader.readLine();
int casenr = 0;
out: while (true) {
BufferedWriter w = new BufferedWriter(new FileWriter(feedFile));
if (!readLine.equals("input")) {
break;
}
while (true) {
readLine = testdataReader.readLine();
if (readLine.equals("output")) {
break;
}
w.write(readLine + "\n");
}
w.close();
System.out.println("Answer on case " + (++casenr) + ": ");
new A111_div2().solve();
System.out.println("Expected answer: ");
while (true) {
readLine = testdataReader.readLine();
if (readLine == null) {
break out;
}
if (readLine.equals("input")) {
break;
}
System.out.println(readLine);
}
System.out.println("----------------");
}
testdataReader.close();
} else { // run on server
new A111_div2().solve();
}
out.close();
}
public A111_div2() throws Throwable {
if (test) {
in = new BufferedReader(new FileReader(new File(feedFile)));
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(inp);
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
enum CompetitionType {
CF, OTHER
};
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class ElongatedMatrix {
static int[][][] memo;
static int mn1[][];
static int mn2[][];
static int r, c;
static int dp(int mask, int first, int lastvisited) {
if (memo[first][lastvisited][mask] != -1)
return memo[first][lastvisited][mask];
int ans = 0;
for (int i = 0; i < r; i++) {
if ((mask & (1 << i)) == 0) {
if (Integer.bitCount(mask) != r - 1) {
ans = Math.max(ans, Math.min(mn1[lastvisited][i], dp(((mask) | (1 << i)), first, i)));
} else
ans = Math.max(ans, Math.min(mn2[first][i], mn1[lastvisited][i]));
}
}
//System.out.println(ans);
return memo[first][lastvisited][mask] = ans;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
PrintWriter out = new PrintWriter(System.out);
r = Integer.parseInt(st.nextToken());
c = Integer.parseInt(st.nextToken());
int[][] arr = new int[r][c];
memo = new int[r][r][1 << r];
mn1 = new int[r][r];
mn2 = new int[r][r];
for(int i=0;i<r;i++) {
st=new StringTokenizer(br.readLine());
for(int j=0;j<c;j++) {
arr[i][j]=Integer.parseInt(st.nextToken());
}
}
for (int i = 0; i < r; i++) {
Arrays.fill(mn1[i], (int)1e9);
Arrays.fill(mn2[i], (int)1e9);
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < r; j++) {
Arrays.fill(memo[i][j], -1);
}
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < r; j++) {
for (int k = 0; k < c; k++) {
mn1[i][j] = Math.min(mn1[i][j], Math.abs(arr[i][k] - arr[j][k]));
}
}
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < r; j++) {
for (int k = 0; k < c-1; k++) {
mn2[i][j] = Math.min(mn2[i][j], Math.abs(arr[j][k] - arr[i][k + 1]));
}
}
}
int ans = 0;
for (int i = 0; i < r; i++) {
ans=Math.max(ans, dp(1<<i,i,i));
}
if(r==1)
ans=mn2[0][0];
out.println(ans);
out.flush();
}
}
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
public class Village
{
static Scanner in = new Scanner( new BufferedReader( new InputStreamReader( System.in ) ) );
public static void main( String[] args )
{
int n = in.nextInt(), t = 2*in.nextInt(), h[][] = new int[n][2], ans = 2;
for( int i = 0; i < n; i++ )
{
h[i][0] = 2*in.nextInt();
h[i][1] = in.nextInt();
}
Arrays.sort( h, new Comp() );
for( int i = 1; i < n; i++ )
{
int d = (h[i][0]-h[i][1])-(h[i-1][0]+h[i-1][1]);
if( d > t ) ans += 2;
else if( d == t ) ans++;
}
System.out.println( ans );
}
static class Comp implements Comparator<int[]> { public int compare( int[] a, int[] b ) { return a[0]-b[0]; } }
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class ProblemA {
private void solve() throws IOException {
Scanner stdin = new Scanner(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = Integer.valueOf(stdin.nextInt());
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = stdin.nextInt();
}
Arrays.sort(p);
if (p[n-1] == 1) {
p[n-1] = 2;
} else {
p[n-1] = 1;
out.print(p[n-1] + " ");
n--;
}
for (int i = 0; i < n; i++) {
out.print(p[i] + " ");
}
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
ProblemA solver = new ProblemA();
solver.solve();
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
static final long MOD = 998244353;
//static final long MOD = 1000000007;
static boolean[] visited;
public static void main(String[] args) throws IOException {
FastScanner sc = new FastScanner();
int Q = sc.nextInt();
for (int q = 0; q < Q; q++) {
int N = sc.nextInt();
int M = sc.nextInt();
int[][] grid = new int[N][M];
int[][] maxes = new int[M][2];
for (int i = 0; i < M; i++)
maxes[i][1] = i;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
grid[i][j] = sc.nextInt();
maxes[j][0] = Math.max(maxes[j][0],grid[i][j]);
}
}
maxes = sort(maxes);
int[] keyCols = new int[Math.min(M, N)];
for (int i = 0; i < keyCols.length; i++)
keyCols[i] = maxes[i][1];
int ans = 0;
for (int x = 0; x < (int)Math.pow(N,N); x++) {
int[] base = baseN(keyCols.length,x);
int ansx = 0;
for (int i = 0; i < N; i++) {
int r = 0;
for (int j = 0; j < keyCols.length; j++) {
r = Math.max(r,grid[(i+base[j])%N][keyCols[j]]);
}
ansx += r;
}
ans = Math.max(ans,ansx);
}
System.out.println(ans);
}
}
public static int[] baseN(int N, int num) {
int[] ans = new int[N];
for (int i = N-1; i >= 0; i--) {
int pow = (int)Math.pow(N,i);
ans[i] = num/pow;
num -= ans[i]*pow;
}
return ans;
}
public static int[][] sort(int[][] array) {
//Sort an array (immune to quicksort TLE)
Random rgen = new Random();
for (int i = 0; i< array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
int[] temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
Arrays.sort(array, new Comparator<int[]>() {
@Override
public int compare(int[] arr1, int[] arr2) {
//Descending order
return arr2[0]-arr1[0];
}
});
return array;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
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;
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
private static int[] a;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
a = new int[101];
for (int i = 0; i < m; i++) {
int type = sc.nextInt();
a[type] = a[type] + 1;
}
int lo=1, hi=100, max=0;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (check(n, mid)) {
max = mid;
lo = mid+1;
} else {
hi = mid -1;
}
}
System.out.println(max);
}
public static boolean check(int n, int target) {
int result = 0;
for (int i=0; i <a.length; i++) {
result = result + (a[i] / target);
}
if (result >= n) {return true;}
return false;
}
}
|
nlogn
|
1011_B. Planning The Expedition
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RoundOneProblemB {
/**
* @param args
*/
public static void main(String[] args) {
int n=1;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in), 50);
try {
n = Integer.valueOf(input.readLine());
if (! ((1 <= n) && (n <= Math.pow(10, 5)))) {
formatError();
}
Pattern typeOne = Pattern.compile("^([A-Z]+)([0-9]+)$");
Pattern typeTwo = Pattern.compile("^R([0-9]+)C([0-9]+)$");
for (int i=0; i < n; i++) {
String line = input.readLine();
Matcher matchOne = typeOne.matcher(line);
if (matchOne.find()) {
System.out.println(convertOneToTwo(matchOne.group(2), matchOne.group(1)));
} else {
Matcher matchTwo = typeTwo.matcher(line);
if (matchTwo.find()) {
System.out.println(convertTwoToOne(matchTwo.group(1), matchTwo.group(2)));
}
}
}
} catch (Exception e) {
formatError();
}
}
private static String convertTwoToOne(String row, String col) {
StringBuilder result = new StringBuilder();
long c = Long.parseLong(col);
while ( c > 0) {
result.append((char)(((c-1) % 26)+'A'));
c = (c-1) / 26;
}
result.reverse();
result.append(Long.parseLong(row));
return result.toString();
}
private static String convertOneToTwo(String row, String col) {
StringBuilder result = new StringBuilder();
int l = col.length();
col = col.toUpperCase();
long base = 1;
long c = 0;
for (int i=l-1; i >= 0; i--) {
c = c + ((col.charAt(i) - 'A' + 1) * base);
base = base * 26;
}
result.append("R").append(Long.parseLong(row)).append("C").append(c);
return result.toString();
}
/**
* Exit with an error due to unexpected standard input.
*/
private static void formatError() {
System.out.println("Unexpected input");
System.exit(1);
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
/**
* @(#)DigitSequence.java
*
*
* @author
* @version 1.00 2019/6/1
*/
import java.io.*;
import java.util.*;
public class DigitSequence {
/**
* Creates a new instance of <code>DigitSequence</code>.
*/
public DigitSequence() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
long k=in.nextLong();
long[] end=new long[12];
end[0]=-1;
for (int i=1; i<end.length; i++) {
end[i]=(i*(long)(Math.pow(10,i)));
end[i]-=(((long)(Math.pow(10,i))-1)/9);
}
//System.out.println(Arrays.toString(end));
int st=0;//st=1 {0,9}; st=2 {10, 189}; st=3 {190-2889}; st=4 {2890-38889}
for (int i=1; i<end.length; i++) {
if (k>=end[i-1]+1 && k<=end[i]) st=i;
}
//System.out.println("st " + st);
long diff=k-end[st-1];
long mod=((diff+st-1)%st);
//System.out.println(mod);
long digit=-1;
int addOn=0;
if (mod==0) addOn=1;
if (mod==st-1) addOn=-1;
digit=(diff/(st*(long)(Math.pow(10,st-1-mod))));
digit+=addOn;
digit%=10;
System.out.println(digit);
//98888888889
//98888888879
//1088888888889
//1088888888878
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.math.*;
import java.util.*;
import java.io.*;
public class Main{
static StreamTokenizer in=new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
static Scanner sc=new Scanner(System.in);
static PrintWriter out=new PrintWriter(System.out);
//static InputReader sc=new InputReader(System.in);
static final int inf=10000000;
public static void main(String args[])throws Exception {
double n,k;
n=sc.nextDouble();
k=sc.nextDouble();
double ans=0;
ans=Math.sqrt(2.25+2*(n+k))-1.5;
System.out.printf("%.0f\n",n-ans);
}
static void ssort(int arr[]){
int len=arr.length;
for(int i=0;i<len;i++){
int t=(int)(len*Math.random());
int temp=arr[t];
arr[t]=arr[i];
arr[i]=temp;
}
Arrays.sort(arr);
}
static int getInt()throws Exception{
in.nextToken();
return (int)in.nval;
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
/*
*/
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class D11 {
static StreamTokenizer in;
static PrintWriter out;
static int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
static String nextString() throws IOException {
in.nextToken();
return in.sval;
}
public static void main(String[] args) throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
n = nextInt();
m = nextInt();
g = new boolean[n][n];
for (int i = 0; i < m; i++) {
int a = nextInt()-1, b = nextInt()-1;
g[a][b] = g[b][a] = true;
}
long ans = 0;
for (int i = n-1; i >= 0; i--) {
long cur = solve(i);
ans += cur;
}
out.println(ans/2);
out.flush();
}
static int n, m;
static boolean[][] g;
static long solve(int v) {
long[][] memo = new long[v][1 << v];
for (int i = 0; i < v; i++)
if (g[v][i])
memo[i][1 << i] = 1;
for (int mask = 1; mask < (1 << v); mask++)
for (int i = 0; i < v; i++) if ((mask&(1 << i)) != 0)
for (int j = 0; j < v; j++) if (g[i][j] && (mask&(1 << j)) == 0)
memo[j][mask|(1 << j)] += memo[i][mask];
long res = 0;
for (int mask = 1; mask < (1 << v); mask++)
for (int i = 0; i < v; i++)
if (Integer.bitCount(mask) > 1 && g[v][i]) res += memo[i][mask];
return res;
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
// main
public static void main(String [] args) throws IOException {
// makes the reader and writer
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
// read in N
int N = Integer.parseInt(f.readLine());
// write to out
if (N%2==0) out.println("4 "+(N-4));
if (N%2==1) out.println("9 "+(N-9));
// cleanup
out.close();
System.exit(0);
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
/**
* Created by IntelliJ IDEA.
* User: Михаил
* Date: 25.03.12
* Time: 19:03
* To change this template use File | Settings | File Templates.
*/
public class ProblemOne {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
int problemCount = scanner.nextInt();
int petrCount = scanner.nextInt();
int vasCount = scanner.nextInt();
int [] problems = new int[problemCount];
for (int i = 0; i < problemCount; i++) {
problems[i] = scanner.nextInt();
}
Arrays.sort(problems);
System.out.println(-problems[vasCount - 1] + problems[vasCount]);
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.InputMismatchException;
/**
* @author Egor Kulikov (egor@egork.net)
* Created on 14.03.2010
*/
public class TaskA implements Runnable {
private InputReader in;
private PrintWriter out;
public static void main(String[] args) {
new Thread(new TaskA()).start();
// new Template().run();
}
public TaskA() {
// String id = getClass().getName().toLowerCase();
// try {
// System.setIn(new FileInputStream(id + ".in"));
// System.setOut(new PrintStream(new FileOutputStream(id + ".out")));
// System.setIn(new FileInputStream("input.txt"));
// System.setOut(new PrintStream(new FileOutputStream("output.txt")));
// } catch (FileNotFoundException e) {
// throw new RuntimeException();
// }
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
public void run() {
// int numTests = in.readInt();
// for (int testNumber = 0; testNumber < numTests; testNumber++) {
// }
int n = in.readInt();
int k = in.readInt();
int last = 2;
for (int i = 3; i + last < n; i++) {
boolean good = true;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
good = false;
break;
}
}
if (good) {
int p = i + last + 1;
for (int j = 2; j * j <= p; j++) {
if (p % j == 0) {
good = false;
break;
}
}
if (good)
k--;
last = i;
}
}
if (k <= 0)
out.println("YES");
else
out.println("NO");
out.close();
}
private static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1000];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.lang.*;
public class Third{
static long mod=1000000007;
public static void main(String[] args) throws Exception{
InputReader in = new InputReader(System.in);
PrintWriter pw=new PrintWriter(System.out);
//int t=in.readInt();
//while(t-->0)
//{
int n=in.readInt();
//long n=in.readLong();
/*int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=in.readInt();
}*/
String a=in.readString();
char c[]=a.toCharArray();
HashSet<Character>ht=new HashSet<Character>();
Deque<Character>q=new LinkedList<Character>();
HashSet<Character>hs=new HashSet<Character>();
HashMap<Character,Integer>hm=new HashMap<Character,Integer>();
for(int i=0;i<n;i++)
{
ht.add(c[i]);
}
int t=ht.size();
q.addLast(c[0]);
hs.add(c[0]);
hm.put(c[0],1);
int ans=Integer.MAX_VALUE;
if(hs.size()==t)
{
ans=min(ans,q.size());
}
for(int i=1;i<n;i++)
{
q.addLast(c[i]);
hs.add(c[i]);
if(hm.containsKey(c[i]))
{
int x=hm.get(c[i]);
hm.put(c[i],x+1);
}
else
hm.put(c[i],1);
while(hs.size()==t)
{
ans=min(ans,q.size());
char ch=q.peekFirst();
int x=hm.get(ch);
if(x==1)
break;
else
{
hm.put(ch, x-1);
q.pollFirst();
}
}
}
pw.println(ans);
//}
pw.close();
}
public static long gcd(long x,long y)
{
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y)
{
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int abs(int a,int b)
{
return (int)Math.abs(a-b);
}
public static long abs(long a,long b)
{
return (long)Math.abs(a-b);
}
public static int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b)
{
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b)
{
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b)
{
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static class Pair implements Comparable<Pair>
{
int a,b;
Pair (int a,int b)
{
this.a=a;
this.b=b;
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if(this.a!=o.a)
return Integer.compare(this.a,o.a);
else
return Integer.compare(this.b, o.b);
//return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.a == a && p.b == b;
}
return false;
}
public int hashCode() {
return new Integer(a).hashCode() * 31 + new Integer(b).hashCode();
}
}
static long sort(int a[])
{ int n=a.length;
int b[]=new int[n];
return mergeSort(a,b,0,n-1);}
static long mergeSort(int a[],int b[],long left,long right)
{ long c=0;if(left<right)
{ long mid=left+(right-left)/2;
c= mergeSort(a,b,left,mid);
c+=mergeSort(a,b,mid+1,right);
c+=merge(a,b,left,mid+1,right); }
return c; }
static long merge(int a[],int b[],long left,long mid,long right)
{long c=0;int i=(int)left;int j=(int)mid; int k=(int)left;
while(i<=(int)mid-1&&j<=(int)right)
{ if(a[i]<=a[j]) {b[k++]=a[i++]; }
else { b[k++]=a[j++];c+=mid-i;}}
while (i <= (int)mid - 1) b[k++] = a[i++];
while (j <= (int)right) b[k++] = a[j++];
for (i=(int)left; i <= (int)right; i++)
a[i] = b[i]; return c; }
public static int[] radixSort(int[] f)
{
int[] to = new int[f.length];
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
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 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 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 double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public 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 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);
}
}
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//StringBuilder sb=new StringBuilder("");
//InputReader in = new InputReader(System.in);
//PrintWriter pw=new PrintWriter(System.out);
//String line=br.readLine().trim();
//int t=Integer.parseInt(br.readLine());
// while(t-->0)
//{
//int n=Integer.parseInt(br.readLine());
//long n=Long.parseLong(br.readLine());
//String l[]=br.readLine().split(" ");
//int m=Integer.parseInt(l[0]);
//int k=Integer.parseInt(l[1]);
//String l[]=br.readLine().split(" ");
//l=br.readLine().split(" ");
/*int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(l[i]);
}*/
//System.out.println(" ");
//}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class tr {
static int[][] ad;
static boolean []vis;
static int []goods;
static int[][]sol;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt();
int []a=new int [n];
int max=0;
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
Stack<Integer> s=new Stack<>();
boolean f=true;
for(int i=0;i<n;i++) {
max=Math.max(max,a[i]);
if(!s.isEmpty() && a[i]>s.peek())
f=false;
s.push(a[i]);
while(!s.isEmpty()) {
int high=s.pop();
if(s.isEmpty() || s.peek()!=high) {
s.push(high);
break;
}
s.pop();
}
// System.out.println(s+" "+max);
}
//System.out.println(f+" "+max);
if(f && s.size()==0)
out.println("YES");
else if(f && s.size()==1 && s.peek()==max)
out.println("YES");
else
out.println("NO");
out.flush();
}
static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
static class pair implements Comparable<pair> {
int a;
int b;
pair(int a, int b) {
this.a = a;
this.b = b;
}
public String toString() {
return a + " " + b;
}
@Override
public int compareTo(pair o) {
return o.a-a ;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
|
linear
|
1092_D1. Great Vova Wall (Version 1)
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
static int mod = (int) 1e9 + 7;
public static void main(String[] args) throws FileNotFoundException {
FasterScanner s = new FasterScanner();
int test = 1;
testloop: while (test-- > 0) {
int n = s.nextInt();
int left = 1;
int right = n;
int x[][] = new int[2][2];
int y[][] = new int[2][2];
while (left < right) {
int mid = (left + right) / 2;
query(1, mid, 1, n);
int ans = s.nextInt();
if (ans < 2) {
left = mid + 1;
} else {
right = mid;
}
}
x[0][0] = left;
left = 1;
right = n;
while (left < right) {
int mid = (left + right) / 2;
query(1, mid, 1, n);
int ans = s.nextInt();
if (ans < 1) {
left = mid + 1;
} else {
right = mid;
}
}
x[0][1] = left;
left = 1;
right = n;
while (left < right) {
int mid = (left + right + 1) / 2;
query(mid, n, 1, n);
int ans = s.nextInt();
if (ans < 2) {
right = mid - 1;
} else {
left = mid;
}
}
x[1][0] = left;
left = 1;
right = n;
while (left < right) {
int mid = (left + right + 1) / 2;
query(mid, n, 1, n);
int ans = s.nextInt();
if (ans < 1) {
right = mid - 1;
} else {
left = mid;
}
}
x[1][1] = left;
// System.out.println(Arrays.deepToString(x));
left = 1;
right = n;
while (left < right) {
int mid = (left + right) / 2;
query(1, n, 1, mid);
int ans = s.nextInt();
if (ans < 2) {
left = mid + 1;
} else {
right = mid;
}
}
y[0][0] = left;
left = 1;
right = n;
while (left < right) {
int mid = (left + right) / 2;
query(1, n, 1, mid);
int ans = s.nextInt();
if (ans < 1) {
left = mid + 1;
} else {
right = mid;
}
}
y[0][1] = left;
left = 1;
right = n;
while (left < right) {
int mid = (left + right + 1) / 2;
query(1, n, mid, n);
int ans = s.nextInt();
if (ans < 2) {
right = mid - 1;
} else {
left = mid;
}
}
y[1][0] = left;
left = 1;
right = n;
while (left < right) {
int mid = (left + right + 1) / 2;
query(1, n, mid, n);
int ans = s.nextInt();
if (ans < 1) {
right = mid - 1;
} else {
left = mid;
}
}
y[1][1] = left;
// System.out.println(Arrays.deepToString(x));
// System.out.println(Arrays.deepToString(y));
int x11 = 0, x12 = 0, y11 = 0, y12 = 0;
int x21 = 0, x22 = 0, y21 = 0, y22 = 0;
for (int x1 = 0; x1 < 2; x1++) {
x11 = x[1][x1];
x21 = x[1][1 - x1];
for (int x2 = 0; x2 < 2; x2++) {
x12 = x[0][x2];
x22 = x[0][1 - x2];
if (x11 > x12)
continue;
if (x21 > x22)
continue;
for (int y1 = 0; y1 < 2; y1++) {
y11 = y[1][y1];
y21 = y[1][1 - y1];
for (int y2 = 0; y2 < 2; y2++) {
y12 = y[0][y2];
y22 = y[0][1 - y2];
if (y11 > y12)
continue;
if (y21 > y22)
continue;
query(x11, x12, y11, y12);
int ans1 = s.nextInt();
query(x21, x22, y21, y22);
int ans2 = s.nextInt();
if (ans1 == 1 && ans2 == 1) {
System.out.println("! " + x11 + " " + y11 + " " + x12 + " " + y12 + " " + x21 + " "
+ y21 + " " + x22 + " " + y22);
System.out.flush();
break testloop;
}
}
}
}
}
}
}
public static void query(int x1, int x2, int y1, int y2) {
System.out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
System.out.flush();
// int count = 0;
// if (x1 <= 2 && y1 <= 2 && x2 >= 2 && y2 >= 2)
// count++;
//
// if (x1 <= 3 && y1 <= 4 && x2 >= 3 && y2 >= 5)
// count++;
// System.out.println(count);
}
public static void set(int[] t, int i, int value) {
i += t.length / 2;
t[i] = value;
for (; i > 1; i >>= 1)
t[i >> 1] = Math.max(t[i], t[i ^ 1]);
}
// max[a, b]
public static int max(int[] t, int a, int b) {
int res = 0;
for (a += t.length / 2, b += t.length / 2; a <= b; a = (a + 1) >> 1, b = (b - 1) >> 1) {
if ((a & 1) != 0)
res = Math.max(res, t[a]);
if ((b & 1) == 0)
res = Math.max(res, t[b]);
}
return res;
}
public static int[] generateDivisorTable(int n) {
int[] divisor = new int[n + 1];
for (int i = 1; i <= n; i++)
divisor[i] = i;
for (int i = 2; i * i <= n; i++)
if (divisor[i] == i)
for (int j = i * i; j <= n; j += i)
if (divisor[j] == j)
divisor[j] = i;
return divisor;
}
public static long pow(long x, long n, long mod) {
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) {
if ((n & 1) != 0) {
res = (res * p % mod);
}
}
return res;
}
static long gcd(long n1, long n2) {
long r;
while (n2 != 0) {
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class Main {
private PrintWriter out;
private Map<Integer, Integer> map;
private int arr[], ans[];
int n, a, b;
class DSU {
private int[] p, size;
public DSU(int n) {
p = new int[n];
size = new int[n];
for (int i=0; i<n; i++) {
p[i] = i;
size[i] = 1;
}
}
public int find(int i) {
if (p[i] == i) {
return i;
}
return p[i] = find(p[i]);
}
public void union (int a, int b) {
a = find(a); b = find(b);
if (size[a] > size[b]) {
p[b] = a;
size[a] += size[b];
} else {
p[a] = b;
size[b] += size[a];
}
}
}
private void solve() throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(in.readLine());
n = Integer.valueOf(st.nextToken());
a = Integer.valueOf(st.nextToken());
b = Integer.valueOf(st.nextToken());
map = new HashMap<Integer, Integer>(n);
String line = in.readLine();
StringTokenizer st1 = new StringTokenizer(line);
arr = new int[n];
ans = new int[n];
DSU dsu = new DSU(n);
for (int i=0; i<n; i++) {
arr[i] = Integer.valueOf(st1.nextToken());
map.put(arr[i], i);
}
in.close();
for (int i=0; i<n; i++) {
boolean f = false;
if (map.get(a - arr[i]) != null) {
f = true;
dsu.union(i, map.get(a - arr[i]));
}
if (map.get(b - arr[i]) != null) {
f = true;
dsu.union(i, map.get(b - arr[i]));
}
if (!f) {
out.println("NO");
out.flush();
return;
}
}
for (int i=0; i<n; i++) {
int p = dsu.find(i);
if (map.get(a - arr[i]) == null) {
ans[p] = 1;
} else if (map.get(b - arr[i]) == null) {
ans[p] = 0;
}
}
for (int i=0; i<n; i++) {
int p = dsu.find(i);
if (ans[p] == 0 && map.get(a - arr[i]) == null) {
out.println("NO");
out.flush();
return;
}
if (ans[p] == 1 && map.get(b - arr[i]) == null) {
out.println("NO");
out.flush();
return;
}
}
out.println("YES");
for (int i=0; i<n; i++) {
out.print(ans[dsu.find(i)] + " ");
}
out.flush();
out.close();
}
public static void main(String[] args) throws Exception {
new Main().solve();
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class C {
MyScanner in;
PrintWriter out;
public static void main(String[] args) throws Exception {
new C().run();
}
public void run() throws Exception {
in = new MyScanner();
out = new PrintWriter(System.out);
solve();
out.close();
}
public void solve() throws Exception {
int n = in.nextInt();
char[] a = in.next().toCharArray();
int h = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == 'H') h++;
}
char[] b = new char[2 * a.length - 1];
for (int i = 0; i < b.length; i++) {
b[i] = a[i % a.length];
}
int maxh = 0;
int hh = 0;
for (int i = 0; i < b.length - h; i++) {
hh = 0;
for (int j = 0; j < h; j++) {
if (b[i + j] == 'H') hh++;
}
maxh = Math.max(maxh, hh);
}
/*for (int i = 0; i < b.length; i++) {
out.print(b[i]);
}
out.println();*/
//out.println(h + " " + maxh);
out.println(h - maxh);
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws Exception {
if ((st == null) || (!st.hasMoreTokens())) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(next());
}
double nextDouble() throws Exception {
return Double.parseDouble(next());
}
boolean nextBoolean() throws Exception {
return Boolean.parseBoolean(next());
}
long nextLong() throws Exception {
return Long.parseLong(next());
}
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.util.*;
public class Village {
private class House implements Comparable<House>{
Double Coordinate;
Double Sidelength;
public House(double coordinate, double sidelength) {
Coordinate = coordinate;
Sidelength = sidelength;
}
public int compareTo(House o) {
return Coordinate.compareTo(o.Coordinate);
}
}
public static void main(String args[]) {
Village v = new Village();
v.solve();
}
public void solve() {
Scanner in = new Scanner(System.in);
int numhouse = in.nextInt();
double requireside = in.nextDouble();
//System.out.println(numhouse);
//System.out.println(requireside);
ArrayList<House> coordinate = new ArrayList<House>();
ArrayList<Double> sidelength = new ArrayList<Double>();
while (in.hasNext()) {
double coo = in.nextDouble();
double side = in.nextDouble();
//System.out.println(coo);
//System.out.println(side);
coordinate.add(new House(coo,side));
sidelength.add(side);
}
Collections.sort(coordinate);
ArrayList<Double> edges = new ArrayList<Double>();
int count = 2;
for (int i = 0; i < coordinate.size();i++) {
edges.add(coordinate.get(i).Coordinate - (double)coordinate.get(i).Sidelength/(double)2);
edges.add(coordinate.get(i).Coordinate + (double)coordinate.get(i).Sidelength/(double)2);
}
ArrayList<Double> difference = new ArrayList<Double>();
for (int i = 1; i < edges.size() - 1; i++) {
difference.add(Math.abs(edges.get(i) - edges.get(i+1)));
}
for (int i = 0; i < difference.size(); i+=2) {
if (difference.get(i) == requireside) count++;
else if (difference.get(i) > requireside) count+=2;
}
System.out.println(count);
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
public class SolutionD {
BufferedReader in;
StringTokenizer str;
PrintWriter out;
String SK;
String next() throws IOException {
while ((str == null) || (!str.hasMoreTokens())) {
SK = in.readLine();
if (SK == null)
return null;
str = new StringTokenizer(SK);
}
return str.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
//in = new BufferedReader(new FileReader("input.txt"));
//out = new PrintWriter("output.txt");
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new SolutionD().run();
}
void solve() throws IOException {
long l=Long.parseLong(next());
long r=Long.parseLong(next());
String low=Long.toBinaryString(l);
String up=Long.toBinaryString(r);
int n=low.length();
int m=up.length();
for(int i=0;i<m-n;i++){
low="0"+low;
}
String ret="";
boolean fu=false;
boolean fd=false;
boolean su=false;
boolean sd=false;
if(m>n){
su=true;
fd=true;
}
for(int i=0;i<m;i++){
if(low.charAt(i)==up.charAt(i)){
if(low.charAt(i)=='1'){
if(fd){
ret+="1";
fu=true;
}
else if(sd){
ret+="1";
su=true;
}
else ret+="0";
}
else{
if(fu){
ret+="1";
fd=true;
}
else if(su){
ret+="1";
sd=true;
}
else ret+="0";
}
}else{
if(up.charAt(i)=='1'){
su=true;
fd=true;
}
ret+="1";
}
}
out.println(Long.parseLong(ret, 2));
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class A implements Runnable {
public void run() {
long startTime = System.nanoTime();
int n = nextInt();
String[] all = new String[9];
all[0] = "M";
for (int i = 0; i < 4; i++) {
String s = "";
for (int j = 0; j < i; j++) {
s += "X";
}
all[2 * i + 1] = s + "S";
all[2 * i + 2] = s + "L";
}
Map<String, Integer> map1 = new HashMap<>();
Map<String, Integer> map2 = new HashMap<>();
for (String s : all) {
map1.put(s, 0);
map2.put(s, 0);
}
for (int i = 0; i < n; i++) {
String s = nextToken();
map1.put(s, map1.get(s) + 1);
}
for (int i = 0; i < n; i++) {
String s = nextToken();
map2.put(s, map2.get(s) + 1);
}
int res = 0;
for (String s : all) {
int a = map1.get(s);
int b = map2.get(s);
if (a > b) {
res += a - b;
}
}
println(res);
if (fileIOMode) {
System.out.println((System.nanoTime() - startTime) / 1e9);
}
out.close();
}
//-----------------------------------------------------------------------------------
private static boolean fileIOMode;
private static BufferedReader in;
private static PrintWriter out;
private static StringTokenizer tokenizer;
public static void main(String[] args) throws Exception {
fileIOMode = args.length > 0 && args[0].equals("!");
if (fileIOMode) {
in = new BufferedReader(new FileReader("a.in"));
out = new PrintWriter("a.out");
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tokenizer = new StringTokenizer("");
new Thread(new A()).start();
}
private static String nextLine() {
try {
return in.readLine();
} catch (IOException e) {
return null;
}
}
private static String nextToken() {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(nextLine());
}
return tokenizer.nextToken();
}
private static int nextInt() {
return Integer.parseInt(nextToken());
}
private static long nextLong() {
return Long.parseLong(nextToken());
}
private static double nextDouble() {
return Double.parseDouble(nextToken());
}
private static BigInteger nextBigInteger() {
return new BigInteger(nextToken());
}
private static void print(Object o) {
if (fileIOMode) {
System.out.print(o);
}
out.print(o);
}
private static void println(Object o) {
if (fileIOMode) {
System.out.println(o);
}
out.println(o);
}
private static void printf(String s, Object... o) {
if (fileIOMode) {
System.out.printf(s, o);
}
out.printf(s, o);
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author kessido
*/
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);
DOlyaAndMagicalSquare solver = new DOlyaAndMagicalSquare();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class DOlyaAndMagicalSquare {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.NextInt();
long k = in.NextLong();
if (k == 0) {
out.println("YES " + n);
return;
}
long operationTillNow = 0, numberOfCubeOnTheSide = 1;
ArrayList<CubeCount> cubes = new ArrayList<>();
for (int i = n - 1; i >= 0; i--) {
cubes.add(new CubeCount(i, (numberOfCubeOnTheSide - 1) * 2 * 2 + 1));
operationTillNow = operationTillNow + 2 * numberOfCubeOnTheSide - 1;
numberOfCubeOnTheSide *= 2;
long operationLeft = k - operationTillNow;
if (operationLeft == 0) {
out.println("YES " + i);
return;
} else if (operationLeft < 0) {
out.println("NO");
return;
}
for (CubeCount c : cubes) {
if (!c.hasLessThen(operationLeft)) {
out.println("YES " + i);
return;
} else {
operationLeft = c.removeMeFrom(operationLeft);
}
}
if (operationLeft <= 0) {
out.println("YES " + i);
return;
}
}
out.println("NO");
return;
}
class CubeCount {
int sideSizeLogScale;
long repeats;
public CubeCount(int sideSizeLogScale, long repeats) {
this.repeats = repeats;
this.sideSizeLogScale = sideSizeLogScale;
}
public boolean hasLessThen(long k) {
return hasLessThen(k, sideSizeLogScale, repeats);
}
private boolean hasLessThen(long k, int sideLog, long repeats) {
while (true) {
if (k <= 0) return false;
if (sideLog == 0) return true;
k -= repeats;
sideLog--;
repeats *= 4;
}
}
public long removeMeFrom(long k) {
return removeMeFrom(k, sideSizeLogScale, repeats);
}
private long removeMeFrom(long k, int sideLog, long repeats) {
while (true) {
if (sideLog == 0) return k;
k -= repeats;
sideLog--;
repeats *= 4;
}
}
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine(), " \t\n\r\f,");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int NextInt() {
return Integer.parseInt(next());
}
public long NextLong() {
return Long.parseLong(next());
}
}
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Scanner;
public class B {
public static void main(String[] args) {
doIt();
}
static void doIt() {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
long n = sc.nextLong();
long k = sc.nextLong();
long msum = (k - 1) * k / 2 + 1;
long u = k;
long l = 0;
long m = (u + l) / 2;
while(l < u){
m = (u + l) / 2 + (u + l) % 2;
long sum = (m - 1) * m / 2;
if(n <= msum - sum) l = m;
else u = m - 1;
}
m = (u + l) / 2 + (u + l) % 2;
if(msum - (m - 1) * m / 2 < n) System.out.println(-1);
else System.out.println(k - m);
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class IQTest implements Runnable
{
public static void main(String[] args) throws Exception
{
new IQTest().run();
}
private void solve() throws Exception
{
int n = nextInt();
int a[] = new int[n];
for (int i = 0; i < a.length; i++)
{
a[i] = nextInt();
}
int c0 = 0, c1 = 0;
for (int i = 0; i < a.length; i++)
{
a[i] = a[i] % 2;
if (a[i] == 0)
c0++;
else
c1++;
}
int f = 0;
if (c0 > c1)
f = 1;
else
f = 0;
int r = 0;
for (int i = 0; i < a.length; i++)
{
if (a[i] == f)
{
r = i + 1;
break;
}
}
out.println(r);
}
// -------------- Input/Output routines below ---------------//
private BufferedReader in;
PrintWriter out;
StringTokenizer tokenizer;
public void run()
{
// String problem = this.getClass().getName();
try
{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
solve();
out.flush();
in.close();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
// System.exit(1);
}
}
String nextToken() throws IOException
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
int nextInt() throws IOException
{
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException
{
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException
{
return Double.parseDouble(nextToken());
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.