src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.io.*;
import java.util.*;
public class B {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static FastReader s = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
private static int[] rai(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
return arr;
}
private static int[][] rai(int n, int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = s.nextInt();
}
}
return arr;
}
private static long[] ral(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextLong();
}
return arr;
}
private static long[][] ral(int n, int m) {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = s.nextLong();
}
}
return arr;
}
private static int ri() {
return s.nextInt();
}
private static long rl() {
return s.nextLong();
}
private static String rs() {
return s.next();
}
static int gcd(int a,int b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
static long gcd(long a,long b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
static boolean isPrime(int n) {
//check if n is a multiple of 2
if(n==1)
{
return false;
}
if(n==2)
{
return true;
}
if (n % 2 == 0) return false;
//if not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
return true;
}
static boolean[] sieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
boolean prime[] = new boolean[n+1];
for(int i=0;i<n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
// If prime[p] is not changed, then it is a prime
if(prime[p] == true)
{
// Update all multiples of p
for(int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
public static void main(String[] args) {
StringBuilder ans = new StringBuilder();
int t = ri();
// int t=1;
while (t-- > 0)
{
long n=rl();
if(n%2==1)
{
ans.append("NO\n");
continue;
}
if(n%4==0)
{
long val = n/4;
long sq = (long) Math.sqrt(val);
if(sq*sq == val)
{
ans.append("YES\n");
continue;
}
}
if(n%2==0)
{
long val = n/2;
long sq = (long) Math.sqrt(val);
if(sq*sq == val)
{
ans.append("YES\n");
continue;
}
}
ans.append("NO\n");
}
out.print(ans.toString());
out.flush();
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class Solver {
StringTokenizer st;
BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws NumberFormatException,
IOException {
Solver solver = new Solver();
solver.open();
solver.solve();
solver.close();
}
public void open() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
public String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
int n;
class Otr {
int x1, y1, x2, y2;
int dx, dy;
public Otr(int x, int y, int dx, int dy) {
super();
this.x1 = x;
this.y1 = y;
this.x2 = x;
this.y2 = y;
this.dx = dx;
this.dy = dy;
}
int getAns() {
if (x1 == x2 && y1 == y2) {
int nx1 = x1 + dx;
int ny2 = y2 + dy;
if ((nx1 <= 0 || nx1 > n) && (ny2 <= 0 || ny2 > n)) {
return 0;
}
}
x1 += dx;
if (x1 <= 0) {
x1 = 1;
y1 += dy;
}
if (x1 > n) {
x1 = n;
y1 += dy;
}
y2 += dy;
if (y2 <= 0) {
y2 = 1;
x2 += dx;
}
if (y2 > n) {
y2 = n;
x2 += dx;
}
return Math.abs(x1 - x2) + 1;
}
@Override
public String toString() {
return "(" + x1 + "," + y1 + ")->(" + x2 + "," + y2 + ")";
}
}
int[] dxs = { -1, -1, 1, 1 };
int[] dys = { -1, 1, -1, 1 };
public void solve() throws NumberFormatException, IOException {
n = nextInt();
int x = nextInt();
int y = nextInt();
long c = nextLong();
long now = 1;
Otr[] otr = new Otr[4];
for (int i = 0; i < 4; i++) {
otr[i] = new Otr(x, y, dxs[i], dys[i]);
}
int result = 0;
while (now < c) {
for (int i = 0; i < 4; i++) {
now += otr[i].getAns();
}
for (int i = 0; i < 3; i++) {
for (int j = i + 1; j < 4; j++) {
Otr o1 = otr[i];
Otr o2 = otr[j];
if (o1.x1!=o1.x2 || o1.y1!=o1.y2){
if (o2.x1!=o2.x2 || o2.y1!=o2.y2){
if (o1.x1 == o2.x1 && o1.y1 == o2.y1) {
now--;
}
if (o1.x1 == o2.x2 && o1.y1 == o2.y2) {
now--;
}
if (o1.x2 == o2.x1 && o1.y2 == o2.y1) {
now--;
}
if (o1.x2 == o2.x2 && o1.y2 == o2.y2) {
now--;
}
}else{
if (o1.x1 == o2.x1 && o1.y1 == o2.y1) {
now--;
}
if (o1.x2 == o2.x1 && o1.y2 == o2.y1) {
now--;
}
}
}else{
if (o2.x1!=o2.x2 || o2.y1!=o2.y2){
if (o1.x2 == o2.x1 && o1.y2 == o2.y1) {
now--;
}
if (o1.x2 == o2.x2 && o1.y2 == o2.y2) {
now--;
}
}else{
if (o1.x1 == o2.x1 && o1.y1 == o2.y1) {
now--;
}
}
}
}
}
result++;
}
out.println(result);
}
public void close() {
out.flush();
out.close();
}
}
|
logn
|
256_B. Mr. Bender and Square
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Aman Kumar Singh
*/
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);
G1PlaylistForPolycarpEasyVersion solver = new G1PlaylistForPolycarpEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class G1PlaylistForPolycarpEasyVersion {
final long mod = 1000000007;
PrintWriter out;
InputReader in;
int n;
int time;
int[][] arr;
long[][][] dp;
long go(int last, int t, int mask) {
if (t > time)
return 0;
if (t == time) {
return 1l;
}
if (mask == (1 << n) - 1)
return 0;
if (dp[last][t][mask] != -1)
return dp[last][t][mask];
long cnt = 0;
int i = 0, j = 0;
for (i = 0; i < n; i++) {
if ((mask & (1 << i)) == 0 && arr[i][1] != last) {
cnt += go(arr[i][1], t + arr[i][0], mask | (1 << i));
cnt %= mod;
}
}
dp[last][t][mask] = cnt;
return cnt;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
this.out = out;
this.in = in;
n = ni();
time = ni();
arr = new int[n][2];
int i = 0;
for (i = 0; i < n; i++) {
arr[i][0] = ni();
arr[i][1] = ni() - 1;
}
dp = new long[3][time + 1][1 << n];
for (i = 0; i < 3; i++) {
for (int j = 0; j <= time; j++)
Arrays.fill(dp[i][j], -1);
}
long ans = (((go(0, 0, 0) + go(1, 0, 0)) % mod + go(2, 0, 0)) % mod);
ans *= modPow(2, mod - 2);
ans %= mod;
pn(ans);
}
int ni() {
return in.nextInt();
}
void pn(Object o) {
out.println(o);
}
long modPow(long a, long p) {
long o = 1;
while (p > 0) {
if ((p & 1) == 1) o = mul(o, a);
a = mul(a, a);
p >>= 1;
}
return o;
}
long mul(long a, long b) {
if (a >= mod) a %= mod;
if (b >= mod) b %= mod;
a *= b;
if (a >= mod) a %= mod;
return a;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
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;
}
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.*;
public class Main
{
static Graph graph[];
public static void add_edge(int u,int v)
{
graph[u].adj.add(graph[v]);
graph[v].adj.add(graph[u]);
}
public static void dfs(int index)
{
Graph z=graph[index];
z.vis=1;Graph v;
for( int i=0;i<z.adj.size();i++)
{
v=z.adj.get(i);
if(v.vis==0)
{
v.dist=z.dist+1;
v.parent=z.val;
dfs(v.val);
}
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader sc=new FastReader();
int n=sc.nextInt();
Pair arr[]=new Pair[n];
Pair pref[]=new Pair[n];
Pair suff[]=new Pair[n];
for( int i=0;i<n;i++)
{
long u=sc.nextLong();
long v=sc.nextLong();
arr[i]=new Pair(u,v);
pref[i]=new Pair(0,0);
suff[i]=new Pair(0,0);
}
pref[0].x=arr[0].x;
pref[0].y=arr[0].y;
for( int i=1;i<n;i++)
{
pref[i].x=(long)Math.max(pref[i-1].x,arr[i].x);
pref[i].y=(long)Math.min(pref[i-1].y,arr[i].y);
}
suff[n-1].x=arr[n-1].x;
suff[n-1].y=arr[n-1].y;
for( int i=n-2;i>=0;i--)
{
suff[i].x=(long)Math.max(suff[i+1].x,arr[i].x);
suff[i].y=(long)Math.min(suff[i+1].y,arr[i].y);
}
long max=Long.MIN_VALUE;
long ans=0;
for( int i=0;i<n;i++)
{
long val=Long.MAX_VALUE;
long val1=Long.MAX_VALUE;
if(i!=0&&i!=n-1)
{
val=(long)Math.min(pref[i-1].y,suff[i+1].y)-(long)Math.max(pref[i-1].x,suff[i+1].x);
}
else if(i!=n-1)
{
val=suff[i+1].y-suff[i+1].x;
}
else
val=pref[i-1].y-pref[i-1].x;
ans=val;
if(ans<0)
ans=0;
max=(long)Math.max(ans,max);
}
System.out.println(max);
}
}
class mycomparator implements Comparator<Graph>
{
public int compare(Graph a, Graph b)
{
return b.dist-a.dist;
}
}
class Graph
{
int vis,col,val;int parent;int deg;int dist;
ArrayList<Graph> adj;
Graph(int val)
{
vis=0;
col=-1;
adj=new ArrayList<>();
parent=-1;
this.val=val;
deg=0;
dist=-1;
}
}
class Pair
{
long x,y;
Pair( long x, long y)
{
this.x=x;
this.y=y;
}
}
|
linear
|
1029_C. Maximal Intersection
|
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;
boolean[] iq;
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_];
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);
}
boolean dijkstra(int s, int t) {
Arrays.fill(pi, INF);
pi[s] = 0;
TreeSet<Integer> pq = new TreeSet<>((u, v) -> pi[u] != pi[v] ? pi[u] - pi[v] : dd[u] != dd[v] ? dd[u] - dd[v] : u - v);
pq.add(s); iq[s] = true;
Integer first;
while ((first = pq.pollFirst()) != null) {
int u = first;
iq[u] = false;
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) {
if (iq[v]) {
pq.remove(v); iq[v] = false;
}
pi[v] = p;
dd[v] = d;
bb[v] = h_;
pq.add(v); iq[v] = true;
}
}
}
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 (dijkstra(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.Scanner;
public class P23A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
System.out.println(F(input));
}
static int F(String string){
int ans =0;
for (int i = 0; i < string.length(); i++) {
for (int j = 1; j < string.length()-i; j++) {
String s = string.substring(i, i+j);
int a=string.indexOf(s);
int b=string.lastIndexOf(s);
if ( a >= 0 && b >=0 && a !=b) ans =Math.max(ans, s.length());
}
}
return ans;
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.math.*;
/*
50
873 838 288 87 889 364 720 410 565 651 577 356 740 99 549 592 994 385 777 435 486 118 887 440 749 533 356 790 413 681 267 496 475 317 88 660 374 186 61 437 729 860 880 538 277 301 667 180 60 393
6
2 2 3 3 5 5
4
2 2 3 3
*/
public class C429 {
static InputStream is;
static int[] counts;
static int[] sufsum;
static long mod = (long)(1e9+7);
static long[][] choose;
static long[][] memo;
public static void main(String[] args) throws IOException {
is = System.in;
int n = ni();
int[] a = na(n);
long[] fact = new long[n+2];
fact[0] = 1;
for (int i = 1; i < fact.length; i++) {
fact[i] = (fact[i-1]*i)%mod;
}
HashMap<Integer,ArrayList<Integer>> hm = new HashMap<>();
for (int i = 0; i < a.length; i++) {
int cp = a[i];
int sfree = 1;
for(int p = 2; p*p <= a[i] && cp > 1; p++){
int count = 0;
while(cp % p == 0){
cp /= p;
count++;
}
if(count % 2 == 1) sfree *= p;
}
if(cp != 1) sfree *= cp;
if(!hm.containsKey(sfree)) hm.put(sfree, new ArrayList<Integer>());
hm.get(sfree).add(a[i]);
}
counts = new int[hm.size()];
int dex = 0;
//System.out.println(hm);
long bigmult = 1;
for(Integer key : hm.keySet()){
ArrayList<Integer> list = hm.get(key);
counts[dex++] = list.size();
bigmult = bigmult*fact[list.size()] % mod;
// HashMap<Integer,Integer> dups = new HashMap<>();
// for(int x : list){
// if(!dups.containsKey(x)){
// dups.put(x, 0);
// }
// dups.put(x, dups.get(x)+1);
// }
// for (int k : dups.keySet()) {
// int amount = dups.get(k);
// long tomult = new BigInteger(fact[amount]+"").modInverse(new BigInteger(mod+"")).longValue();
// bigmult*= tomult;
// bigmult %= mod;
// }
}
Arrays.sort(counts);
sufsum = new int[counts.length];
for(int i = counts.length-2; i >= 0; i--){
sufsum[i] = sufsum[i+1]+counts[i+1];
}
choose = new long[2*n+3][2*n+3];
for(int i = 0; i < choose.length; i++){
choose[i][0] = 1;
for(int j = 1; j <=i; j++){
choose[i][j] = (choose[i-1][j]+choose[i-1][j-1])%mod;
}
}
memo = new long[counts.length][700];
for (int i = 0; i < memo.length; i++) {
Arrays.fill(memo[i], -1);
}
//System.out.println("bigmult: " + bigmult);
System.out.println((bigmult*dp(counts.length-2,counts[counts.length-1]-1))%mod);
}
static long dp(int dex, int need){
if(dex == -1){
if(need == 0) return 1;
return 0;
}
//System.out.println("dex: " + dex + " need " + need);
if(memo[dex][need] != -1) return memo[dex][need];
int numspots = sufsum[dex]+1;
long ret = 0;
int c = counts[dex];
for(int numdivs = 1; numdivs <= c; numdivs++) {
long toadd = 0;
for(int gotoneed =0; gotoneed <= need && gotoneed <= numdivs; gotoneed++) {
long temp = choose[need][gotoneed];
temp *= choose[numspots-need][numdivs-gotoneed];
//System.out.println("dex: " + dex + " need: "+ need + " numdivs: " + numdivs + " c1: " + choose[need][gotoneed] + " c2 " + choose[numspots-need][numdivs-gotoneed]);
temp %= mod;
temp *= dp(dex-1,need-gotoneed+c-numdivs);
temp %= mod;
toadd += temp;
toadd %= mod;
}
toadd *= choose[c-1][numdivs-1];
toadd %= mod;
ret += toadd;
ret %= mod;
}
//System.out.println("dex: " + dex + " need: "+ need + " ret: " + ret);
return memo[dex][need]=ret;
}
private static byte[] inbuf = new byte[1024];
public static int lenbuf = 0, ptrbuf = 0;
private static 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 static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private static double nd() { return Double.parseDouble(ns()); }
private static char nc() { return (char)skip(); }
private static 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 static 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 static 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 static int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private static 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 static 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();
}
}
}
|
cubic
|
840_C. On the Bench
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main implements Runnable {
private void solution() throws IOException {
int n = in.nextInt();
int m = in.nextInt();
boolean[][] adj = new boolean[n][n];
long res = 0;
for (int i = 0; i < m; ++i) {
int x = in.nextInt();
int y = in.nextInt();
adj[x - 1][y - 1] = true;
adj[y - 1][x - 1] = true;
}
final long[][] dp = new long[1 << n][n];
for (int i = 0; i < n; ++i) {
int Limit = 1 << (n - i);
int nn = n - i;
for (int mask = 0; mask < Limit; ++mask) {
for (int j = 0; j < nn; ++j) {
dp[mask][j] = 0;
}
}
dp[0][0] = 1;
for (int mask = 0; mask < Limit; ++mask) {
for (int j = 0; j < nn; ++j) {
if (dp[mask][j] != 0) {
long am = dp[mask][j];
for (int k = 0; k < nn; ++k) {
if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) {
dp[mask | (1 << k)][k] += am;
}
}
}
}
if (((mask >> 0) & 1) != 0) {
res += dp[mask][0];
}
}
}
out.println((res - m) / 2);
}
public void run() {
try {
solution();
in.reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private class Scanner {
BufferedReader reader;
StringTokenizer tokenizer;
public Scanner(Reader reader) {
this.reader = new BufferedReader(reader);
this.tokenizer = new StringTokenizer("");
}
public boolean hasNext() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String next = reader.readLine();
if (next == null) {
return false;
}
tokenizer = new StringTokenizer(next);
}
return true;
}
public String next() throws IOException {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public String nextLine() throws IOException {
tokenizer = new StringTokenizer("");
return reader.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
public static void main(String[] args) throws IOException {
new Thread(null, new Main(), "", 1 << 28).start();
}
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
Scanner in = new Scanner(new InputStreamReader(System.in));
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class D {
public static void solve(FastScanner fs) {
int n=fs.nextInt();
int[] a=fs.readArray(n);
boolean even=((countInversions(a)&1)==0);
int q=fs.nextInt();
for (int i=0; i<q; i++) {
int start=fs.nextInt();
int end=fs.nextInt();
int diff=end-start;
boolean evenChange=(diff+1)/2%2==0;
even^=!evenChange;
System.out.println(even?"even":"odd");
}
}
private static int countInversions(int[] a) {
int c=0;
for (int i=0; i<a.length; i++) {
for (int j=i+1; j<a.length; j++)
if (a[j]<a[i])
c++;
}
return c;
}
public static void main(String[] args) throws NumberFormatException, IOException {
FastScanner scanner = new FastScanner(System.in);
solve(scanner);
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(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;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++)
a[i]=nextInt();
return a;
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
//package codeforces;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class D {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(System.out);
StringTokenizer stringTokenizer;
String next() throws IOException {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
final int MOD = 1000 * 1000 * 1000 + 7;
int sum(int a, int b) {
a += b;
return a >= MOD ? a - MOD : a;
}
@SuppressWarnings("unchecked")
void solve() throws IOException {
final int n = nextInt();
int m = nextInt();
int[] from = new int[m];
int[] to = new int[m];
for(int i = 0; i < m; i++) {
from[i] = nextInt();
to[i] = nextInt();
}
int ans = solve(n, m, from, to);
writer.println(ans);
writer.close();
}
private int solve(final int n, int m, int[] from, int[] to) {
final List<List<Integer>> g = new ArrayList<>();
for(int i = 0; i <= n; i++) {
g.add(new ArrayList<Integer>());
}
int[] c = new int[n + 1];
int[] loop = new int[n + 1];
for(int i = 0; i < m; i++) {
int u = from[i];
int v = to[i];
g.get(u).add(v);
c[u]++;
c[v]++;
if(u == v) {
loop[u]++;
}
}
class Utils {
int[] prev = new int[n + 1];
int[] used = new int[n + 1];
int mark;
int forbidden;
int maxMatch() {
maxMatch = 0;
for(int i = 1; i <= n; i++) {
mark = i;
if(findPath(i)) {
maxMatch++;
}
}
return maxMatch;
}
boolean findPath(int u) {
if(u == forbidden) {
return false;
}
used[u] = mark;
for (int v : g.get(u)) {
if(v == forbidden) {
continue;
}
if(prev[v] == 0 || (used[prev[v]] != mark && findPath(prev[v]))) {
prev[v] = u;
return true;
}
}
return false;
}
int maxMatch = 0;
}
int ans = Integer.MAX_VALUE;
for(int i = 1; i <= n; i++) {
Utils utils = new Utils();
utils.forbidden = i;
utils.maxMatch();
ans = Math.min(ans, (2 * n - 1 - c[i] + loop[i]) + (m - c[i] + loop[i] - utils.maxMatch) + (n - 1 - utils.maxMatch));
}
return ans;
}
public static void main(String[] args) throws IOException {
new D().solve();
}
}
|
cubic
|
387_D. George and Interesting Graph
|
CODEFORCES
|
import java.util.*;
public class Hotels {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] cities = new int[n];
int d = input.nextInt();
for (int i = 0; i<n; i++) {
cities[i] = input.nextInt();
}
int possibilities = 0;
ArrayList<Integer> newHotels = new ArrayList<Integer>();
for (int i = 0; i<n; i++) {
int plusD = cities[i]+d;
if (newHotels.indexOf(cities[i]+d)==-1 && minDist(plusD,cities)==d) {
possibilities++;
newHotels.add(cities[i]+d);
}
if (newHotels.indexOf(cities[i]-d)==-1 && minDist(cities[i]-d,cities)==d) {
possibilities++;
newHotels.add(cities[i]-d);
}
}
System.out.println(possibilities);
}
public static int minDist(int a, int[] arr) {
int minDist = Integer.MAX_VALUE;
for (int i=0; i<arr.length; i++) {
minDist = Math.min(Math.abs(arr[i]-a), minDist);
}
return minDist;
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.util.*;
public class Main {
static int n=5;
static int[] arr=new int[5];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for (int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
for (int i=0;i<n;i++)
{
if (arr[i]>=0)
{
arr[i]=-arr[i]-1;
}
}
if (n%2!=0)
{
int min=0;
for (int i=1;i<n;i++)
{
if (arr[i]<arr[min])
min=i;
}
arr[min]=-arr[min]-1;
}
for (int x:arr)
{
System.out.print(x + " ");
}
}
}
|
linear
|
1180_B. Nick and Array
|
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 Main {
private static final String NO = "NO";
private static final String YES = "YES";
InputStream is;
PrintWriter out;
String INPUT = "";
private static long MOD = 1000000007;
private static final int MAXN = 100000;
void solve() {
int T = 1;// ni();
for (int i = 0; i < T; i++) {
solve(i);
}
}
static final int N = 405;
static long[][] dp = new long[N][N];
static long[] p2 = new long[N];
static long[] fac = new long[N];
static long[] ifac = new long[N];
public static long bino(int n, int k) {
return ((fac[n] * ifac[n - k]) % MOD * ifac[k]) % MOD;
}
void solve(int T) {
int n = ni();
MOD = nl();
fac[0] = 1;
ifac[0] = 1;
p2[0] = 1;
for (int i = 1; i <= n; ++i) {
fac[i] = (fac[i - 1] * i) % MOD;
p2[i] = (p2[i - 1] * 2) % MOD;
}
ifac[n] = power(fac[n], MOD - 2);
for (int i = n - 1; i > 0; --i) {
ifac[i] = (ifac[i + 1] * (i + 1)) % MOD;
}
dp[0][0] = 1;
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= i; ++j) {
for (int k = 1; i + k <= n; ++k) {
dp[i + k + 1][j
+ k] = (dp[i + k + 1][j + k] + ((dp[i][j] * p2[k - 1]) % MOD * bino(k + j, k)) % MOD) % MOD;
}
}
}
long ans = 0;
for (int i = 0; i <= n; ++i) {
ans = (ans + dp[n + 1][i]) % MOD;
}
out.println(ans);
}
// a^b
long power(long a, long b) {
long x = 1, y = a;
while (b > 0) {
if (b % 2 != 0) {
x = (x * y) % MOD;
}
y = (y * y) % MOD;
b /= 2;
}
return x % MOD;
}
private long gcd(long a, long b) {
while (a != 0) {
long tmp = b % a;
b = a;
a = tmp;
}
return b;
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty())
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n) {
if (!(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 List<Integer> na2(int n) {
List<Integer> a = new ArrayList<Integer>();
for (int i = 0; i < n; i++)
a.add(ni());
return a;
}
private int[][] na(int n, int m) {
int[][] a = new int[n][];
for (int i = 0; i < n; i++)
a[i] = na(m);
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(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private long[][] nl(int n, int m) {
long[][] a = new long[n][];
for (int i = 0; i < n; i++)
a[i] = nl(m);
return a;
}
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 static void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class cf166a {
private static boolean[][] matrix;
private static int n;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// long l = sc.nextLong();
// int i = sc.nextInt();
// String input = sc.nextLine();
int n = sc.nextInt();
int k = sc.nextInt();
int[] p = new int[n];
int[] t = new int[n];
int[] score = new int[n];
for(int i=0;i<n;i++){
p[i] = sc.nextInt();
t[i] = sc.nextInt();
score[i] = p[i] * 100 + (50 - t[i]);
}
boolean[] called = new boolean[n];
int x = 0;
boolean check = false;
while(true){
int max = 0;
int y = 0;
for(int i=0;i<n;i++){
if(called[i]==false&&score[i]>max){max=score[i];}
}
for(int i=0;i<n;i++){
if(max==score[i]){
called[i] = true;
x++;
y++;
if(x==k){check=true;}
}
}
if(check){
System.out.println(y);
break;
}
}
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
/**
* JUDGE_ID : 104262PN
* User : Денис
* Date : 09.05.11
* Time : 22:48
* ICQ : 785625
* Email : popokus@gmail.com
*/
import java.io.*;
public class s11_d {
public static void main(String[] args) throws IOException {
new s11_d().run();
}
int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
String nextString() throws IOException {
in.nextToken();
return (String) in.sval;
}
StreamTokenizer in;
Writer writer;
Reader reader;
void run() throws IOException {
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
reader = oj ? new InputStreamReader(System.in, "ISO-8859-1") : new FileReader("input/is11_d.txt");
writer = new OutputStreamWriter(System.out, "ISO-8859-1");
in = new StreamTokenizer(new BufferedReader(reader));
PrintWriter out = new PrintWriter(writer);
int n = nextInt();
int e = nextInt();
boolean[][] is = new boolean[n + 1][n + 1];
for (int i = 0; i < e;i++) {
int a = nextInt() - 1;
int b = nextInt() - 1;
is[a][b] = true;
is[b][a] = true;
}
// calculating dp
long[] am = new long[n + 1];
long[][] ways = new long[1 << (n - 1)][n];
for (int start = 0; start < n; ++start) {
for (int mask = 0; mask < (1 << (n - start - 1)); ++mask)
for (int last = start; last < n; ++last) {
ways[mask][last - start] = 0;
}
ways[1 >> 1][0] = 1;
for (int mask = 1; mask < (1 << (n - start)); mask += 2) {
int cnt = 0;
int tmp = mask;
while (tmp > 0) {
++cnt;
tmp = tmp & (tmp - 1);
}
for (int last = start; last < n; ++last)
if (ways[mask >> 1][last - start] > 0) {
long amm = ways[mask >> 1][last - start];
for (int i = start; i < n; ++i)
if ((mask & (1 << (i - start))) == 0 && is[last][i]) {
ways[(mask | (1 << (i - start))) >> 1][i - start] += amm;
}
if (is[last][start])
am[cnt] += ways[mask >> 1][last - start];
}
}
}
long res = 0;
for (int cnt = 3; cnt <= n; ++cnt) {
if (am[cnt] % (2) != 0)
throw new RuntimeException();
res += am[cnt] / (2);
}
out.println(res);
out.flush();
out.close();
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
public class A {
static StreamTokenizer st;
static class Sort implements Comparable<Sort> {
int val;
public int compareTo(Sort o) {
return this.val-o.val;
}
}
public static void main(String[] args) throws IOException{
st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
Sort[]a = new Sort[n+1];
int[]b = new int[n+1];
for (int i = 1; i <= n; i++) {
a[i] = new Sort();
a[i].val = nextInt();
b[i] = a[i].val;
}
Arrays.sort(a, 1, n+1);
int k1 = 0, k2 = 0;
for (int i = 1; i <= n; i++) {
if (b[i] != a[i].val) {
if (k1==0)
k1 = i;
else if (k2==0)
k2 = i;
else {
System.out.println("NO");
return;
}
}
}
if (k1==0)
System.out.println("YES");
else if (k2==0)
System.out.println("NO");
else {
if (b[k1]==a[k2].val && b[k2]==a[k1].val)
System.out.println("YES");
else
System.out.println("NO");
}
pw.close();
}
private static int nextInt() throws IOException{
st.nextToken();
return (int) st.nval;
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.IOException;
import java.util.StringTokenizer;
/*
* @author Tnascimento
*/
public class MaeDosDragoes {
public static PrintWriter saida = new PrintWriter(System.out, false);
public static class Escanear {
BufferedReader reader;
StringTokenizer tokenizer;
public Escanear() {
this(new InputStreamReader(System.in));
}
public Escanear(Reader in) {
reader = new BufferedReader(in);
}
String proximo() {
if (tokenizer == null || !tokenizer.hasMoreElements()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
int proximoNum() {
return Integer.parseInt(proximo());
}
}
public static void main(String[] args) {
Escanear escanear = new Escanear();
int proximoInt = escanear.proximoNum();
long[] aux = new long[proximoInt];
double proximoDouble = escanear.proximoNum();
for(Integer i = 0; i < proximoInt; i++) {
for(Integer j =0; j < proximoInt; j++) {
Integer val = escanear.proximoNum();
if (val.equals(1) || i.equals(j)) {
aux[i] |= 1L << j;
}
}
}
int esquerda = proximoInt/2;
int direita = proximoInt - esquerda;
int maiorMascara = 1 << esquerda;
int[] depois = new int[1 << esquerda];
Integer mascara = 1;
while (mascara < maiorMascara) {
int mascaraAtual = mascara;
for(int j = 0; j < esquerda; j++) {
if (((1 << j) & mascara) > 0) {
mascaraAtual &= aux[j + direita] >> direita;
depois[mascara] = Math.max(depois[mascara], depois[mascara ^ (1 << j)]);
}
}
if (mascara == mascaraAtual) {
depois[mascara] = Math.max(depois[mascara],Integer.bitCount(mascara));
}
mascara++;
}
// for(int mascara = 1; mascara < maiorMascara; mascara++) {
// int mascaraAtual = mascara;
// for(int j = 0; j < esquerda; j++) {
// if (((1 << j) & mascara) > 0) {
// mascaraAtual &= aux[j + direita] >> direita;
// depois[mascara] = Math.max(depois[mascara], depois[mascara ^ (1 << j)]);
// }
// }
// if (mascara == mascaraAtual) {
// depois[mascara] = Math.max(depois[mascara],Integer.bitCount(mascara));
// }
// }
int auxiliar = 0;
int mascaraMaxima = 1 << direita;
for(int masc = 0; masc < mascaraMaxima; masc++) {
int mascaraCorrente = masc;
int mascaraValor = maiorMascara -1;
for(int j = 0; j < direita; j++) {
if (((1 << j) & masc) > 0) {
mascaraCorrente &= (aux[j] & (mascaraMaxima-1));
mascaraValor &= aux[j] >> direita;
}
}
if (mascaraCorrente != masc) continue;
auxiliar = Math.max(auxiliar, Integer.bitCount(masc) + depois[mascaraValor]);
}
proximoDouble/=auxiliar;
saida.println(proximoDouble * proximoDouble * (auxiliar * (auxiliar-1))/2);
saida.flush();
}
}
|
np
|
839_E. Mother of Dragons
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class B {
void run(){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), k = sc.nextInt();
int[] a = new int[n+1];
for(int i=1;i<=n;i++)a[i]=sc.nextInt();
int[] c = new int[100001];
int num = 0;
int ri = -1, rj = -1;
int s = 1, t = 0;
while(t<n){
t++;
if(c[a[t]]==0){
num++;
}
c[a[t]]++;
for(;k<=num;s++){
if(ri==-1 || rj-ri+1>t-s+1){
ri = s; rj = t;
}
c[a[s]]--;
if(c[a[s]]==0){
num--;
}
}
}
System.out.println(ri+" "+rj);
}
void debug(Object...o){
System.out.println(Arrays.deepToString(o));
}
public static void main(String[] args) {
new B().run();
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
//package global14;
import java.util.Scanner;
public class B {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while(t > 0){
t --;
int n = in.nextInt();
if(n % 2 != 0){
System.out.println("NO");
continue;
}
int a = n / 2;
int x = (int)Math.sqrt(a);
if(x * x == a || (x + 1) * (x + 1) == a){
System.out.println("YES");
continue;
}
a = n / 4;
if(n % 4 != 0){
System.out.println("NO");
continue;
}
x = (int)Math.sqrt(a);
if(x * x == a || (x + 1) * (x + 1) == a){
System.out.println("YES");
continue;
}
System.out.println("NO");
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder text = new StringBuilder(in.nextLine()); String substr; String max="";
for(int i=2; i<=text.length(); i++){
for(int j=0; j<i; j++){
substr = text.substring(j, i);
if(text.lastIndexOf(substr) != text.indexOf(substr)){
if(substr.length() > max.length()){ max = substr;}
}
}
}
System.out.println(max.length());
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class B {
public static void main(String[] args) throws IOException {
/**/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
/*/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/b.in"))));
/**/
int t = sc.nextInt();
for (int z = 0; z < t; ++z) {
int n = sc.nextInt();
if (n%2==1) {
System.out.println("NO");
continue;
}
n/=2;
int sqrt = (int)Math.sqrt(n);
if (sqrt*sqrt==n) {
System.out.println("YES");
continue;
}
if (n%2==1) {
System.out.println("NO");
continue;
}
n/=2;
sqrt = (int)Math.sqrt(n);
if (sqrt*sqrt==n) {
System.out.println("YES");
continue;
}
System.out.println("NO");
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import javax.lang.model.util.ElementScanner6;
public class codef
{
public static void main(String ar[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer nk=new StringTokenizer(br.readLine());
int n=Integer.parseInt(nk.nextToken());
int k=Integer.parseInt(nk.nextToken());
String st[]=br.readLine().split(" ");
int ans[]=new int[n];
int a[]=new int[n];
for(int i=0;i<n;i++)
ans[i]=Integer.parseInt(st[i]);
for(int i=1;i<n;i++)
a[i]=ans[i]-ans[i-1];
a[0]=-1;
Arrays.sort(a);
int count=0,sum=0;
for(int i=0;i<n;i++)
if(a[i]<0)
count++;
else
sum=sum+a[i];
k=k-count;
int i=n-1;
while(k>0 && i>=0)
{
if(a[i]>-1)
{
sum=sum-a[i];
k--;
}
i--;
}
System.out.println(sum);
}
}
|
nlogn
|
1197_C. Array Splitting
|
CODEFORCES
|
import java.io.*;
import java.util.*;
/*
polyakoff
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int oo = (int) 1e9 + 10;
static final long OO = (long) 1e18 + 10;
static final int MOD = (int) 1e9 + 7;
static void solve() {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Stack<Integer> st = new Stack<>();
for (int i = 0; i < n; i++) {
if (a[i] != 1) {
while (!st.empty() && st.peek() + 1 != a[i])
st.pop();
st.pop();
}
st.push(a[i]);
for (int j = 0; j < st.size(); j++) {
out.print(st.get(j));
if (j < st.size() - 1)
out.print('.');
}
out.println();
}
}
public static void main(String[] args) {
in = new FastReader();
out = new PrintWriter(System.out);
int t = 1;
t = in.nextInt();
while (t-- > 0) {
solve();
}
out.flush();
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader() {
this(System.in);
}
FastReader(String file) throws FileNotFoundException {
this(new FileInputStream(file));
}
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
String nextLine() {
String line;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] h = new int[3000];
for(int i = 0; i<n; i++)
h[i] = in.nextInt();
int l = 0, r = 1000000000, m = 0;
int ansl = 0, ansr = 0;
while(l<=r){
m = (l+r)/2;
int ca=0;
for(int i = 0;i<n;i++)
if (h[i]>m) ca++;
if (ca == a) ansl=m;
if (ca <= a) r=m-1; else l=m+1;
}
l = 0; r = 1000000000;
while(l<=r){
m = (l+r)/2;
int ca=0;
for(int i = 0;i<n;i++)
if (h[i]>m) ca++;
if (ca == a) ansr=m;
if (ca < a) r=m-1; else l=m+1;
}
if (ansl == 0 || ansr==0) System.out.print(0); else
System.out.print(ansr-ansl+1);
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import java.io.*;
import java.math.*;
import java.util.*;
@SuppressWarnings("unused")
public class A {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
TreeSet<Integer> set = new TreeSet<Integer>();
set.add(n);
try {
String s = Integer.toString(n);
s = s.substring(0, s.length() - 1);
set.add(Integer.parseInt(s));
} catch (Exception e) {
}
try {
String s = Integer.toString(n);
s = s.substring(0, s.length() - 2) + s.charAt(s.length() - 1);
set.add(Integer.parseInt(s));
} catch (Exception e) {
}
System.out.println(max(set));
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
public class main {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static PrintWriter pw = new PrintWriter(System.out);
public static String line;
public static StringTokenizer st;
public static ArrayList<ArrayList<Integer>> adjList;
public static int[] dr = {-1, 0, 1, 0, -1, 1, 1, -1};
public static int[] dc = {0, 1, 0, -1, 1, 1, -1, -1};
public static void main(String[] args) throws Exception{
int N = Integer.parseInt(br.readLine());
char[] A = br.readLine().toCharArray();
HashSet<Character> cndD = new HashSet<Character>();
for(int i = 0; i < N; i++){
cndD.add(A[i]);
}
int cnt = cndD.size();
int a = 0;
int b = 0;
int ans = (1 << 30);
HashMap<Character, Integer> d = new HashMap<Character, Integer>();
while(b < N){
if(d.containsKey(A[b])){
if(A[a] == A[b]){
a++;
while(d.get(A[a]) > 1){
d.put(A[a], d.get(A[a])-1);
a++;
}
} else{
d.put(A[b], d.get(A[b])+1);
}
} else{
d.put(A[b], 1);
}
if(d.size() == cnt){
ans = Math.min(b-a+1, ans);
}
b++;
}
pw.print(ans + "\n");
pw.close();
br.close();
}
}
class Pair implements Comparable<Pair>{
public int a, b;
Pair(int a, int b){
this.a = a;
this.b = b;
}
@Override
public int compareTo(Pair P){
if(P.b != this.b){
return b - P.b;
} else if(P.a == this.a){
return a - P.a;
} else{
return 0;
}
}
public String toString(){
return a + " " + b;
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
//package round718;
import java.io.*;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Queue;
public class D2 {
InputStream is;
FastWriter out;
String INPUT = "";//2 5 9 9 9 9 9 8 8 8 8 5 6 7 8 9";
void solve()
{
int n = ni(), m = ni(), K = ni();
int[][] a = new int[2*n+1][2*m+1];
for(int i = 0;i < n;i++){
int[] u = na(m-1);
for(int j = 0;j < m-1;j++){
a[2*i][2*j+1] = u[j];
}
}
for(int i = 0;i < n-1;i++){
int[] u = na(m);
for(int j = 0;j < m;j++){
a[2*i+1][2*j] = u[j];
}
}
if(K % 2 == 1){
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
out.print(-1 + " ");
}
out.println();
}
return;
}
int[][][] dp = new int[K/2+1][n][m];
int[] dr = {1, 0, -1, 0};
int[] dc = {0, 1, 0, -1};
for(int i = 1;i <= K/2;i++){
for(int j = 0;j < n;j++){
for(int k = 0;k < m;k++){
dp[i][j][k] = Integer.MAX_VALUE;
for(int l = 0;l < 4;l++){
int jj = j + dr[l], kk = k + dc[l];
if(jj >= 0 && jj < n && kk >= 0 && kk < m){
dp[i][j][k] = Math.min(dp[i][j][k], dp[i-1][jj][kk] + a[j+jj][k+kk]);
}
}
}
}
}
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
out.print(dp[K/2][i][j] * 2 + " ");
}
out.println();
}
}
void run() throws Exception
{
// int n = 500, m = 500;
// Random gen = new Random();
// StringBuilder sb = new StringBuilder();
// sb.append(n + " ");
// sb.append(n + " ");
// sb.append(20 + " ");
// for (int i = 0; i < n; i++) {
// for(int j = 0;j < m-1;j++) {
// sb.append(gen.nextInt(200000) + " ");
// }
// }
// for (int i = 0; i < n-1; i++) {
// for(int j = 0;j < m;j++) {
// sb.append(gen.nextInt(200000) + " ");
// }
// }
// INPUT = sb.toString();
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new FastWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new D2().run(); }
private byte[] inbuf = new byte[1024];
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 int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private long[] nal(int n)
{
long[] a = new long[n];
for(int i = 0;i < n;i++)a[i] = nl();
return a;
}
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[][] nmi(int n, int m) {
int[][] map = new int[n][];
for(int i = 0;i < n;i++)map[i] = na(m);
return map;
}
private int ni() { return (int)nl(); }
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();
}
}
public static class FastWriter
{
private static final int BUF_SIZE = 1<<13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter(){out = null;}
public FastWriter(OutputStream os)
{
this.out = os;
}
public FastWriter(String path)
{
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b)
{
buf[ptr++] = b;
if(ptr == BUF_SIZE)innerflush();
return this;
}
public FastWriter write(char c)
{
return write((byte)c);
}
public FastWriter write(char[] s)
{
for(char c : s){
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
}
return this;
}
public FastWriter write(String s)
{
s.chars().forEach(c -> {
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x)
{
if(x == Integer.MIN_VALUE){
return write((long)x);
}
if(ptr + 12 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x)
{
if(x == Long.MIN_VALUE){
return write("" + x);
}
if(ptr + 21 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision)
{
if(x < 0){
write('-');
x = -x;
}
x += Math.pow(10, -precision)/2;
// if(x < 0){ x = 0; }
write((long)x).write(".");
x -= (long)x;
for(int i = 0;i < precision;i++){
x *= 10;
write((char)('0'+(int)x));
x -= (int)x;
}
return this;
}
public FastWriter writeln(char c){
return write(c).writeln();
}
public FastWriter writeln(int x){
return write(x).writeln();
}
public FastWriter writeln(long x){
return write(x).writeln();
}
public FastWriter writeln(double x, int precision){
return write(x, precision).writeln();
}
public FastWriter write(int... xs)
{
boolean first = true;
for(int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs)
{
boolean first = true;
for(long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln()
{
return write((byte)'\n');
}
public FastWriter writeln(int... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(long... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(char[] line)
{
return write(line).writeln();
}
public FastWriter writeln(char[]... map)
{
for(char[] line : map)write(line).writeln();
return this;
}
public FastWriter writeln(String s)
{
return write(s).writeln();
}
private void innerflush()
{
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush()
{
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) { return write(b); }
public FastWriter print(char c) { return write(c); }
public FastWriter print(char[] s) { return write(s); }
public FastWriter print(String s) { return write(s); }
public FastWriter print(int x) { return write(x); }
public FastWriter print(long x) { return write(x); }
public FastWriter print(double x, int precision) { return write(x, precision); }
public FastWriter println(char c){ return writeln(c); }
public FastWriter println(int x){ return writeln(x); }
public FastWriter println(long x){ return writeln(x); }
public FastWriter println(double x, int precision){ return writeln(x, precision); }
public FastWriter print(int... xs) { return write(xs); }
public FastWriter print(long... xs) { return write(xs); }
public FastWriter println(int... xs) { return writeln(xs); }
public FastWriter println(long... xs) { return writeln(xs); }
public FastWriter println(char[] line) { return writeln(line); }
public FastWriter println(char[]... map) { return writeln(map); }
public FastWriter println(String s) { return writeln(s); }
public FastWriter println() { return writeln(); }
}
public void trnz(int... o)
{
for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" ");
System.out.println();
}
// print ids which are 1
public void trt(long... o)
{
Queue<Integer> stands = new ArrayDeque<>();
for(int i = 0;i < o.length;i++){
for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x));
}
System.out.println(stands);
}
public void tf(boolean... r)
{
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
public void tf(boolean[]... b)
{
for(boolean[] r : b) {
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
System.out.println();
}
public void tf(long[]... b)
{
if(INPUT.length() != 0) {
for (long[] r : b) {
for (long x : r) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
System.out.println();
}
}
public void tf(long... b)
{
if(INPUT.length() != 0) {
for (long x : b) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Random;
import java.util.TreeSet;
/**
* Actual solution is at the top, in class Solver
*/
final public class Main implements Runnable {
private static String[] args;
public static void main(String[] args) {
Main.args = args;
new Thread(null, new Main(), "MyRunThread", 1 << 27).start();
}
//@Override
public void run() {
long time_beg = -1;
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
if (args.length > 0 && args[0].equals("outside")) {
time_beg = System.currentTimeMillis();
try {
inputStream = new FileInputStream("IO/in.txt");
// outputStream = new FileOutputStream("IO/out.txt");
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
} else {
try {
// inputStream = new FileInputStream("IO/in.txt");
// outputStream = new FileOutputStream("IO/out.txt");
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
}
Solver s = new Solver();
s.in = new InputReader(inputStream);
s.out = new OutputWriter(outputStream);
if (args.length > 0 && args[0].equals("outside")) {
s.dout = new DebugWriter(s.out);
}
s.solve();
if (args.length > 0 && args[0].equals("outside")) {
s.dout.printFormat("*** Total time: %.3f ***\n", (System.currentTimeMillis() - time_beg) / 1000.0);
}
s.out.close();
}
}
final class Solver {
InputReader in;
OutputWriter out;
DebugWriter dout;
public void solve() {
int n = in.readInt();
int k = in.readInt();
TreeSet<Integer> q = new TreeSet<Integer>();
int[] mas = new int[n];
for (int i = 0; i < n; ++i) {
mas[i] = in.readInt();
if (mas[i] % k != 0)
q.add(mas[i]);
}
// SequenceUtils.quickSort(mas);
Arrays.sort(mas);
for (int i = 0; i < n; ++i)
if (mas[i] % k == 0 && !q.contains(mas[i] / k))
q.add(mas[i]);
out.printLine(q.size());
}
}
final class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1 << 10];
private int curChar;
private int 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 peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
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();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public 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 == '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 boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
}
final class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream), 1 << 10));
}
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 printFormat(String format, Object... objects) {
writer.printf(format, objects);
}
public void print(char[] objects) {
writer.print(objects);
}
public void printLine(char[] objects) {
writer.println(objects);
}
public void printLine(char[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void print(int[] objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(int[] objects) {
print(objects);
writer.println();
}
public void printLine(int[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void print(short[] objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(short[] objects) {
print(objects);
writer.println();
}
public void printLine(short[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void print(long[] objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(long[] objects) {
print(objects);
writer.println();
}
public void printLine(long[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void print(double[] objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(double[] objects) {
print(objects);
writer.println();
}
public void printLine(double[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void print(byte[] objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(byte[] objects) {
print(objects);
writer.println();
}
public void printLine(byte[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void print(boolean[] objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(boolean[] objects) {
print(objects);
writer.println();
}
public void printLine(boolean[][] objects) {
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
final class DebugWriter {
private final OutputWriter writer;
public DebugWriter(OutputWriter writer) {
this.writer = writer;
}
private void printDebugMessage() {
writer.print("DEBUG:\t");
}
public void printLine(Object... objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printFormat(String format, Object... objects) {
flush();
printDebugMessage();
writer.printFormat(format, objects);
flush();
}
public void printLine(char[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(char[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void printLine(double[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(double[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void printLine(int[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(int[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void printLine(short[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(short[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void printLine(long[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(long[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void printLine(byte[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(byte[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void printLine(boolean[] objects) {
flush();
printDebugMessage();
writer.printLine(objects);
flush();
}
public void printLine(boolean[][] objects) {
flush();
for (int i = 0; i < objects.length; ++i)
printLine(objects[i]);
flush();
}
public void flush() {
writer.flush();
}
}
interface Graph {
// add vertexes
public void addVertexes(int amount);
// add edge
public void addEdge(int source, int destination, boolean directed);
public void addEdge(int source, int destination, boolean directed, long weight);
public void addEdge(int source, int destination, long capacity);
public void addEdge(int source, int destination, long weight, long capacity);
// iterate through incident edges
public int getFirstEdge(int source);
public boolean hasNextEdge(int id);
public int getNextEdge(int id);
// graph info
public int getVertexCount();
public int getEdgeCount();
public void show(DebugWriter writer);
// simple edge info
public int getSource(int id);
public int getDestination(int id);
public int getColor(int id);
public void setColor(int id, int color);
public boolean hasReverseEdge(int id);
public int getReverseEdge(int id);
public String edgeToString(int id);
// weighted edge info
public long getWeight(int id);
public void setWeight(int id, long weight);
// flow edge info
public long getCapacity(int id);
public void addCapacity(int id, long capacity);
public long getFlow(int id);
public void pushFlow(int id, long flow);
}
class GraphSimple implements Graph {
protected int[] firstEdge;
protected int[] nextEdge;
protected int vertexCount = 0;
protected int edgeCount = 0;
protected int[] reverseEdge;
protected int[] source;
protected int[] destination;
protected int[] color;
public GraphSimple() {
this(16, 16);
}
public GraphSimple(int vertexCapacity, int edgeCapacity) {
firstEdge = new int[vertexCapacity];
nextEdge = new int[edgeCapacity];
reverseEdge = new int[edgeCapacity];
source = new int[edgeCapacity];
destination = new int[edgeCapacity];
color = new int[edgeCapacity];
}
protected void ensureVertexCapacity(int size) {
}
protected void ensureEdgeCapacity(int size) {
}
// add vertexes
@Override
public void addVertexes(int amount) {
ensureVertexCapacity(vertexCount + amount);
for (int i = 0; i < amount; ++i)
firstEdge[i + vertexCount] = -1;
vertexCount += amount;
}
// add edge
@Override
public void addEdge(int source, int destination, boolean directed) {
if (source >= vertexCount || destination >= vertexCount)
throw new ArrayIndexOutOfBoundsException("wrong vertex's number");
ensureEdgeCapacity(edgeCount + 2);
nextEdge[edgeCount] = firstEdge[source];
firstEdge[source] = edgeCount;
this.source[edgeCount] = source;
this.destination[edgeCount] = destination;
this.color[edgeCount] = -1;
if (directed) reverseEdge[edgeCount++] = -1;
else {
reverseEdge[edgeCount] = edgeCount + 1;
++edgeCount;
nextEdge[edgeCount] = firstEdge[destination];
firstEdge[destination] = edgeCount;
this.source[edgeCount] = destination;
this.destination[edgeCount] = source;
this.color[edgeCount] = -1;
reverseEdge[edgeCount] = edgeCount - 1;
++edgeCount;
}
}
@Override
public void addEdge(int source, int destination, boolean directed, long weight) {
throw new UnsupportedOperationException();
}
@Override
public void addEdge(int source, int destination, long capacity) {
throw new UnsupportedOperationException();
}
@Override
public void addEdge(int source, int destination, long weight, long capacity) {
throw new UnsupportedOperationException();
}
// iterate through incident edges
@Override
public int getFirstEdge(int source) {
if (source >= vertexCount)
throw new ArrayIndexOutOfBoundsException("wrong vertex's number");
return firstEdge[source];
}
@Override
public boolean hasNextEdge(int id) {
return id != -1;
}
@Override
public int getNextEdge(int id) {
return nextEdge[id];
}
// graph info
@Override
public int getVertexCount() {
return vertexCount;
}
@Override
public int getEdgeCount() {
return edgeCount;
}
@Override
public void show(DebugWriter writer) {
writer.printLine("Graph:");
for (int i = 0; i < getVertexCount(); ++i) {
writer.printLine("\tincident to vertex [" + i + "]: ");
for (int id = getFirstEdge(i); hasNextEdge(id); id = getNextEdge(id))
writer.printLine("\t\t" + edgeToString(id));
}
}
// simple edge info
@Override
public int getSource(int id) {
return source[id];
}
@Override
public int getDestination(int id) {
return destination[id];
}
@Override
public int getColor(int id) {
return color[id];
}
@Override
public void setColor(int id, int color) {
this.color[id] = color;
}
@Override
public boolean hasReverseEdge(int id) {
return reverseEdge[id] != -1;
}
@Override
public int getReverseEdge(int id) {
if (reverseEdge[id] == -1)
throw new NoSuchFieldError();
return reverseEdge[id];
}
@Override
public String edgeToString(int id) {
return "<(" + getSource(id) + " -> " + getDestination(id) + ") color : " + getColor(id) + ">";
}
// weighted edge info
@Override
public long getWeight(int id) {
throw new UnsupportedOperationException();
}
@Override
public void setWeight(int id, long weight) {
throw new UnsupportedOperationException();
}
// flow edge info
@Override
public long getCapacity(int id) {
throw new UnsupportedOperationException();
}
@Override
public void addCapacity(int id, long capacity) {
throw new UnsupportedOperationException();
}
@Override
public long getFlow(int id) {
throw new UnsupportedOperationException();
}
@Override
public void pushFlow(int id, long flow) {
throw new UnsupportedOperationException();
}
}
abstract class SequenceUtils {
// swap
public final static <T> void swap(List<T> sequence, int j, int i) {
T tmp = sequence.get(j);
sequence.set(j, sequence.get(i));
sequence.set(i, tmp);
}
public final static <T> void swap(T[] sequence, int j, int i) {
T tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(int[] sequence, int j, int i) {
int tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(long[] sequence, int j, int i) {
long tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(char[] sequence, int j, int i) {
char tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(double[] sequence, int j, int i) {
double tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(boolean[] sequence, int j, int i) {
boolean tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(short[] sequence, int j, int i) {
short tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
public final static void swap(byte[] sequence, int j, int i) {
byte tmp = sequence[j];
sequence[j] = sequence[i];
sequence[i] = tmp;
}
// reverse
public final static <T> void reverse(List<T> sequence) {
for (int left = 0, right = sequence.size() - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static <T> void reverse(T[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(int[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(long[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(char[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(double[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(boolean[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(short[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
public final static void reverse(byte[] sequence) {
for (int left = 0, right = sequence.length - 1; left < right; ++left, --right)
swap(sequence, left, right);
}
// next permutation
public final static <T extends Comparable<T>> boolean nextPermutation(List<T> sequence) {
for (int j = sequence.size() - 2; j >= 0; --j) {
if (sequence.get(j).compareTo(sequence.get(j + 1)) < 0) {
reverse(sequence.subList(j + 1, sequence.size()));
for (int i = j + 1; i < sequence.size(); ++i)
if (sequence.get(j).compareTo(sequence.get(i)) < 0) {
swap(sequence, j, i);
return true;
}
}
}
return false;
}
public final static <T> boolean nextPermutation(List<T> sequence, Comparator<T> comparator) {
for (int j = sequence.size() - 2; j >= 0; --j) {
if (comparator.compare(sequence.get(j), sequence.get(j + 1)) < 0) {
reverse(sequence.subList(j + 1, sequence.size()));
for (int i = j + 1; i < sequence.size(); ++i)
if (comparator.compare(sequence.get(j), sequence.get(i)) < 0) {
swap(sequence, j, i);
return true;
}
}
}
return false;
}
// random shuffle
public final static <T> void shuffle(List<T> sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.size(); ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static <T> void shuffle(T[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(int[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(long[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(char[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(double[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(boolean[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(short[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
public final static void shuffle(byte[] sequence) {
Random random = new Random(System.nanoTime());
for (int i = 1; i < sequence.length; ++i)
swap(sequence, random.nextInt(i + 1), i);
}
// merge sort
public final static <T extends Comparable<T>> void mergeSort(List<T> sequence) {
int n = sequence.size();
T[] tmp = (T[]) new Object[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence.get(i);
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static <T extends Comparable<T>> void merge(List<T> sequence, T[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence.set(i, tmp[pRight++]);
else if (pRight > right) sequence.set(i, tmp[pLeft++]);
else if (tmp[pLeft].compareTo(tmp[pRight]) <= 0) sequence.set(i, tmp[pLeft++]);
else sequence.set(i, tmp[pRight++]);
}
public final static <T> void mergeSort(List<T> sequence, Comparator<T> comparator) {
int n = sequence.size();
T[] tmp = (T[]) new Object[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence.get(i);
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1), comparator);
}
}
private final static <T> void merge(List<T> sequence, T[] tmp, int left, int mid, int right, Comparator<T> comparator) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence.set(i, tmp[pRight++]);
else if (pRight > right) sequence.set(i, tmp[pLeft++]);
else if (comparator.compare(tmp[pLeft], tmp[pRight]) <= 0) sequence.set(i, tmp[pLeft++]);
else sequence.set(i, tmp[pRight++]);
}
public final static void mergeSort(int[] sequence) {
int n = sequence.length;
int[] tmp = new int[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(int[] sequence, int[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (tmp[pLeft] <= tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
public final static void mergeSort(long[] sequence) {
int n = sequence.length;
long[] tmp = new long[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(long[] sequence, long[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (tmp[pLeft] <= tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
public final static void mergeSort(char[] sequence) {
int n = sequence.length;
char[] tmp = new char[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(char[] sequence, char[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (tmp[pLeft] <= tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
public final static void mergeSort(double[] sequence) {
int n = sequence.length;
double[] tmp = new double[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(double[] sequence, double[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (tmp[pLeft] <= tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
public final static void mergeSort(boolean[] sequence) {
int n = sequence.length;
boolean[] tmp = new boolean[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(boolean[] sequence, boolean[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (!tmp[pLeft] || tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
public final static void mergeSort(short[] sequence) {
int n = sequence.length;
short[] tmp = new short[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(short[] sequence, short[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (tmp[pLeft] <= tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
public final static void mergeSort(byte[] sequence) {
int n = sequence.length;
byte[] tmp = new byte[n];
for (int step = 1; step < n; step *= 2) {
for (int i = 0; i < n; ++i)
tmp[i] = sequence[i];
for (int i = 0; i + step < n; i += 2 * step)
merge(sequence, tmp, i, i + step - 1, Math.min(i + step * 2 - 1, n - 1));
}
}
private final static void merge(byte[] sequence, byte[] tmp, int left, int mid, int right) {
int pLeft = left;
int pRight = mid + 1;
for (int i = left; i <= right; ++i)
if (pLeft > mid) sequence[i] = tmp[pRight++];
else if (pRight > right) sequence[i] = tmp[pLeft++];
else if (tmp[pLeft] <= tmp[pRight]) sequence[i] = tmp[pLeft++];
else sequence[i] = tmp[pRight++];
}
// quick sort
public final static <T> void quickSort(List<T> sequence, Comparator<T> comparator) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.size() - 1, comparator);
}
private final static <T> void quickSortImplementation(List<T> sequence, int left, int right, Comparator<T> comparator) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
T value = sequence.get(left);
while (i <= greaterThen) {
int cmp = comparator.compare(sequence.get(i), value);
if (cmp < 0) swap(sequence, i++, lessThen++);
else if (cmp > 0) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1, comparator);
quickSortImplementation(sequence, greaterThen + 1, right, comparator);
}
public final static <T extends Comparable<T>> void quickSort(List<T> sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.size() - 1);
}
private final static <T extends Comparable<T>> void quickSortImplementation(List<T> sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
T value = sequence.get(left);
while (i <= greaterThen) {
int cmp = sequence.get(i).compareTo(value);
if (cmp < 0) swap(sequence, i++, lessThen++);
else if (cmp > 0) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(int[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(int[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
int value = sequence[left];
while (i <= greaterThen) {
if (sequence[i] < value) swap(sequence, i++, lessThen++);
else if (sequence[i] > value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(long[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(long[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
long value = sequence[left];
while (i <= greaterThen) {
if (sequence[i] < value) swap(sequence, i++, lessThen++);
else if (sequence[i] > value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(char[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(char[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
char value = sequence[left];
while (i <= greaterThen) {
if (sequence[i] < value) swap(sequence, i++, lessThen++);
else if (sequence[i] > value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(double[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(double[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
double value = sequence[left];
while (i <= greaterThen) {
if (sequence[i] < value) swap(sequence, i++, lessThen++);
else if (sequence[i] > value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(boolean[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(boolean[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
boolean value = sequence[left];
while (i <= greaterThen) {
if (!sequence[i] && value) swap(sequence, i++, lessThen++);
else if (sequence[i] && !value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(short[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(short[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
short value = sequence[left];
while (i <= greaterThen) {
if (sequence[i] < value) swap(sequence, i++, lessThen++);
else if (sequence[i] > value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
public final static void quickSort(byte[] sequence) {
shuffle(sequence);
quickSortImplementation(sequence, 0, sequence.length - 1);
}
private final static void quickSortImplementation(byte[] sequence, int left, int right) {
if (left >= right) return;
int lessThen = left;
int greaterThen = right;
int i = left;
byte value = sequence[left];
while (i <= greaterThen) {
if (sequence[i] < value) swap(sequence, i++, lessThen++);
else if (sequence[i] > value) swap(sequence, i, greaterThen--);
else ++i;
}
quickSortImplementation(sequence, left, lessThen - 1);
quickSortImplementation(sequence, greaterThen + 1, right);
}
// unique
public static <T> ArrayList<T> unique(ArrayList<T> sequence) {
int size = 1;
for (int i = 1; i < sequence.size(); ++i)
if (!sequence.get(i).equals(sequence.get(i - 1)))
++size;
ArrayList<T> newSequence = new ArrayList<T>(size);
newSequence.add(sequence.get(0));
for (int i = 1; i < sequence.size(); ++i)
if (!sequence.get(i).equals(sequence.get(i - 1)))
newSequence.add(sequence.get(i));
return newSequence;
}
public static <T> T[] unique(T[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (!sequence[i].equals(sequence[i - 1]))
++size;
T[] newSequence = (T[]) new Object[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (!sequence[i].equals(sequence[i - 1]))
newSequence[++size] = sequence[i];
return newSequence;
}
public static int[] unique(int[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
int[] newSequence = new int[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
public static long[] unique(long[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
long[] newSequence = new long[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
public static char[] unique(char[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
char[] newSequence = new char[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
public static double[] unique(double[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
double[] newSequence = new double[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
public static boolean[] unique(boolean[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
boolean[] newSequence = new boolean[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
public static short[] unique(short[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
short[] newSequence = new short[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
public static byte[] unique(byte[] sequence) {
int size = 1;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
++size;
byte[] newSequence = new byte[size];
newSequence[0] = sequence[0];
size = 0;
for (int i = 1; i < sequence.length; ++i)
if (sequence[i] != sequence[i - 1])
newSequence[++size] = sequence[i];
return newSequence;
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.io.* ;
import java.util.*;
import static java.lang.Math.* ;
import static java.util.Arrays.* ;
public class A {
public static void main(String[] args) throws IOException {
new A().solveProblem();
out.close();
}
static Scanner in = new Scanner(new InputStreamReader(System.in));
//static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static PrintStream out = new PrintStream(new BufferedOutputStream(System.out));
public void solveProblem() {
int n = in.nextInt() ;
E[] get = new E[n] ;
for( int i = 0 ; i < n ; i++ ){
get[i] = new E(i,in.nextInt()) ;
}
sort(get) ;
if( get[n-1].g == 1){
get[n-1].g = 2 ;
}else{
get[n-1].g = 1 ;
}
sort(get) ;
for( int i = 0 ; i < n - 1 ; i++ )
out.print(get[i].g +" " ) ;
out.println(get[n-1].g) ;
}
class E implements Comparable<E>{
int g ;
int index ;
public E( int index, int g){
this.g = g ;
this.index = index ;
}
public int compareTo( E e){
return g - e.g ;
}
}
static int[] readGet( int n ){
int[] get = new int[n] ;
for( int i = 0 ; i < n ; i++ )
get[i] = in.nextInt();
return get ;
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
public class A {
public static void main(String[] args) throws Exception {
int n = nextInt(), b = nextInt(), a = nextInt();
int[] mas = new int[n];
for(int i = 0; i<n; i++) {
mas[i] = nextInt();
}
Arrays.sort(mas);
if(mas[a - 1] == mas[a]) {
exit(0);
}
println(mas[a] - mas[a-1]);
}
/////////////////////////////////////////////////////////////////
// IO
/////////////////////////////////////////////////////////////////
private static StreamTokenizer in;
private static PrintWriter out;
private static BufferedReader inB;
private static boolean FILE=false;
private static int nextInt() throws Exception{
in.nextToken();
return (int)in.nval;
}
private static String nextString() throws Exception{
in.nextToken();
return in.sval;
}
static{
try {
out = new PrintWriter(FILE ? (new FileOutputStream("output.txt")) : System.out);
inB = new BufferedReader(new InputStreamReader(FILE ? new FileInputStream("input.txt") : System.in));
} catch(Exception e) {e.printStackTrace();}
in = new StreamTokenizer(inB);
}
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
// pre - written
/////////////////////////////////////////////////////////////////
private static void println(Object o) throws Exception {
out.println(o);
out.flush();
}
private static void exit(Object o) throws Exception {
println(o);
exit();
}
private static void exit() {
System.exit(0);
}
private static final int INF = Integer.MAX_VALUE;
private static final int MINF = Integer.MIN_VALUE;
//////////////////////////////////////////////////////////////////
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.AbstractList;
import java.io.Writer;
import java.util.List;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Egor Kulikov (egor@egork.net)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int size = in.readInt();
int[] array = IOUtils.readIntArray(in, size);
Arrays.sort(array);
if (array[size - 1] == 1)
array[size - 1] = 2;
else
array[size - 1] = 1;
Arrays.sort(array);
out.printLine(Array.wrap(array).toArray());
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
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 static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(outputStream);
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
abstract class Array<T> extends AbstractList<T> {
public static List<Integer> wrap(int...array) {
return new IntArray(array);
}
protected static class IntArray extends Array<Integer> {
protected final int[] array;
protected IntArray(int[] array) {
this.array = array;
}
public int size() {
return array.length;
}
public Integer get(int index) {
return array[index];
}
public Integer set(int index, Integer value) {
int result = array[index];
array[index] = value;
return result;
}
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Aman Kumar Singh
*/
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);
BSportMafia solver = new BSportMafia();
solver.solve(1, in, out);
out.close();
}
static class BSportMafia {
int MAXN = 200005;
PrintWriter out;
InputReader in;
public void solve(int testNumber, InputReader in, PrintWriter out) {
this.out = out;
this.in = in;
long n = nl();
long k = nl();
long i = 0;
k += n;
for (i = 0; i < MAXN; i++) {
long x = (i * (i + 3)) / 2;
if (k == x) {
pn(n - i);
return;
}
}
}
long nl() {
return in.nextLong();
}
void pn(long zx) {
out.println(zx);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new UnknownError();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public long nextLong() {
return Long.parseLong(next());
}
public String next() {
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;
}
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
int INF = Integer.MAX_VALUE >> 1;
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
/* Input */
int x0 = nextInt();
int y0 = nextInt();
int N = nextInt();
int FULL_MASK = (1 << N) - 1;
int[] xs = new int [N];
int[] ys = new int [N];
for (int i = 0; i < N; i++) {
xs[i] = nextInt();
ys[i] = nextInt();
}
/* Precalc */
int[][] dist = new int [N][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
dist[i][j] = dist(x0, y0, xs[i], ys[i]) + dist(xs[i], ys[i], xs[j], ys[j]) + dist(xs[j], ys[j], x0, y0);
/* DP */
int[] dp = new int [1 << N];
int[] pr = new int [1 << N];
Arrays.fill(dp, INF);
dp[0] = 0;
for (int mask = 0; mask < FULL_MASK; mask++) {
int i = Integer.numberOfTrailingZeros(~mask); // hack: use first non-zero bit
int imask = mask | (1 << i);
for (int j = i; j < N; j++) {
int jmask = mask | (1 << j);
if (jmask == mask) continue;
int ijmask = imask | jmask;
int nval = dp[mask] + dist[i][j];
if (dp[ijmask] > nval) {
dp[ijmask] = nval;
pr[ijmask] = mask;
}
}
}
/* Output */
out.println(dp[FULL_MASK]);
out.print("0");
for (int mask = FULL_MASK; mask != 0; mask = pr[mask]) {
int diff = mask ^ pr[mask];
int i = Integer.numberOfTrailingZeros(diff);
diff &= ~(1 << i);
int j = Integer.numberOfTrailingZeros(diff);
if (i != 32) out.print(" " + (i + 1));
if (j != 32) out.print(" " + (j + 1));
out.print(" 0");
}
out.println();
out.close();
}
/***************************************************************
* Utility
**************************************************************/
int dist(int x1, int y1, int x2, int y2) {
return sqr(x2 - x1) + sqr(y2 - y1);
}
int sqr(int x) {
return x * x;
}
/***************************************************************
* Input
**************************************************************/
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static Scanner scan = new Scanner(System.in);
public static boolean bg = true;
public static void main(String[] args) throws Exception {
String k1 = scan.next();
HashSet<String> met = new HashSet();
String ans = "";
for (int i=1;i<=k1.length()-1;i++){
for (int j=0;j+i<=k1.length();j++){
String cur = k1.substring(j, j+i);
if (!met.contains(cur)){
met.add(cur);
}
else {
if (cur.length()>ans.length())ans=cur;
}
}
}
System.out.println(ans.length());
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
/*************************************************************************
* Compilation: javac LRS.java
* Execution: java LRS < file.txt
* Dependencies: StdIn.java
*
* Reads a text corpus from stdin, replaces all consecutive blocks of
* whitespace with a single space, and then computes the longest
* repeated substring in that corpus. Suffix sorts the corpus using
* the system sort, then finds the longest repeated substring among
* consecutive suffixes in the sorted order.
*
* % java LRS < mobydick.txt
* ',- Such a funny, sporty, gamy, jesty, joky, hoky-poky lad, is the Ocean, oh! Th'
*
* % java LRS
* aaaaaaaaa
* 'aaaaaaaa'
*
* % java LRS
* abcdefg
* ''
*
*************************************************************************/
import java.util.Arrays;
public class LRS {
// return the longest common prefix of s and t
public static String lcp(String s, String t) {
int n = Math.min(s.length(), t.length());
for (int i = 0; i < n; i++) {
if (s.charAt(i) != t.charAt(i))
return s.substring(0, i);
}
return s.substring(0, n);
}
// return the longest repeated string in s
public static String lrs(String s) {
// form the N suffixes
int N = s.length();
String[] suffixes = new String[N];
for (int i = 0; i < N; i++) {
suffixes[i] = s.substring(i, N);
}
// sort them
Arrays.sort(suffixes);
// find longest repeated substring by comparing adjacent sorted suffixes
String lrs = "";
for (int i = 0; i < N - 1; i++) {
String x = lcp(suffixes[i], suffixes[i+1]);
if (x.length() > lrs.length())
lrs = x;
}
return lrs;
}
// read in text, replacing all consecutive whitespace with a single space
// then compute longest repeated substring
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
s = s.replaceAll("\\s+", " ");
System.out.println(lrs(s).length());
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x111C
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int R = Integer.parseInt(st.nextToken());
int C = Integer.parseInt(st.nextToken());
if(R > C)
{
int t = R;
R = C;
C = t;
}
//dp[c][m1][m2] = min spoders in first c columns
int[][][] dp = new int[C+1][1 << R][1 << R];
for(int i=0; i <= C; i++)
for(int mask=0; mask < (1<<R); mask++)
Arrays.fill(dp[i][mask], 69);
for(int mask=0; mask < (1<<R); mask++)
dp[0][0][mask] = 0;
for(int c=1; c <= C; c++)
for(int mask1=0; mask1 < (1<<R); mask1++)
for(int mask2=0; mask2 < (1<<R); mask2++)
for(int mask3=0; mask3 < (1<<R); mask3++)
{
boolean works = true;
for(int b=0; b < R; b++)
if((mask2&(1<<b)) == 0)
{
if(b > 0 && (mask2&(1<<(b-1))) > 0);
else if(b+1 < R && (mask2&(1<<(b+1))) > 0);
else if((mask1&(1<<b)) > 0);
else if((mask3&(1<<b)) > 0);
else works = false;
}
if(works)
dp[c][mask2][mask3] = Math.min(dp[c][mask2][mask3], dp[c-1][mask1][mask2]+Integer.bitCount(mask1));
}
int res = 0;
for(int mask=0; mask < (1<<R); mask++)
res = Math.max(res, R*C-(dp[C][mask][0]+Integer.bitCount(mask)));
System.out.println(res);
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class oK{
void pre() throws Exception{}
void solve(int TC) throws Exception{
int n=ni();
int a[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=ni();
}
Arrays.sort(a);
int b[]=new int[101];
int flag=0;
int count=0;
for(int i=0;i<n;i++) {
flag=0;
if(b[a[i]]==0) {
count++;
}
for(int j=i;j<n;j++) {
if(b[a[j]]==0&&a[j]%a[i]==0) {
b[a[j]]=1;
}
//if(flag==1)count++;
}
}
pn(count);
}
// void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
static boolean multipleTC = false, memory = false;
FastReader in;PrintWriter out;
void run() throws Exception{
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC)?ni():1;
pre();for(int t = 1; t<= T; t++)solve(t);
out.flush();
out.close();
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new oK().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new oK().run();
}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str = "";
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.awt.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.List;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long n = scanner.nextLong();
long x = scanner.nextLong(), y = scanner.nextLong();
long whiteSteps, blackSteps;
if(x == 1 || y == 1){
whiteSteps = (x - 1) + (y - 1);
} else {
whiteSteps = Math.min((x - 1) + Math.abs(y - x), (y - 1) + Math.abs(y - x));
}
if(x == n || y == n){
blackSteps = (n - x) + (n - y);
} else {
blackSteps = Math.min((n - x) + Math.abs(y - x), (n - y) + Math.abs(y - x));
}
if (whiteSteps <= blackSteps){
System.out.println("White");
} else {
System.out.println("Black");
}
}
}
|
constant
|
1075_A. The King's Race
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
/**
* @author Mubtasim Shahriar
*/
public class Cgr14 {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
int t = sc.nextInt();
// int t = 1;
while (t-- != 0) {
solver.solve(sc, out);
}
out.close();
}
static class Solver {
public void solve(InputReader sc, PrintWriter out) {
long n = sc.nextInt();
long l = 1;
long r = (long)1e5;
while(l<=r) {
long mid = (l+r)/2;
long needed = (mid*mid)*2;
if(needed==n) {
out.println("YES");
return;
}
if(needed>n) {
r = mid-1;
} else {
l = mid+1;
}
}
l = 1;
r = (long)1e5;
while(l<=r) {
long mid = (l+r)/2;
long needed = (mid*mid)*4;
if(needed==n) {
out.println("YES");
return;
}
if(needed>n) {
r = mid-1;
} else {
l = mid+1;
}
}
out.println("NO");
}
}
static void sort(int[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
}
static void sort(long[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
}
static void sortDec(int[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
int l = 0;
int r = n - 1;
while (l < r) {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
l++;
r--;
}
}
static void sortDec(long[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i) continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
int l = 0;
int r = n - 1;
while (l < r) {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
l++;
r--;
}
}
static class InputReader {
private boolean finished = false;
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 peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
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 boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int[] nextSortedIntArray(int n) {
int array[] = nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n) {
int[] array = new int[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public long[] nextSumLongArray(int n) {
long[] array = new long[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextSortedLongArray(int n) {
long array[] = nextLongArray(n);
Arrays.sort(array);
return array;
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* User: alms
* Date: 09.07.2010
* Time: 18:57:44
*/
public class Solution {
public static void main(String[] args) throws Exception {
final String str;
final BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
str = r.readLine();
int max = 0;
for (int x = 0; x < str.length(); x++) {
for (int y = x + 1; y < str.length(); y++) {
int c = 0;
for (;c + x < str.length() && y + c < str.length(); c++) {
if (str.charAt(x + c) != str.charAt(y + c)) {
break;
}
}
if (c > max) {
max = c;
}
}
}
System.out.println(max);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class lucky
{
public static void main(String args[]) throws IOException
{
BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));
String s=cin.readLine();
int l=s.length();
int n=Integer.parseInt(s);
if(s.equals("47") || s.equals("4") || s.equals("7") || s.equals("74") || s.equals("447") || s.equals("477") || s.equals("474") || s.equals("44") || s.equals("77") || s.equals("444") || s.equals("777") || s.equals("747") || s.equals("774") || s.equals("744"))
System.out.println("YES");
else if(n%(47)==0 || n%(4)==0 || n%(7)==0 || n%(74)==0 || n%(447)==0 || n%(477)==0 || n%(474)==0 || n%(44)==0 || n%(77)==0 || n%(444)==0 || n%(777)==0 || n%(747)==0 || n%(774)==0 || n%(744)==0)
System.out.println("YES");
else
System.out.println("NO");
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution {
static class Data{
int x,i;
Data(int x,int i){
this.x = x;
this.i = i;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split("\\s");
int N = Integer.parseInt(s[0]);
int K = Integer.parseInt(s[1]);
s = br.readLine().split("\\s");
int[] arr = new int[N];
for(int i=0;i<N;++i) arr[i] = Integer.parseInt(s[i]);
solve(N,K,arr);
}
private static void solve(int N,int K,int[] arr){
PriorityQueue<Data> pq = new PriorityQueue<Data>(2000,(a,b) -> a.x - b.x == 0 ? b.i - a.i : b.x - a.x);
for(int i=0;i<arr.length;++i){
pq.offer(new Data(arr[i],i));
}
int tot_sum = 0;
List<Integer> ls = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for(int i=1;i<=K;++i){
Data t = pq.poll();
tot_sum += t.x;
set.add(t.i);
}
int last = -1;
for(int i =0;i<arr.length;++i){
if(set.contains(i)){
K--;
//System.out.println(i);
if(K == 0) ls.add(arr.length-last-1);
else ls.add(i-last);
last = i;
}
}
System.out.println(tot_sum);
int size = ls.size();
for(int i=0;i<size;++i){
System.out.print(ls.get(i) + " ");
}
}
}
|
nlogn
|
1006_B. Polycarp's Practice
|
CODEFORCES
|
import java.io.*;
import java.util.regex.*;
public class Main {
private static String encode(long rowNum) {
if(rowNum<=26) {
return String.valueOf((char)('A'+rowNum-1));
}
else {
if(rowNum%26==0){
return encode((long)Math.floor((double)rowNum/26)-1)
+ String.valueOf((char)('A'+26-1));
}
else {
return encode((long)Math.floor((double)rowNum/26))
+ String.valueOf((char)('A'+rowNum%26-1));
}
}
}
private static long decode(String rowNum){
long result = 0;
char rowChars[] = rowNum.toCharArray();
for(int i=rowChars.length-1;i>=0;i--){
result+= (rowChars[i]-'A'+1) * (long)Math.pow(26,rowChars.length-i-1);
}
return result;
}
public static void main(String arg[])throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
Pattern p1 = Pattern.compile("R\\d+C\\d+");
Pattern p2 = Pattern.compile("\\d+");
for(int i=0;i<t;i++){
String input = in.readLine();
Matcher m1 = p1.matcher(input);
Matcher m2 = p2.matcher(input);
if(m1.matches()){
String result = "";
if(m2.find()){
result = m2.group();
}
if(m2.find()){
result = encode(Long.parseLong(m2.group()))+result;
}
System.out.println(result);
}
else {
String result = "R";
if(m2.find()){
result += m2.group();
}
result += "C";
System.out.println(result+decode(input.replaceAll(m2.group(),"")));
}
}
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.util.Scanner;
public class Word {
static String word;
private static void check(String subword) {
int i = 0;
int j = 0;
while (j + subword.length() <= word.length()) {
if (word.substring(j).startsWith(subword)){
i++;
}
j++;
}
if (i > 1){
System.out.println(subword.length());
System.exit(0);
}
}
public static void main(String[] arg) {
Scanner in = new Scanner(System.in);
word = in.next();
if (word.length() == 1) {
System.out.println(0);
return;
}
for (int i = word.length() - 1; i > 0; i--) {
int j = 0;
while (j + i <= word.length()) {
check(word.substring(j, i+j));
j++;
}
}
System.out.println(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
BufferedReader in = null;
PrintWriter out = null;
int dist(int x1, int y1, int x2, int y2) {
int dx = Math.abs(x1 - x2);
int dy = Math.abs(y1 - y2);
return dx * dx + dy * dy;
}
boolean testBit(int use, int p) {
return ((use >> p) & 1) == 1;
}
int rec(int use, int a[][], int dp[], int next[]) {
if (dp[use] != -1) {
return dp[use];
}
if (use == 0) {
return dp[use] = 0;
}
int n = a.length;
int ix = -1;
for (int i = 0; i < n; ++i) {
if (testBit(use, i)) {
if (ix == -1) {
ix = i;
break;
}
/*
int t = rec(use ^ (1 << i), a, dp);
t += a[i][i];
r = Math.min(r, t);*/
}
}
int r = rec(use ^ (1 << ix), a, dp, next) + a[ix][ix];
next[use] = use ^ (1 << ix);
for (int i = ix + 1; i < n; ++i) {
if (!testBit(use, i)) {
continue;
}
int t = rec(use ^ (1 << ix) ^ (1 << i), a, dp, next);
t += a[ix][i];
if (t < r) {
r = t;
next[use] = use ^ (1 << ix) ^ (1 << i);
}
}
return dp[use] = r;
}
void print(int use1, int use2, int n) {
for (int i = 0; i < n; ++i) {
if (testBit(use1, i) ^ testBit(use2, i)) {
int x = i + 1;
out.print(x + " ");
}
}
}
void solve() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
//in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(System.out);
StringTokenizer st;
st = new StringTokenizer(in.readLine());
int sx = Integer.valueOf(st.nextToken());
int sy = Integer.valueOf(st.nextToken());
st = new StringTokenizer(in.readLine());
int n = Integer.valueOf(st.nextToken());
int x[] = new int[n];
int y[] = new int[n];
for (int i = 0; i < n; ++i) {
st = new StringTokenizer(in.readLine());
x[i] = Integer.valueOf(st.nextToken());
y[i] = Integer.valueOf(st.nextToken());
}
int a[][] = new int[n][n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
a[i][j] = dist(x[i], y[i], sx, sy) + dist(x[j], y[j], sx, sy) + dist(x[i], y[i], x[j], y[j]);
}
}
int dp[] = new int[1 << n];
Arrays.fill(dp, -1);
int next[] = new int[1 << n];
int ans = rec((1 << n) - 1, a, dp, next);
out.println(ans);
int use = (1 << n) - 1;
while (true) {
int nuse = next[use];
out.print("0 ");
print(use, nuse, n);
if (nuse == 0) break;
use = nuse;
}
out.println("0");
in.close();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().solve();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class E {
static long mod;
static long[][] dp;
static int n;
static long[] nWaysToPlaceGroupOfSize;
public static void main(String[] args) {
FastScanner fs=new FastScanner();
n=fs.nextInt();
mod=fs.nextInt();
precomp();
dp=new long[n+1][n+1];
for (int i=0; i<dp.length; i++) Arrays.fill(dp[i], -1);
long ans=0;
for (int nXsLeft=2; nXsLeft<=n; nXsLeft++) {
long curAns=go(0, nXsLeft);
ans=add(ans, curAns);
}
System.out.println(ans);
}
static long go(int position, int nXsLeft) {
if (position==n) {
//last thing was skipped, impossible
return 0;
}
if (position==n+1) {
//last thing was included, 1 way of doing that
if (nXsLeft==0) return 1;
return 0;
}
if (dp[position][nXsLeft]!=-1) {
return dp[position][nXsLeft];
}
//TODO: brute force number of xs to place
long ways=0;
for (int nPlace=1; nPlace<=Math.min(nXsLeft, n-position); nPlace++) {
long futureWays=go(position+nPlace+1, nXsLeft-nPlace);
long waysToPlaceMe=nCk(nXsLeft, nPlace);
if (nPlace>1) waysToPlaceMe=mul(waysToPlaceMe, nWaysToPlaceGroupOfSize[nPlace]);
ways=add(ways, mul(waysToPlaceMe, futureWays));
}
return dp[position][nXsLeft]=ways;
}
static long nCk(int n, int k) {
if (k>n) throw null;
return mul(facts[n], mul(factInvs[k], factInvs[n-k]));
}
static long add(long a, long b) {
return (a+b)%mod;
}
static long sub(long a, long b) {
return ((a-b)%mod+mod)%mod;
}
static long mul(long a, long b) {
return (a*b)%mod;
}
static long fastPow(long base, long e) {
if (e==0) return 1;
long half=fastPow(base, e/2);
if (e%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
static long[] facts=new long[1_000_00];
static long[] factInvs=new long[1_000_00];
static void precomp() {
facts[0]=1;
for (int i=1; i<facts.length; i++) facts[i]=mul(facts[i-1], i);
for (int i=0; i<factInvs.length; i++) factInvs[i]=fastPow(facts[i], mod-2);
nWaysToPlaceGroupOfSize=new long[500];
for (int finalSize=1; finalSize<nWaysToPlaceGroupOfSize.length; finalSize++) {
for (int firstPos=0; firstPos<finalSize; firstPos++) {
int l=firstPos, r=finalSize-1-firstPos;
nWaysToPlaceGroupOfSize[finalSize]=add(nWaysToPlaceGroupOfSize[finalSize], nCk(l+r, l));
}
}
System.err.println("Done with precomp.");
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
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[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.* ;
import java.io.* ;
import java.math.* ;
/************************
* *
* Lord Klotski *
* *
***********************/
public class C
{
static int[] arr ; static int L ;
public static void rotate()
{
int tmp = arr[0] ;
for (int i = 1 ; i < L ; i ++)
arr[i-1] = arr[i] ;
arr[L-1] = tmp ;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in) ;
L = input.nextInt() ; String s = input.next() ;
arr = new int[L]; for (int i = 0 ; i < L ; i ++) {arr[i] = s.charAt(i) == 'H' ? 1 : 0 ;}
// want to find longest sequence of 1s
// then rotate to head
int count = 99999 ;
for (int A = 0; A < L ; A ++)
{
int[] tmp = new int[L] ; System.arraycopy(arr, 0, tmp, 0, arr.length);
int ans = 0 ;
for (int i = 0 ; i < L ; i ++)
{
if (tmp[i] == 1) continue ;
for (int j = L-1 ; j > i ; j --)
{
if (tmp[j] == 0) continue ;
ans ++ ;
tmp[i] = 1 ; tmp[j] = 0 ;
//System.out.println("SWAP " + i + " " + j);
//for (int k = 0 ; k < L ; k ++)
// System.out.print(arr[k]);
//System.out.println("");
break;
}
}
count = Math.min(count,ans) ;
rotate() ;
}
// rotate until j is at the front
System.out.println(count);
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.util.Scanner;
public class A961_Tetris {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int platforms = input.nextInt();
int in = input.nextInt();
int[] cols = new int[platforms];
int[] squares = new int[in];
for (int i = 0; i < in; i ++) {
squares[i] = input.nextInt();
}
boolean hi = false;
int score = 0;
for (int i = 0; i < in; i ++) {
cols[squares[i] - 1] ++;
hi = checkscore(cols);
if (hi == true) {
hi = false;
score ++;
for (int j = 0; j < cols.length; j ++) {
cols[j] --;
}
}
}
System.out.println(score);
}
public static boolean checkscore(int[] cols) {
for (int i = 0; i < cols.length; i ++) {
if (cols[i] == 0) {
return false;
}
}
return true;
}
}
|
quadratic
|
961_A. Tetris
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Comparator.*;
public class Main {
FastScanner in;
PrintWriter out;
private void solve() throws IOException {
solveB();
}
private void solveA() throws IOException {
int n = in.nextInt(), k = in.nextInt();
int[] cnt = new int[k];
for (int i = 0; i < n; i++)
cnt[in.nextInt() - 1] ^= 1;
int ans = 0;
for (int i = 0; i < k; i++)
ans += cnt[i];
out.println(n - ans + (ans + 1) / 2);
}
private void solveB() throws IOException {
long n = in.nextLong();
long c = (n + in.nextLong()) * 2;
long l = 0, r = (long) 1e9;
while (l + 1 < r) {
long m = (l + r) / 2;
if (m * m + 3 * m >= c)
r = m;
else
l = m;
}
out.println(n-r);
}
private void solveC() throws IOException {
}
private void solveD() throws IOException {
}
private void solveE() throws IOException {
}
class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
for (int t = 1; t-- > 0; )
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.*;
public class MainClass {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[] = {4,7,47,74,447,474,477,744,747,774};
int i=0, x = in.nextInt();
while (i<arr.length)
if (x%arr[i++] == 0)
{
System.out.print("YES");
return;
}
System.out.print("NO");
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.util.*;
public class Hexadecimal {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int n = input.nextInt();
System.out.print("0 0 " + n);
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main{
public static void main(String []args){
Scanner cin = new Scanner( System.in );
int n = cin.nextInt();
int [] num = new int [ n ];
for (int i=0; i<n; i++)
num[i] = cin.nextInt();
Arrays.sort( num );
int i = 0;
while ( i < n ){
if ( num[i] != num[0] ) break;
i++;
}
if ( i == n ) System.out.println("NO");
else System.out.println(num[i]);
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Solution {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
static class Pair implements Comparable<Pair> {
int x, a;
Pair(int x, int a) {
this.x = x;
this.a = a;
}
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
return 0;
}
}
boolean isCross(double l1, double r1, double l2, double r2) {
double r = min(r1, r2);
double l = max(l1, l2);
return r > l;
}
boolean check(double xl, double xr, double[] l, double[] r, int n) {
boolean ok = false;
for (int j = 0; j < n; ++j)
ok |= isCross(xl, xr, l[j], r[j]);
return ok;
}
void solve() throws IOException {
int n = ni();
double t = ni();
double[] l = new double[n];
double[] r = new double[n];
for (int i = 0; i < l.length; i++) {
double x = ni();
double len = ni();
l[i] = x - len / 2.0;
r[i] = x + len / 2.0;
}
HashSet<Double> set = new HashSet<Double>();
for (int i = 0; i < n; ++i) {
double xl = l[i] - t;
double xr = l[i];
boolean ok = check(xl, xr, l, r, n);
if (!ok)
set.add(xl);
xl = r[i];
xr = r[i] + t;
ok = check(xl, xr, l, r, n);
if (!ok)
set.add(xl);
}
out.println(set.size());
}
public Solution() throws IOException {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
String ns() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int ni() throws IOException {
return Integer.valueOf(ns());
}
long nl() throws IOException {
return Long.valueOf(ns());
}
double nd() throws IOException {
return Double.valueOf(ns());
}
public static void main(String[] args) throws IOException {
new Solution();
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author kanak893
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader fi, PrintWriter out) {
long n, k;
n = fi.nextLong();
k = fi.nextLong();
long ans = 2 * n;
long mod = (long) Math.pow(10, 9) + 7;
if (k > 0) {
ans = (modulus(modulus(pow(2, k + 1, mod), mod) * modulus(n, mod), mod));
long temp = modulus(pow(2, k, mod) - 1, mod);
ans = modulus(modulus(ans, mod) - modulus(temp, mod), mod);
}
if (n == 0) {
ans = 0;
}
ans=ans%mod;
out.println(ans);
}
static long pow(long x, long y, long mod) {
if (y == 0) return 1 % mod;
if (y == 1) return x % mod;
long res = 1;
x = x % mod;
while (y > 0) {
if ((y % 2) != 0) {
res = (res * x) % mod;
}
y = y / 2;
x = (x * x) % mod;
}
return res;
}
static long modulus(long a, long mod) {
return (a % mod + mod) % mod;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.*;
public class helloWorld
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int n = in.nextInt();
int ans = n - (a + b - c);
if(ans < 1 || a >= n || b >= n || c > a || c > b)
ans = -1;
System.out.println(ans);
in.close();
}
}
|
constant
|
991_A. If at first you don't succeed...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class program{
public static void main(String args[]) throws Exception{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if(n==0){
System.out.println("0 0 0");
return;
}
else if(n==1){
System.out.println("0 0 1");
return;
}
else if(n==2){
System.out.println("0 1 1");
return;
}
else{
int ppp=0;
int pp=1;
int c=2;
while(true){
if(ppp+pp+c==n){
System.out.println(ppp+" "+pp+" "+c);
return;
}
else{
c=c+pp+ppp;
int temp=pp;
pp=pp+ppp;
ppp=temp;
}
}
}
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
public class Task343A {
public static void main(String... args) throws NumberFormatException,
IOException {
Solution.main(System.in, System.out);
}
static class Scanner {
private final BufferedReader br;
private String[] cache;
private int cacheIndex;
Scanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
cache = new String[0];
cacheIndex = 0;
}
int nextInt() throws IOException {
if (cacheIndex >= cache.length) {
cache = br.readLine().split(" ");
cacheIndex = 0;
}
return Integer.parseInt(cache[cacheIndex++]);
}
long nextLong() throws IOException {
if (cacheIndex >= cache.length) {
cache = br.readLine().split(" ");
cacheIndex = 0;
}
return Long.parseLong(cache[cacheIndex++]);
}
String next() throws IOException {
if (cacheIndex >= cache.length) {
cache = br.readLine().split(" ");
cacheIndex = 0;
}
return cache[cacheIndex++];
}
void close() throws IOException {
br.close();
}
}
static class Solution {
private static long r(long a, long b) {
if (a == 0 || b == 0) {
return 0;
}
if (a > b) {
return a / b + r(b, a % b);
}
return b / a + r(a, b % a);
}
public static void main(InputStream is, OutputStream os)
throws NumberFormatException, IOException {
PrintWriter pw = new PrintWriter(os);
Scanner sc = new Scanner(is);
long a = sc.nextLong();
long b = sc.nextLong();
pw.println(r(a, b));
pw.flush();
sc.close();
}
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
public class A_GENERAL {
// for fast output printing : use printwriter or stringbuilder
// remember to close pw using pw.close()
static StringBuilder sb = new StringBuilder();
static long seive_size = (long) 1e6;
static String alpha = "abcdefghijklmnopqrstuvwxyz";
static ArrayList<Integer> primes = new ArrayList<>();
static boolean[] seive_set = new boolean[(int) seive_size+1];
static int n, m, k;
static ArrayList<Integer>[] adj;
static boolean[] vis;
static ArrayDeque<Integer> q = new ArrayDeque<>();
static final long MOD = 998244353;
static int[] dx = new int[] {1, 0, -1, 0, 1, -1, 1, -1};
static int[] dy = new int[] {0, 1, 0, -1, -1, 1, 1, -1};
static long[][] arr;
static int[] rank;
static int[] parent;
static int[] s;
static long[] a;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
// MyScanner sc = new MyScanner();
Scanner sc = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter("output.txt");
n = sc.nextInt();
m = sc.nextInt();
k = sc.nextInt();
ArrayDeque<iPair> qq = new ArrayDeque<>();
boolean[][] vis = new boolean[n+1][m+1];
for(int i = 0; i < k; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
qq.add(new iPair(u, v));
vis[u][v] = true;
}
iPair last = null;
while(!qq.isEmpty()) {
iPair pp = qq.poll();
int i = pp.f;
int j = pp.s;
if(isValid(i-1, j) && !vis[i-1][j]) {
qq.add(new iPair(i-1, j));
vis[i-1][j] = true;
}
if(isValid(i+1, j) && !vis[i+1][j]) {
qq.add(new iPair(i+1, j));
vis[i+1][j] = true;
}
if(isValid(i, j-1) && !vis[i][j-1]) {
qq.add(new iPair(i, j-1));
vis[i][j-1] = true;
}
if(isValid(i, j+1) && !vis[i][j+1]) {
qq.add(new iPair(i, j+1));
vis[i][j+1] = true;
}
last = pp;
}
out.println(last.f + " " + last.s);
sc.close();
out.close();
}
public static boolean isValid(int i, int j) {
if(i < 1 || i > n || j < 1 || j > m) return false;
return true;
}
public static class Triplet implements Comparable<Triplet> {
int x;
int y;
int z;
Triplet(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int compareTo(Triplet o) {
return Integer.compare(this.x, o.x);
}
}
public static class iPair implements Comparable<iPair> {
int f;
int s;
iPair(int f, int s) {
this.f = f;
this.s = s;
}
public int compareTo(iPair o) {
return Integer.compare(this.f, o.f);
}
}
public static class Pair implements Comparable<Pair>{
long f;
long s;
Pair(long f, long s) {
this.f = f;
this.s = s;
}
public int compareTo(Pair o) {
return Long.compare(this.f, o.f);
}
}
public static void init(int n) {
adj = new ArrayList[n+1];
vis = new boolean[n+1];
parent = new int[n+1];
rank = new int[n+1];
for(int i = 0; i <= n; i++) {
adj[i] = new ArrayList<>();
parent[i] = i;
rank[i] = 0;
}
}
// print string "s" multiple times
// prefer to use this function for multiple printing
public static String mp(String s, int times) {
return String.valueOf(new char[times]).replace("\0", s);
}
// take log with base 2
public static long log2(long k) {
return 63-Long.numberOfLeadingZeros(k);
}
// using lambda function for sorting
public static void lambdaSort() {
Arrays.sort(arr, (a, b) -> Double.compare(a[0], b[0]));
}
// (n choose k) = (n/k) * ((n-1) choose (k-1))
public static long choose(long n, long k) {
return (k == 0) ? 1 : (n*choose(n-1, k-1))/k;
}
// just for keeping gcd function for other personal purposes
public static long gcd(long a, long b) {
return (a == 0) ? b : gcd(b%a, a);
}
public static long max(long... as) {
long max = Long.MIN_VALUE;
for (long a : as) max = Math.max(a, max);
return max;
}
public static long min(int... as) {
long min = Long.MAX_VALUE;
for (long a : as) min = Math.min(a, min);
return min;
}
public static long modpow(long x, long n, long mod) {
if(n == 0) return 1%mod;
long u = modpow(x, n/2, mod);
u = (u*u)%mod;
if(n%2 == 1) u = (u*x)%mod;
return u;
}
// ======================= binary search (lower and upper bound) =======================
public static int lowerBound(long[] a, int x) {
int lo = 0;
int hi = a.length-1;
int ans = -1;
while(lo <= hi) {
int mid = (lo+hi)/2;
if(x < a[mid]) {
hi = mid-1;
} else if(x > a[mid]) {
lo = mid+1;
} else if(lo != hi) {
hi = mid-1; // for first occurrence
ans = mid;
} else {
return mid;
}
}
return ans;
}
public static int upperBound(long[] a, long x) {
int lo = 0;
int hi = a.length-1;
int ans = -1;
while(lo <= hi) {
int mid = (lo+hi)/2;
if(x < a[mid]) {
hi = mid-1;
} else if(x > a[mid]) {
lo = mid+1;
} else if(lo != hi) {
lo = mid+1; // for last occurrence
ans = mid;
} else {
return mid;
}
}
return ans;
}
// ================================================================
// ================== SEIVE OF ERATOSTHENES =======================
// Complexity : O(N * log(log(N))) ( almost O(N) )
public static void generatePrimes() {
// set.add(0);
// set.add(1);
Arrays.fill(seive_set, true);
seive_set[0] = false;
seive_set[1] = false;
for(int i = 2; i <= seive_size; i++) {
if(seive_set[i]) {
for(long j = (long) i*i; j <= seive_size; j+=i)
seive_set[(int)j] = false;
primes.add(i);
}
}
}
public static boolean isPrime(long N) {
if(N <= seive_size) return seive_set[(int)N];
for (int i = 0; i < (int)primes.size(); i++)
if (N % primes.get(i) == 0) return false;
return true;
}
// ===========================================================
// ================ Permutation of String ====================
public static void permute(String str) {
permute(str, 0, str.length()-1);
}
public static void permute(String str, int l, int r)
{
if (l == r)
System.out.println(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
permute(str, l+1, r);
str = swap(str,l,i);
}
}
}
public static String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
// Union-find
// static int[] parent, rank;
// public static void makeSet(int n) {
//
// parent = new int[n+1];
// rank = new int[n+1];
// for(int i = 1; i <= n; i++) {
// parent[i] = i;
// rank[i] = 0;
// }
// }
public static int find(int u) {
if(parent[u] == u) return u;
int v = find(parent[u]);
parent[u] = v;
return v;
}
public static boolean connected(int u, int v) {
return find(u) == find(v);
}
public static void Union(int u, int v) {
int x = find(u); //root of u
int y = find(v); //root of v
if(x == y) return;
if(rank[x] == rank[y]) {
parent[y] = x;
rank[x]++;
}
else if(rank[x] > rank[y]) {
parent[y] = x;
}
else {
parent[x] = y;
}
}
// public static int dijkstra(int x, int y) {
// int[] dist = new int[n+1];
// Arrays.fill(dist, Integer.MAX_VALUE);
// PriorityQueue<Node> q = new PriorityQueue<>();
// q.add(new Node(x, 0));
// dist[x] = 0;
// while(!q.isEmpty()) {
// Node node = q.poll();
// int u = node.key;
// if(u == y) {
// break;
// }
// for(int v : res[u]) {
// if(dist[v] > dist[u]+count[u]) {
// dist[v] = dist[u] + count[u];
// q.add(new Node(v, dist[v]));
// }
// }
// }
// if(dist[y] == Integer.MAX_VALUE) {
// return -1;
// }
// return dist[y];
// }
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;}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
int[] nextIntArray(int n, int delta) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt() + delta;
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class ElongatedMatrix {
public static void main(String[] args) {
InputStream input;
OutputStream output;
try {
input = new FileInputStream("input.txt");
output = new FileOutputStream("output.txt");
} catch (FileNotFoundException e) {
input = System.in;
output = System.out;
}
Kattio io = new Kattio(input, output);
(new Solve(io)).main();
io.close();
if (input instanceof FileInputStream)
try {
input.close();
} catch (IOException e) {
}
if (output instanceof FileOutputStream)
try {
output.close();
} catch (IOException e) {
}
}
}
class Solve {
static final int oo = (int) 1e9;
Kattio io;
int n, m;
int[][] a;
int[][][] dp;
int[][] diff;
int[][] slant;
Solve(Kattio io) {
this.io = io;
}
int getbit(int x, int n) {
n--;
return (x >> n) & 1;
}
int setbit(int x, int n) {
n--;
return x | (1 << n);
}
int caldp(int currentRow, int firstRow, int mask) {
if (dp[currentRow][firstRow][mask] != -1)
return dp[currentRow][firstRow][mask];
dp[currentRow][firstRow][mask] = 0;
if (mask == (1 << n) - 1)
dp[currentRow][firstRow][mask] = slant[currentRow][firstRow];
else {
for (int i = 1; i <= n; i++)
if (getbit(mask, i) == 0) {
dp[currentRow][firstRow][mask] = Math.max(
Math.min(caldp(i, firstRow, setbit(mask, i)), diff[currentRow][i]),
dp[currentRow][firstRow][mask]);
}
}
return dp[currentRow][firstRow][mask];
}
void main() {
n = io.getInt();
m = io.getInt();
a = new int[n+1][m+1];
dp = new int[n+1][n+1][1<<n];
for (int i=1; i<=n; i++)
for (int j=1; j<=m; j++)
a[i][j] = io.getInt();
diff = new int[n+1][n+1];
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++)
{
diff[i][j]=oo;
for (int x=1; x<=m; x++)
diff[i][j]=Math.min(diff[i][j], Math.abs(a[i][x]-a[j][x]));
}
slant = new int[n+1][n+1];
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++)
{
slant[i][j] = oo;
for (int x=1; x+1<=m; x++)
slant[i][j] = Math.min(slant[i][j], Math.abs(a[i][x]-a[j][x+1]));
}
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++)
Arrays.fill(dp[i][j], -1);
int res = 0;
for (int i=1; i<=n; i++)
res = Math.max(res, caldp(i,i,setbit(0,i)));
io.print(res);
}
}
class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int getInt() {
return Integer.parseInt(nextToken());
}
public double getDouble() {
return Double.parseDouble(nextToken());
}
public long getLong() {
return Long.parseLong(nextToken());
}
public String getWord() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import com.sun.org.apache.xml.internal.utils.StringComparable;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
public class Main {
public static void main(String[] args) {
// Test.testing();
ConsoleIO io = new ConsoleIO();
new Main(io).solve();
io.close();
}
ConsoleIO io;
Main(ConsoleIO io) {
this.io = io;
}
ArrayList<ArrayList<Integer>> gr;
boolean[] visit;
class Edge {
public Edge(int u, int v, int c) {
this.u = u;
this.v = v;
this.c = c;
}
public int u;
public int v;
public int c;
}
long MOD = 1_000_000_007;
int N, M, K;
double[][] map;
public void solve() {
String s = io.readLine();
N = Integer.parseInt(s);
char[] a = io.readLine().toCharArray();
int[] look = new int[256];
Arrays.fill(look, 10000);
int k = 0;
for (int i = 0; i < a.length; i++) {
if (look[a[i]] == 10000) {
look[a[i]] = k;
k++;
}
}
int res = N;
long need = (1L << k) - 1;
long mask = 0;
int head = 0;
int tail = 0;
int[] c = new int[k];
while (head < a.length) {
while (head < a.length && mask != need) {
int v = look[a[head]];
if (c[v] == 0)
mask |= (1L << v);
c[v]++;
head++;
}
while (tail < head && mask == need) {
res = Math.min(res, head - tail);
int v = look[a[tail]];
c[v]--;
if (c[v] == 0)
mask ^= (1L << v);
tail++;
}
}
io.writeLine(res + "");
}
long gcd(long a, long b) {
if (a < b) return gcd(b, a);
if (b == 0) return a;
return gcd(b, a % b);
}
}
class ConsoleIO {
BufferedReader br;
PrintWriter out;
public ConsoleIO(){br = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);}
public void flush(){this.out.flush();}
public void close(){this.out.close();}
public void writeLine(String s) {this.out.println(s);}
public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
public void writeWord(String s){
this.out.print(s);
}
public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }}
public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
public long readLong() {
return Long.parseLong(this.readLine());
}
public long[] readLongArray() {
String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length];
for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
return r;
}
public int[] readIntArray() {
String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
return r;
}
public int[] readIntArray(int n) {
int[] res = new int[n];
char[] all = this.readLine().toCharArray();
int cur = 0;boolean have = false;
int k = 0;
boolean neg = false;
for(int i = 0;i<all.length;i++){
if(all[i]>='0' && all[i]<='9'){
cur = cur*10+all[i]-'0';
have = true;
}else if(all[i]=='-') {
neg = true;
}
else if(have){
res[k++] = neg?-cur:cur;
cur = 0;
have = false;
neg = false;
}
}
if(have)res[k++] = neg?-cur:cur;
return res;
}
public int readInt() {
try {
int r = 0;
boolean start = false;
boolean neg = false;
while (true) {
int c = br.read();
if (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
start = true;
} else if (!start && c == '-') {
start = true;
neg = true;
} else if (start || c == -1) return neg ? -r : r;
}
} catch (Exception ex) {
return -1;
}
}
public void writeIntArray(int[] a) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < a.length; i++) {if (i > 0) sb.append(' ');sb.append(a[i]);}
this.writeLine(sb.toString());
}
}
class Pair {
public Pair(int a, int b) {this.a = a;this.b = b;}
public int a;
public int b;
}
class Tri {
public Tri(int a, int b, int c) {this.a = a;this.b = b;this.c = c;}
public int a;
public int b;
public int c;
}
class PairLL {
public PairLL(long a, long b) {this.a = a;this.b = b;}
public long a;
public long b;
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
static final double eps=1e-10;
public static void main(String[] args) throws FileNotFoundException
{
new Main().solve();
}
public void solve() throws FileNotFoundException
{
Scanner cin=new Scanner(System.in);
int n;
n=cin.nextInt();
String s;
s=cin.next();
int ans=Integer.MAX_VALUE;
int h=0,t=0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='H')
h++;
else if(s.charAt(i)=='T')
t++;
}
ans=Math.min(ans,fun(s,'H',h));
ans=Math.min(ans,fun(s,'T',t));
System.out.println(ans);
}
public int fun(String s,char c,int num)
{
int ans=Integer.MAX_VALUE;
int ret=num;
for(int i=0;i<num;i++)
{
if(s.charAt(i)==c)
{
ret--;
}
}
ans=ret;
for(int i=0;i+num<s.length();i++)
{
if(s.charAt(i)!=c)
ret--;
if(s.charAt(i+num)!=c)
{
ret++;
}
ans=Math.min(ans, ret);
}
return ans;
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1517d {
public static void main(String[] args) throws IOException {
int n = rni(), m = ni(), k = ni(), ans[][] = new int[n][m];
WGraph g = wgraph(n * m);
for (int i = 0; i < n; ++i) {
r();
for (int j = 0; j < m - 1; ++j) {
g.c(i * m + j, i * m + j + 1, ni());
}
}
for (int i = 0; i < n - 1; ++i) {
r();
for (int j = 0; j < m; ++j) {
g.c(i * m + j, (i + 1) * m + j, ni());
}
}
if (k % 2 == 1) {
for (int[] row : ans) {
fill(row, -1);
prln(row);
}
close();
return;
}
k >>= 1;
for (int l = 0; l < k; ++l) {
int nans[][] = new int[n][m];
for (int[] row : nans) {
fill(row, IBIG);
}
for (int i = 0; i < n * m; ++i) {
for (int ed[] : g.get(i)) {
int j = ed[0], d = ed[1];
if (ans[i / m][i % m] + d < nans[j / m][j % m]) {
nans[j / m][j % m] = ans[i / m][i % m] + d;
}
}
}
ans = nans;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
ans[i][j] *= 2;
}
}
for (int[] row : ans) {
prln(row);
}
close();
}
static int solve(WGraph g, int i, int k) {
List<Map<Integer, Integer>> cost = new ArrayList<>();
for (int j = 0; j <= k; ++j) {
cost.add(new HashMap<>());
}
PriorityQueue<int[]> dijk = new PriorityQueue<>((a, b) -> a[2] - b[2]);
dijk.offer(new int[] {i, 0, 0});
cost.get(0).put(i, 0);
while (!dijk.isEmpty()) {
int e[] = dijk.poll(), node = e[0], dist = e[1], co = e[2];
if (co > cost.get(dist).get(node)) {
continue;
}
if (dist == k) {
return 2 * co;
}
if (dist < k) {
for (int ed[] : g.get(node)) {
int j = ed[0], c = ed[1];
if (co + c < cost.get(dist + 1).getOrDefault(j, IBIG)) {
cost.get(dist + 1).put(j, co + c);
dijk.offer(new int[] {j, dist + 1, co + c});
}
}
}
}
return -1;
}
static WGraph wgraph(int n) {
WGraph g = new WGraph();
for (int i = 0; i < n; ++i) {
g.add(new ArrayList<>());
}
return g;
}
static WGraph wgraph(int n, int m) throws IOException {
WGraph g = wgraph(n);
for (int i = 0; i < m; ++i) {
g.c(rni() - 1, ni() - 1, ni());
}
return g;
}
static WGraph wdigraph(int n, int m) throws IOException {
WGraph g = wgraph(n);
for (int i = 0; i < m; ++i) {
g.cto(rni() - 1, ni() - 1, ni());
}
return g;
}
static class WGraph extends ArrayList<List<int[]>> {
void cto(int u, int v, int w) {
get(u).add(new int[] {v, w});
}
void c(int u, int v, int w) {
cto(u, v, w);
cto(v, u, w);
}
}
static BufferedReader __i = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __o = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __r = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final long LMAX = 9223372036854775807L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcd(int a, int b) {return b == 0 ? a : gcd(b, a % b);}
static long gcd(long a, long b) {return b == 0 ? a : gcd(b, a % b);}
static int[] exgcd(int a, int b) {if (b == 0) return new int[] {1, 0}; int[] y = exgcd(b, a % b); return new int[] {y[1], y[0] - y[1] * (a / b)};}
static long[] exgcd(long a, long b) {if (b == 0) return new long[] {1, 0}; long[] y = exgcd(b, a % b); return new long[] {y[1], y[0] - y[1] * (a / b)};}
static int randInt(int min, int max) {return __r.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __i.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
// output
static void pr(int i) {__o.print(i);}
static void prln(int i) {__o.println(i);}
static void pr(long l) {__o.print(l);}
static void prln(long l) {__o.println(l);}
static void pr(double d) {__o.print(d);}
static void prln(double d) {__o.println(d);}
static void pr(char c) {__o.print(c);}
static void prln(char c) {__o.println(c);}
static void pr(char[] s) {__o.print(new String(s));}
static void prln(char[] s) {__o.println(new String(s));}
static void pr(String s) {__o.print(s);}
static void prln(String s) {__o.println(s);}
static void pr(Object o) {__o.print(o);}
static void prln(Object o) {__o.println(o);}
static void prln() {__o.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;};
static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;}
static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__o.flush();}
static void close() {__o.close();}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
/*
* Institute DA-IICT
*/
import java.io.*;
import java.math.*;
import java.util.*;
public class C
{
InputStream in;
PrintWriter out;
void solve()
{
int n=ni();
long dp[]=new long[n+1];
dp[0]=1;
for (int i=0;i<n;)
{
i++;
if (nc()=='f')
{
//boolean flag=i==1;
i++;
int k=1;
while (nc()!='s')
{
i++;k++;
}
//long dp1[]=Arrays.copyOf(dp, n+1);
for (int j=n-1;j>=0;j--)
{
dp[j]=add(dp[j],dp[j+1]);
}
for (int j=n;j>=k;j--)
{
dp[j]=dp[j-k];
}
for (int j=0;j<k;j++)
dp[j]=0;
}
else
{
for (int j=n-1;j>=0;j--)
{
dp[j]=add(dp[j],dp[j+1]);
}
}
//tr(dp);
}
long sum=0;
for (int i=0;i<=n;i++)
sum=add(sum,dp[i]);
out.println(sum);
}
class LazyPropagation
{
long tree[];
long lazy[];
long A[];
public LazyPropagation(int n,long arr[])
{
tree=new long[4*n];
lazy=new long[4*n];
A=arr;
buildSum(1,1,n);
}
public LazyPropagation(int n)
{
tree=new long[4*n];
lazy=new long[4*n];
}
void buildSum(int node,int start,int end)
{
if (start==end)
{
tree[node]=A[start];
}
else
{
int mid=(start+end)>>1;
buildSum(node*2, start, mid);
buildSum(node*2+1, mid+1, end);
tree[node]=tree[node*2]+tree[2*node+1];
}
}
void updateRangeSum(int node, int start, int end,int l,int r,long val)
{
if (lazy[node]!=0)
{
tree[node]=add(tree[node],mul((end-start+1),lazy[node]));
if (start!=end)
{
lazy[2*node]=add(lazy[2*node],lazy[node]);
lazy[node*2+1]=add(lazy[2*node+1],lazy[node]);
}
lazy[node]=0;
}
if (start>end||start>r||end<l)
return;
if (start>=l&&end<=r)
{
tree[node]=add(tree[node],mul((end-start+1),val));
if (start!=end)
{
lazy[2*node]=add(lazy[2*node],val);
lazy[node*2+1]=add(lazy[2*node+1],val);
}
return;
}
int mid=(start+end)>>1;
updateRangeSum(node*2, start, mid, l, r, val);
updateRangeSum(node*2+1, mid+1, end, l, r, val);
tree[node]=add(tree[node*2],tree[node*2+1]);
}
long queryRangeSum(int node,int start,int end,int l,int r)
{
if (start>r||end<l||start>end)
return 0;
if (lazy[node]!=0)
{
tree[node]=add(tree[node],mul((end-start+1),lazy[node]));
if (start!=end)
{
lazy[2*node]=add(lazy[2*node],lazy[node]);
lazy[node*2+1]=add(lazy[2*node+1],lazy[node]);
}
lazy[node]=0;
}
if (start>=l&&end<=r)
return tree[node];
int mid=(start+end)>>1;
return add(queryRangeSum(node*2, start, mid, l, r),queryRangeSum(node*2+1, mid+1, end, l, r));
}
}
long mod=(long)1e9+7;
long add(long a,long b)
{
long x=(a+b);
while(x>=mod) x-=mod;
return x;
}
long sub(long a,long b)
{
long x=(a-b);
while(x<0) x+=mod;
return x;
}
long mul(long a,long b)
{
a%=mod;
b%=mod;
long x=(a*b);
return x%mod;
}
void run() throws Exception {
String INPUT = "C:/Users/ayubs/Desktop/input.txt";
in = oj ? System.in : new FileInputStream(INPUT);
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 C().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 = in.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean inSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && inSpaceChar(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 (!(inSpaceChar(b))) { // when nextLine, (inSpaceChar(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 && !(inSpaceChar(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));
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
/**
* Created by IntelliJ IDEA.
* User: Nick
* Date: 08.08.2010
* Time: 20:44:02
* To change this template use File | Settings | File Templates.
*/
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class B {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
Pattern rc_style = Pattern.compile("R[0-9]+C[0-9]+");
int n = input.nextInt();
while(n-- > 0) {
String str = input.next();
Matcher m = rc_style.matcher(str);
if (m.matches()) {
String nums[] = str.split("[RC]");
String row = nums[1];
String col = nums[2];
String buffer = "";
int col_num = Integer.valueOf(col);
while(col_num > 0) {
if (col_num % 26 > 0) {
buffer += (char)(col_num % 26 + 'A' - 1);
col_num /= 26;
} else {
buffer += 'Z';
col_num /= 26;
col_num--;
}
}
for (int i = buffer.length() - 1; i >= 0; --i) {
System.out.print(buffer.charAt(i));
}
System.out.println(row);
} else {
String col = str.split("[0-9]+")[0];
String row = str.split("[A-Z]+")[1];
int col_num = 0;
int shift = 1;
for (int i = col.length() - 1; i >= 0; --i){
col_num += (int)(col.charAt(i) - 'A' + 1) * shift;
shift *= 26;
}
System.out.println("R" + row + "C" + col_num);
}
}
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
public A () throws IOException {
String input = r.readLine();
int N = Integer.parseInt(input);
int [] A = new int [N];
input = r.readLine();
String [] S = input.split(" ");
for (int i = 0; i < N; ++i)
A[i] = Integer.parseInt(S[i]);
solve(N, A);
}
public void solve (int N, int [] A) {
t = millis();
Arrays.sort(A);
if (A[N-1] > 1) A[N-1] = 1;
else A[N-1] = 2;
Arrays.sort(A);
System.out.print(A[0]);
for (int i = 1; i < N; ++i)
System.out.print(" " + A[i]);
System.out.println();
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new A();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author Antonio "Teo" Alurralde
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer tok = new StringTokenizer(br.readLine());
int ax = Integer.parseInt(tok.nextToken());
int ay = Integer.parseInt(tok.nextToken());
tok = new StringTokenizer(br.readLine());
int bx = Integer.parseInt(tok.nextToken());
int by = Integer.parseInt(tok.nextToken());
tok = new StringTokenizer(br.readLine());
int cx = Integer.parseInt(tok.nextToken());
int cy = Integer.parseInt(tok.nextToken());
boolean ans = (bx < ax && cx < ax && by < ay && cy < ay) ||
(bx < ax && cx < ax && by > ay && cy > ay) ||
(bx > ax && cx > ax && by < ay && cy < ay) ||
(bx > ax && cx > ax && by > ay && cy > ay);
System.out.print(ans?"YES":"NO");
}
}
|
constant
|
1033_A. King Escape
|
CODEFORCES
|
import java.util.*;
public class a {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++) a[i] = in.nextInt()%2;
int z = 0;
for(int i=0;i<n;i++) z+=(a[i] == 0)?1:0;
if (z == 1) z = 0;
else z = 1;
for(int i=0;i<n;i++)
if (a[i] == z){
System.out.println(i+1);
break;
}
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author MaxHeap
*/
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);
CBanhMi solver = new CBanhMi();
solver.solve(1, in, out);
out.close();
}
static class CBanhMi {
long mod = (long) (1e9 + 7);
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int q = in.nextInt();
long[] two = new long[n + 1];
two[0] = 1;
for (int i = 1; i <= n; ++i) {
two[i] = (two[i - 1] * 2L);
two[i] %= mod;
}
char[] s = in.nextCharArray();
int[] acc = new int[n + 1];
for (int i = 1; i <= n; ++i) {
acc[i] = s[i - 1] == '0' ? 0 : 1;
acc[i] += acc[i - 1];
}
// 0 0 1 1 | 1: 1 1 2| 2: 2 3| 4: 5| 9
// 0 1 1 1| 1: 1 2 2| 2: 3 3| 5: 6| 11
// 0 1 1 wwqwq| 1: 1 2 2| 3: 5 3| 8: 8| 16
// 0 0 1 1| 1: 1 1 2| 3: 3 3| 6: 6| 12
// 0 0 0 1| 1: 1 1 1| 2: 2 2| 4: 4| 8
while (q-- > 0) {
int f = in.nextInt();
int t = in.nextInt();
int ones = acc[t] - acc[f - 1];
int zeros = (t - f + 1) - ones;
if (ones == 0) {
out.println(0);
} else {
long ans = two[t - f + 1] - (zeros > 0 ? two[zeros] : 0);
if (zeros == 0) {
--ans;
}
ans = (ans + mod) % mod;
out.println(ans);
}
}
}
}
static class InputReader implements FastIO {
private InputStream stream;
private static final int DEFAULT_BUFFER_SIZE = 1 << 16;
private static final int EOF = -1;
private byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (this.numChars == EOF) {
throw new UnknownError();
} else {
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.stream.read(this.buf);
} catch (IOException ex) {
throw new InputMismatchException();
}
if (this.numChars <= 0) {
return EOF;
}
}
return this.buf[this.curChar++];
}
}
public int nextInt() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {
}
byte sgn = 1;
if (c == 45) {
sgn = -1;
c = this.read();
}
int res = 0;
while (c >= 48 && c <= 57) {
res *= 10;
res += c - 48;
c = this.read();
if (isSpaceChar(c)) {
return res * sgn;
}
}
throw new InputMismatchException();
}
public String next() {
int c;
while (isSpaceChar(c = this.read())) {
}
StringBuilder result = new StringBuilder();
result.appendCodePoint(c);
while (!isSpaceChar(c = this.read())) {
result.appendCodePoint(c);
}
return result.toString();
}
public static boolean isSpaceChar(int c) {
return c == 32 || c == 10 || c == 13 || c == 9 || c == EOF;
}
public char[] nextCharArray() {
return next().toCharArray();
}
}
static interface FastIO {
}
}
|
linear
|
1062_C. Banh-mi
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
* @author pttrung
*/
public class D_Edu_Round_35 {
public static long MOD = 1000000007;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int[] data = new int[n];
for (int i = 0; i < n; i++) {
data[i] = in.nextInt();
}
FT tree = new FT(n + 1);
int result = 0;
for (int i = n - 1; i >= 0; i--) {
tree.update(data[i], 1);
result += tree.get(data[i] - 1);
result %= 2;
}
int q = in.nextInt();
int[] tmp = new int[n];
for (int i = 0; i < q; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
int total = r - l + 1;
total = total * (total - 1) / 2;
total %= 2;
result += total;
result %= 2;
if (result % 2 == 0) {
out.println("even");
} else {
out.println("odd");
}
}
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
int[] data;
FT(int n) {
data = new int[n];
}
public void update(int index, int value) {
while (index < data.length) {
data[index] += value;
data[index] %= 2;
index += (index & (-index));
}
}
public int get(int index) {
int result = 0;
while (index > 0) {
result += data[index];
result %= 2;
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.Arrays;
import java.util.StringTokenizer;
public class Solution {
//<editor-fold desc="input parse" defaultstate="collapsed">
private static StringTokenizer st;
private static java.io.BufferedReader reader;
private static java.io.BufferedWriter writer;
private static long nextLong() {
return Long.parseLong(st.nextToken());
}
private static int nextInt() {
return Integer.parseInt(st.nextToken());
}
private static double nextDouble() {
return Double.parseDouble(st.nextToken());
}
private static short nextShort() {
return Short.parseShort(st.nextToken());
}
private static byte nextByte() {
return Byte.parseByte(st.nextToken());
}
private static void initTokenizer() throws Exception {
st = new StringTokenizer(reader.readLine());
}
//</editor-fold>
public static void main(String[] args) throws Exception {
reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in), 1 << 20);
writer = new java.io.BufferedWriter(new java.io.OutputStreamWriter(System.out));
//reader = new java.io.BufferedReader(new java.io.FileReader("input.txt"), 1 << 20);
//writer = new java.io.BufferedWriter(new java.io.FileWriter("output.txt"));
initTokenizer();
int n = nextInt();
int m = nextInt();
int k = nextInt();
initTokenizer();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
Arrays.sort(a);
int total = k;
int cnt = 0;
while (total < m && cnt < a.length) {
total += a[a.length - 1 - cnt] - 1;
cnt++;
}
if (total >= m) System.out.println(cnt);
else System.out.println(-1);
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Math.*;
// Solution is at the bottom of code
public class _____A implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new _____A(), "", 128 * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
solve();
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken(delim);
}
String readLine() throws IOException{
return in.readLine();
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() throws IOException{
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
}
char[] readCharArray() throws IOException{
return readLine().toCharArray();
}
/////////////////////////////////////////////////////////////////
int readInt() throws IOException{
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException{
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
///////////////////////////////////////////////////////////////////
long readLong() throws IOException{
return Long.parseLong(readString());
}
long[] readLongArray(int size) throws IOException{
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) throws IOException{
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
/////////////////////////////////////////////////////////////////////
Point readPoint() throws IOException{
int x = readInt();
int y = readInt();
return new Point(x, y);
}
Point[] readPointArray(int size) throws IOException{
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
throws IOException{
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
class OutputWriter extends PrintWriter{
final int DEFAULT_PRECISION = 12;
int precision;
String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
boolean check(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
boolean checkBit(int mask, int bitNumber){
return (mask & (1 << bitNumber)) != 0;
}
/////////////////////////////////////////////////////////////////////
long md = (1000 * 1000 * 1000 + 9);
void solve() throws IOException{
int n = readInt();
int m = readInt();
int k = readInt();
long count = n / k;
long mod = n % k;
long maxM = count * (k - 1) + mod;
if (maxM >= m) {
out.println(m % md);
return;
}
long d = m - maxM;
long mul = (binpow(2, d) - 1 + md) % md * 2 % md;
long ans = (mul * k) % md;
ans = (ans + ((count - d) * (k - 1) % md + md) % md + mod) % md;
out.println(ans);
}
long binpow(long a, long n) {
if (n == 0) return 1;
if ((n & 1) == 0) {
long b = binpow(a, n >> 1);
return (b * b) % md;
} else {
return binpow(a, n - 1) * a % md;
}
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import static java.lang.Math.max;
import static java.lang.Math.min;
import java.io.*;
import java.util.*;
public class B {
private void solve() throws IOException {
int senators = nextInt();
int candies = nextInt();
scoreA = nextInt();
lvl = new int[senators];
unloyal = new int[senators];
for (int i = 0; i < senators; i++) {
lvl[i] = nextInt();
unloyal[i] = 10 - nextInt() / 10;
}
n = senators;
give = new int[n];
res = 0;
go(0, candies);
out.println(res);
}
static double res;
static int[] lvl;
static int[] unloyal;
static int[] give;
static int n;
static int scoreA;
static double probability() {
double res = 0;
for (int mask = 0; mask < 1 << n; mask++) {
double p = 1;
int scoreB = 0;
int cntGood = Integer.bitCount(mask);
for (int i = 0; i < n; i++) {
int cnt = unloyal[i] - give[i];
if ((mask & (1 << i)) == 0) {
scoreB += lvl[i];
p *= cnt * .1;
} else {
p *= (10 - cnt) * .1;
}
}
if (2 * cntGood > n) {
res += p;
} else {
res += p * scoreA / (scoreA + scoreB);
}
}
return res;
}
static void go(int man, int candies) {
if (man == n) {
res = max(res, probability());
return;
}
give[man] = 0;
go(man + 1, candies);
for (int i = 1; i <= min(unloyal[man], candies); i++) {
give[man] = i;
go(man + 1, candies - i);
}
}
public static void main(String[] args) {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
new B().solve();
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(239);
}
}
static BufferedReader br;
static StringTokenizer st;
static PrintWriter out;
static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
import java.util.HashMap;
public class Main
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String s(){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 l(){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 i(){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 double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String args[])
{
Reader sc=new Reader();
PrintWriter out=new PrintWriter(System.out);
int n=sc.i();
String s1=sc.s();
String s2=sc.s();
int pos1=-1;
int pos2=-1;
int arr[][][]=new int[100][100][2];
for(int i=0;i<n;i++)
{
if(s1.charAt(i)!=s2.charAt(i))
{
if(arr[s2.charAt(i)-97][s1.charAt(i)-97][0]==1)
{
pos2=i;
pos1=arr[s2.charAt(i)-97][s1.charAt(i)-97][1];
break;
}
arr[s1.charAt(i)-97][s2.charAt(i)-97][0]=1;
arr[s1.charAt(i)-97][s2.charAt(i)-97][1]=i;
}
}
int ham=0;
for(int i=0;i<n;i++)
{
if(s1.charAt(i)!=s2.charAt(i))
ham++;
}
if(pos1!=-1&&pos2!=-1)
{
System.out.println(ham-2);
System.out.println(pos1+1+" "+(pos2+1));
System.exit(0);
}
int arr1[][]=new int[100][2];
int arr2[][]=new int[100][2];
for(int i=0;i<n;i++)
{
if(s1.charAt(i)!=s2.charAt(i))
{
if(arr1[s1.charAt(i)-97][0]==1)
{
pos2=i;
pos1=arr1[s1.charAt(i)-97][1];
break;
}
if(arr2[s2.charAt(i)-97][0]==1)
{
pos2=i;
pos1=arr2[s2.charAt(i)-97][1];
break;
}
arr1[s2.charAt(i)-97][0]=1;
arr1[s2.charAt(i)-97][1]=i;
arr2[s1.charAt(i)-97][0]=1;
arr2[s1.charAt(i)-97][1]=i;
}
}
if(pos1!=-1&&pos2!=-1)
{
System.out.println(ham-1);
System.out.println(pos1+1+" "+(pos2+1));
System.exit(0);
}
System.out.println(ham);
System.out.println(pos1+" "+pos2);
}
}
|
linear
|
527_B. Error Correct System
|
CODEFORCES
|
import java.util.Scanner;
/**
*
* 作者:张宇翔 创建日期:2017年6月16日 上午9:00:48 描述:写字楼里写字间,写字间里程序员; 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠; 酒醉酒醒日复日,网上网下年复年。 但愿老死电脑间,不愿鞠躬老板前; 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱; 不见满街漂亮妹,哪个归得程序员?
*/
public class Main {
private final static int Max = (int) (1e5 + 10);
private static long n,s;
public static void main(String[] args) {
InitData();
GetAns();
}
private static void InitData() {
Scanner cin = new Scanner(System.in);
n=cin.nextLong();
s=cin.nextLong();
};
private static void GetAns() {
long i;
long ans=0;
for(i=s;i<=n;i++){
long k=i-sum(i);
if(k>=s){
if(i%10==9){
break;
}
ans++;
}
}
if(n>=s){
System.out.println(ans-i+n+1);
}else{
System.out.println(0);
}
};
private static long sum(long ans){
long sum=0;
while(ans>0){
sum+=(ans%10);
ans/=10;
}
return sum;
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.FileInputStream;
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;
Reader in = new Reader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
BDigitsSequenceHardEdition solver = new BDigitsSequenceHardEdition();
solver.solve(1, in, out);
out.close();
}
static class BDigitsSequenceHardEdition {
public void solve(int testNumber, Reader in, PrintWriter out) {
long k = in.nextLong();
long start = 1;
long nDigit = 1;
while (true) {
long curr = start * 9 * nDigit;
if (curr >= k) break;
start *= 10;
nDigit += 1;
k -= curr;
}
if (k % nDigit == 0) {
start += (k / nDigit - 1);
out.println(start % 10);
} else {
long n = start + ((k / nDigit));
int off = (int) (k % nDigit);
out.println(Long.toString(n).charAt(off - 1));
}
}
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer;
private int bytesRead;
public Reader(InputStream in) {
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) {
try {
din = new DataInputStream(new FileInputStream(file_name));
} catch (IOException e) {
throw new RuntimeException(e);
}
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public long nextLong() {
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;
}
private void fillBuffer() {
try {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private byte read() {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
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 ATailouloute
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, QuickScanner in, PrintWriter out) {
long n = in.nextLong();
out.println(IntegerUtils.pow(5L, n, 100));
}
}
static class QuickScanner {
BufferedReader br;
StringTokenizer st;
InputStream is;
public QuickScanner(InputStream stream) {
is = stream;
br = new BufferedReader(new InputStreamReader(stream), 32768);
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(nextToken());
}
}
static class IntegerUtils {
public static long pow(long a, long base, long mod) {
if (base == 0) return 1;
if (base == 1) return a;
if ((base & 1) == 1)
return (a * pow(a, base - 1, mod)) % mod;
return pow((a * a) % mod, base / 2, mod);
}
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class ProblemD
{
static int mod = (int) (1e9+7);
static InputReader in;
static PrintWriter out;
static void update(int i, int val, int[] bit){
for(; i < bit.length; i += (i&-i))
bit[i] += val;
}
static int query(int i, int[] bit){
int ans=0;
for(; i>0; i -= (i&-i))
ans += bit[i];
return ans;
}
static int get(int l, int r, int[] bit){
if(l > r) return 0;
return query(r, bit) - query(l - 1, bit);
}
static void solve()
{
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int n = in.nextInt();
int[] arr = new int[n + 1];
int[] bit = new int[n + 2];
for(int i = 1; i <= n; i++){
arr[i] = in.nextInt();
}
int cnt = 0;
for(int i = n; i > 0; i--){
cnt += query(arr[i], bit);
update(arr[i], 1, bit);
}
cnt %= 2;
int q = in.nextInt();
while(q-- > 0){
int l = in.nextInt();
int r = in.nextInt();
int length = r - l + 1;
int x = (length * (length - 1)) / 2;
x %= 2;
cnt ^= x;
out.println(cnt == 0 ? "even" : "odd");
}
out.close();
}
public static void main(String[] args)
{
new Thread(null ,new Runnable(){
public void run(){
try{
solve();
} catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<26).start();
}
static class Pair implements Comparable<Pair>
{
long x,y;
Pair (long x,long y)
{
this.x = x;
this.y = y;
}
public int compareTo(Pair o)
{
return Long.compare(this.x,o.x);
//return 0;
}
public boolean equals(Object o)
{
if (o instanceof Pair)
{
Pair p = (Pair)o;
return p.x == x && p.y==y;
}
return false;
}
@Override
public String toString()
{
return x + " "+ y ;
}
/*public int hashCode()
{
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}*/
}
static long add(long a,long b){
long x=(a+b);
while(x>=mod) x-=mod;
return x;
}
static long sub(long a,long b){
long x=(a-b);
while(x<0) x+=mod;
return x;
}
static long mul(long a,long b){
long x=(a*b);
while(x>=mod) x-=mod;
return x;
}
static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long gcd(long x,long y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static int gcd(int x,int y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static long pow(long n,long p,long m)
{
long result = 1;
if(p==0){
return 1;
}
while(p!=0)
{
if(p%2==1)
result *= n;
if(result >= m)
result %= m;
p >>=1;
n*=n;
if(n >= m)
n%=m;
}
return result;
}
static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static void debug(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
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 LogicalExpression {
int N = 256;
void solve() {
Expression[] E = new Expression[N];
for (int i = 0; i < N; i++) E[i] = new Expression();
E[Integer.parseInt("00001111", 2)].update_f("x");
E[Integer.parseInt("00110011", 2)].update_f("y");
E[Integer.parseInt("01010101", 2)].update_f("z");
for (int l = 2; l < 40; l++) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (E[i].e != null && E[j].t != null && E[i].e.length() + E[j].t.length() + 1 == l) {
E[i | j].update_e(E[i].e + '|' + E[j].t);
}
if (E[i].t != null && E[j].f != null && E[i].t.length() + E[j].f.length() + 1 == l) {
E[i & j].update_t(E[i].t + '&' + E[j].f);
}
}
if (E[i].f != null) E[i ^ (N - 1)].update_f('!' + E[i].f);
}
}
String[] res = new String[N];
for (int i = 0; i < N; i++) res[i] = E[i].calc_best();
int n = in.nextInt();
for (int i = 0; i < n; i++) {
int x = Integer.parseInt(in.nextToken(), 2);
out.println(res[x]);
}
}
static class Expression {
String e, t, f;
Expression() {
}
public Expression(String e, String t, String f) {
this.e = e;
this.t = t;
this.f = f;
}
String calc_best() {
String best = e;
if (compare(best, t) > 0) best = t;
if (compare(best, f) > 0) best = f;
return best;
}
void update_e(String ne) {
if (e == null || compare(e, ne) > 0) {
e = ne;
update_f('(' + e + ')');
}
}
void update_t(String nt) {
if (t == null || compare(t, nt) > 0) {
t = nt;
update_e(t);
}
}
void update_f(String nf) {
if (f == null || compare(f, nf) > 0) {
f = nf;
update_t(f);
}
}
int compare(String a, String b) {
if (a.length() != b.length()) return Integer.compare(a.length(), b.length());
return a.compareTo(b);
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new LogicalExpression().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());
}
}
}
|
quadratic
|
913_E. Logical Expression
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class r114 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
ArrayList<Integer> l = new ArrayList<Integer>();
for (int i = 0 ; i < n; i++) {
l.add(sc.nextInt());
}
Collections.sort(l);
int pet = l.get(n - a);
int vas = l.get(b - 1);
if (pet <= vas) {
System.out.println(0);
}
else System.out.println(pet - vas);
sc.close();
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class programA {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
if(n%2 == 0)System.out.println(n/2 +1);
else System.out.println((int)Math.ceil((double)n/2));
}
}
|
constant
|
964_A. Splits
|
CODEFORCES
|
//package com.example.programming;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class CodeforcesProblems {
static class Pair {
public Pair(int key, int val) {
this.key = key;
this.val = val;
}
int key;
int val;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//String[] strings = br.readLine().split(" ");
int n = Integer.parseInt(br.readLine());
String[] strings = br.readLine().split(" ");
int[] arr = new int[n];
for(int i = 0; i<n; i++) {
arr[i] = Integer.parseInt(strings[i]);
}
HashMap<Integer, ArrayList<Pair>> segments = new HashMap<>();
for(int r = 0; r<arr.length; r++) {
int sum = 0;
for(int l = r; l>=0; l--) {
sum += arr[l];
ArrayList<Pair> pairs = segments.get(sum);
if(pairs == null) {
pairs = new ArrayList<>();
segments.put(sum, pairs);
}
pairs.add(new Pair(l, r));
}
}
int res = 0;
ArrayList<Pair> result = new ArrayList<>();
for(ArrayList<Pair> pairs: segments.values()) {
ArrayList<Pair> temp = new ArrayList<>();
int count = 0;
int r = -1;
for(Pair p : pairs) {
if(p.key>r) {
count++;
temp.add(p);
r = p.val;
}
}
if(count>res) {
res = count;
result = temp;
}
}
System.out.println(res);
StringBuilder sb = new StringBuilder();
for(Pair p : result){
sb.append(p.key+1).append(' ').append(p.val+1).append('\n');
}
System.out.print(sb);
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main implements Runnable {
int n;
double[] prob;
double[][] a;
void solve() throws IOException {
n = nextInt();
a = new double[n][n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
a[i][j] = nextDouble();
}
}
prob = new double[1<<n];
Arrays.fill(prob, 0.0);
prob[(1<<n)-1] = 1.0;
for (int i = (1<<n)-1; i > 1; --i) {
int c = 0;
for (int bit = 0; bit < n; ++bit) {
if (((1<<bit) & i) > 0) {
++c;
}
}
double k = c * (c - 1) / 2.0;
for (int f = 0; f < n; ++f) {
if (((1<<f) & i) > 0) {
for (int s = f+1; s < n; ++s) {
if (((1<<s) & i) > 0) {
prob[i^(1<<f)] += prob[i] * a[s][f] / k;
prob[i^(1<<s)] += prob[i] * a[f][s] / k;
}
}
}
}
}
for (int i = 0; i < n; ++i) {
writer.printf(Locale.US, "%.6f ", prob[1<<i]);
}
}
public static void main(String[] args) throws InterruptedException {
new Thread(null, new Runnable() {
public void run() {
new Main().run();
}
},
"1",
1 << 25).start();
}
@Override
public void run() {
try {
boolean fromStandart = true;
reader = new BufferedReader(fromStandart ? new InputStreamReader(System.in) : new FileReader(INFILE));
writer = new PrintWriter(new BufferedWriter(fromStandart ? new OutputStreamWriter(System.out) : new FileWriter(OUTFILE)));
tokenizer = null;
solve();
writer.flush();
} catch (Exception error) {
error.printStackTrace();
System.exit(1);
}
}
static final String INFILE = "input.txt";
static final String OUTFILE = "output.txt";
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextString() throws IOException {
return reader.readLine();
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/**
* Created by mostafa on 10/7/17.
*/
public class FireAgain {
static int n, m, k;
static int inf = (int) 1e9;
static class Pair {
int x, y;
Pair(int a, int b) {
x = a; y = b;
}
}
static int[] dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1};
static boolean valid(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < m;
}
static int[][] bfs(int[] xs, int[] ys) {
int[][] dist = new int[n][m];
for(int i = 0; i < n; i++)
Arrays.fill(dist[i], inf);
Queue<Pair> q = new LinkedList<>();
for(int i = 0; i < k; i++) {
dist[xs[i]][ys[i]] = 0;
q.add(new Pair(xs[i], ys[i]));
}
while(!q.isEmpty()) {
Pair p = q.remove();
for(int d = 0; d < 4; d++) {
int nx = p.x + dx[d], ny = p.y + dy[d];
if(valid(nx, ny) && dist[nx][ny] == inf) {
dist[nx][ny] = dist[p.x][p.y] + 1;
q.add(new Pair(nx, ny));
}
}
}
return dist;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt();
int[] xs = new int[k], ys = new int[k];
for(int i = 0; i < k; i++) {
xs[i] = sc.nextInt() - 1; ys[i] = sc.nextInt() - 1;
}
int[][] dist = bfs(xs, ys);
int x = 0, y = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(dist[i][j] > dist[x][y]) {
x = i; y = j;
}
x++; y++;
PrintWriter out = new PrintWriter("output.txt");
out.println(x + " " + y);
out.flush();
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() throws FileNotFoundException {
br = new BufferedReader(new FileReader("input.txt"));
}
String next() throws IOException {
while(st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Chores
{
public static void main(String args[])throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String[] line = br.readLine().split("\\W");
int n = Integer.parseInt(line[0]);
int a = Integer.parseInt(line[1]);
int b = Integer.parseInt(line[2]);
int[] num = new int[n];
line = br.readLine().split("\\W");
for(int i=0;i<n;i++) num[i] = Integer.parseInt(line[i]);
Arrays.sort(num);
System.out.println(num[b]-num[b-1]);
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
public class Main {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
int mod=1000000007;
String[] input=in.readLine().split(" ");
int n=Integer.parseInt(input[0]);
int a=Integer.parseInt(input[1]);
int b=Integer.parseInt(input[2]);
String[] h=in.readLine().split(" ");
int[] mas=new int[n];
for(int i=0; i<n; i++){
mas[i]=Integer.parseInt(h[i]);
}
Arrays.sort(mas);
int l=mas[b-1];
int r=mas[b];
int count=0;
if(l==r) count=0;
else count=r-l;
out.println(count);
out.close();
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.util.Map.*;
import java.math.*;
//import java.lang.*;
public class q1
{
static int MOD=1000000007;
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[1000000]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static boolean isPrime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
//Functions
public static void main(String[] args) throws IOException
{
Scanner sc=new Scanner(System.in);
//int T=sc.nextInt();
int T=1;
while(T-- > 0){
int N=sc.nextInt();
int a[]=new int[N];
int count=0;
int ans=0;
boolean flag=false;
for(int i=0;i<N;++i){
a[i]=sc.nextInt();
}
Arrays.sort(a);
for(int i=0;i<N;++i){
if(a[i]==-1)
continue;
for(int j=i+1;j<N;++j){
if(a[j]%a[i]==0 && a[j]!=-1){
a[j]=-1;;
}
}
}
//int i=0;
for(int i=0;i<N;++i){
if(a[i]!= -1)
count++;
}
System.out.println(count);
} // End of test cases loop
}//end of main function
} //end of class
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class CF224B {
public static void main(String[] args) throws Exception {
new CF224B().solve();
}
private void solve() throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
final int MAX_A = 100000;
int[] freq = new int[MAX_A+1];
int numDistinct = 0;
int r = -1;
for (int i = 0; i < n; i++) {
int t = a[i];
freq[t]++;
if (freq[t] == 1) {
numDistinct++;
}
if (numDistinct == k) {
r = i;
break;
}
}
if (r == -1) {
System.out.println("-1 -1");
return;
}
int l;
for (l = 0; l < r; l++) {
int t = a[l];
freq[t]--;
if (freq[t] == 0) {
break;
}
}
System.out.println((l+1) + " " + (r+1));
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
String a = r.next();
char[] c = a.toCharArray();
for(int l = a.length()-1; l >= 1; l--){
for(int i = 0; i <= a.length()-l; i++){
int j = i+l-1;
for(int s = 0; s <= a.length()-l; s++){
if(i == s)continue;
if(a.substring(i, i+l).equals(a.subSequence(s, s+l))){
System.out.println(l);
System.exit(0);
}
}
}
}
System.out.println(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class CF1185G2 {
static final int MD = 1000000007;
static int[][] solve1(int[] aa, int t, int n) {
int[][] da = new int[t + 1][n + 1];
da[0][0] = 1;
for (int i = 0; i < n; i++) {
int a = aa[i];
for (int s = t - 1; s >= 0; s--)
for (int m = 0; m < n; m++) {
int x = da[s][m];
if (x != 0) {
int s_ = s + a;
if (s_ <= t)
da[s_][m + 1] = (da[s_][m + 1] + x) % MD;
}
}
}
return da;
}
static int[][][] solve2(int[] aa, int[] bb, int t, int na, int nb) {
int[][] da = solve1(aa, t, na);
int[][][] dab = new int[t + 1][na + 1][nb + 1];
for (int s = 0; s <= t; s++)
for (int ma = 0; ma <= na; ma++)
dab[s][ma][0] = da[s][ma];
for (int i = 0; i < nb; i++) {
int b = bb[i];
for (int s = t - 1; s >= 0; s--)
for (int ma = 0; ma <= na; ma++)
for (int mb = 0; mb < nb; mb++) {
int x = dab[s][ma][mb];
if (x != 0) {
int s_ = s + b;
if (s_ <= t)
dab[s_][ma][mb + 1] = (dab[s_][ma][mb + 1] + x) % MD;
}
}
}
return dab;
}
static long power(int a, int k) {
if (k == 0)
return 1;
long p = power(a, k / 2);
p = p * p % MD;
if (k % 2 == 1)
p = p * a % MD;
return p;
}
static int[] ff, gg;
static int ch(int n, int k) {
return (int) ((long) ff[n] * gg[n - k] % MD * gg[k] % MD);
}
static int[][][] init(int n, int na, int nb, int nc) {
ff = new int[n + 1];
gg = new int[n + 1];
for (int i = 0, f = 1; i <= n; i++) {
ff[i] = f;
gg[i] = (int) power(f, MD - 2);
f = (int) ((long) f * (i + 1) % MD);
}
int[][][] dp = new int[na + 1][nb + 1][nc + 1];
for (int ma = 0; ma <= na; ma++)
for (int mb = 0; mb <= nb; mb++)
for (int mc = 0; mc <= nc; mc++) {
int x = (int) ((long) ff[ma + mb + mc] * gg[ma] % MD * gg[mb] % MD * gg[mc] % MD);
for (int ma_ = ma == 0 ? 0 : 1; ma_ <= ma; ma_++) {
int cha = ma == 0 ? 1 : ch(ma - 1, ma_ - 1);
for (int mb_ = mb == 0 ? 0 : 1; mb_ <= mb; mb_++) {
int chb = mb == 0 ? 1 : ch(mb - 1, mb_ - 1);
for (int mc_ = mc == 0 ? 0 : 1; mc_ <= mc; mc_++) {
int chc = mc == 0 ? 1 : ch(mc - 1, mc_ - 1);
int y = dp[ma_][mb_][mc_];
if (y == 0)
continue;
x = (int) ((x - (long) y * cha % MD * chb % MD * chc) % MD);
}
}
}
if (x < 0)
x += MD;
dp[ma][mb][mc] = x;
}
for (int ma = 0; ma <= na; ma++)
for (int mb = 0; mb <= nb; mb++)
for (int mc = 0; mc <= nc; mc++)
dp[ma][mb][mc] = (int) ((long) dp[ma][mb][mc] * ff[ma] % MD * ff[mb] % MD * ff[mc] % MD);
return dp;
}
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 t = Integer.parseInt(st.nextToken());
int[] aa = new int[n];
int[] bb = new int[n];
int[] cc = new int[n];
int na = 0, nb = 0, nc = 0;
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int g = Integer.parseInt(st.nextToken());
if (g == 1)
aa[na++] = a;
else if (g == 2)
bb[nb++] = a;
else
cc[nc++] = a;
}
int[][][] dp = init(n, na, nb, nc);
int[][][] dab = solve2(aa, bb, t, na, nb);
int[][] dc = solve1(cc, t, nc);
int ans = 0;
for (int tab = 0; tab <= t; tab++) {
int tc = t - tab;
for (int ma = 0; ma <= na; ma++)
for (int mb = 0; mb <= nb; mb++) {
int xab = dab[tab][ma][mb];
if (xab == 0)
continue;
for (int mc = 0; mc <= nc; mc++) {
int xc = dc[tc][mc];
if (xc == 0)
continue;
ans = (int) ((ans + (long) xab * xc * dp[ma][mb][mc]) % MD);
}
}
}
System.out.println(ans);
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
for (int i = 0; i < n; i++) b[i] = sc.nextInt();
int c[] = new int[2 * n];
c[0] = a[0];
for (int i = 1; i < n; i++) {
c[i * 2] = a[i];
c[i * 2 - 1] = b[i];
if (a[i] == 1 || b[i] == 1) {
System.out.print(-1);
System.exit(0);
}
}
c[2 * n - 1] = b[0];
if (a[0] == 1 || b[0] == 1) {
System.out.print(-1);
System.exit(0);
}
System.out.println(bin_search(c, m));
}
private static double bin_search(int[] c, int m) {
double start = 0;
double end = Integer.MAX_VALUE;
double mid;
while (start + 0.0000001 < end) {
mid = (start + end) / 2;
if (test(mid, m, c)) end = mid;
else start = mid;
}
return end;
}
private static boolean test(double fuel, int m, int[] c) {
for (int i = 0; i < c.length; i++) {
fuel -= (m + fuel) / c[i];
if (fuel < 0) {
return false;
}
}
return true;
}
}
|
nlogn
|
1010_A. Fly
|
CODEFORCES
|
import java.util.Scanner;
public class LCM {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n=sc.nextLong();
if(n < 3) {
System.out.println(n);
}
else if(n % 2 != 0) {
System.out.println(n * (n-1) * (n-2));
}
else if(n % 3 == 0) {
System.out.println((n-1) * (n-2) * (n-3));
}
else {
System.out.println(n * (n-1) * (n-3));
}
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
//package ContestEd69;
import java.io.*;
import java.util.StringTokenizer;
public class mainD {
public static PrintWriter out = new PrintWriter(System.out);
public static FastScanner enter = new FastScanner(System.in);
public static long[] arr;
public static void main(String[] args) throws IOException {
int n=enter.nextInt();
int m=enter.nextInt();
long k=enter.nextLong();
arr=new long[n+1];
for (int i = 1; i <n+1 ; i++) {
arr[i]=enter.nextLong();
}
long[] summ=new long[n+1];
for (int i = 1; i <n+1 ; i++) {
summ[i]+=arr[i]+summ[i-1];
}
long[] best=new long[n+1];
for (int i = 1; i <n+1 ; i++) {
best[i]=Math.max(0, ((i-m>=0) ? best[i-m]+summ[i]-summ[i-m]-k:0));
}
long ans=best[1];
for (int i = 1; i <n+1 ; i++) {
ans=Math.max(ans,best[i]);
for (int j = 1; j <m ; j++) {
ans=Math.max(ans, ((i-j>=0) ? best[i-j] -k +summ[i]-summ[i-j]:0));
}
}
System.out.println(ans);
}
static class FastScanner {
BufferedReader br;
StringTokenizer stok;
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return null;
}
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
char nextChar() throws IOException {
return (char) (br.read());
}
String nextLine() throws IOException {
return br.readLine();
}
}
}
|
quadratic
|
1197_D. Yet Another Subarray Problem
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Set;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.Map.Entry;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Washoum
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
inputClass in = new inputClass(inputStream);
PrintWriter out = new PrintWriter(outputStream);
F2SameSumBlocksHard solver = new F2SameSumBlocksHard();
solver.solve(1, in, out);
out.close();
}
static class F2SameSumBlocksHard {
public void solve(int testNumber, inputClass sc, PrintWriter out) {
int n = sc.nextInt();
int[] tab = new int[n];
int[] s = new int[n];
for (int i = 0; i < n; i++) {
tab[i] = sc.nextInt();
if (i > 0)
s[i] = s[i - 1] + tab[i];
else
s[0] = tab[0];
}
HashMap<Integer, F2SameSumBlocksHard.Pair> sums = new HashMap<>();
F2SameSumBlocksHard.Pair p;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j > 0) {
if (sums.get(s[i] - s[j - 1]) != null) {
if (sums.get(s[i] - s[j - 1]).last < j) {
sums.get(s[i] - s[j - 1]).sum++;
sums.get(s[i] - s[j - 1]).last = i;
}
} else {
p = new F2SameSumBlocksHard.Pair();
p.sum = 1;
p.last = i;
sums.put(s[i] - s[j - 1], p);
}
} else {
if (sums.get(s[i]) != null) {
if (sums.get(s[i]).last < j) {
sums.get(s[i]).sum++;
sums.get(s[i]).last = i;
}
} else {
p = new F2SameSumBlocksHard.Pair();
p.sum = 1;
p.last = i;
sums.put(s[i], p);
}
}
}
}
Iterator<Map.Entry<Integer, F2SameSumBlocksHard.Pair>> it = sums.entrySet().iterator();
Map.Entry<Integer, F2SameSumBlocksHard.Pair> t;
int maxsum = 0;
int cnt = 0;
while (it.hasNext()) {
t = it.next();
if (t.getValue().sum > cnt) {
maxsum = t.getKey();
cnt = t.getValue().sum;
}
}
out.println(cnt);
int start = 0;
for (int i = 0; i < n; i++) {
for (int j = start; j <= i; j++) {
if (j > 0) {
if (s[i] - s[j - 1] == maxsum) {
out.println((j + 1) + " " + (i + 1));
start = i + 1;
break;
}
} else {
if (s[i] == maxsum) {
out.println((j + 1) + " " + (i + 1));
start = i + 1;
break;
}
}
}
}
}
static class Pair {
int sum;
int last;
}
}
static class inputClass {
BufferedReader br;
StringTokenizer st;
public inputClass(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
long solve(long a, long b) {
return b == 0 ? 0 : a / b + solve(b, a % b);
}
public void run() {
try {
long a = reader.nextLong();
long b = reader.nextLong();
writer.println(solve(a, b));
} catch (IOException ex) {
}
writer.close();
}
InputReader reader;
PrintWriter writer;
Main() {
reader = new InputReader();
writer = new PrintWriter(System.out);
}
public static void main(String[] args) {
new Main().run();
}
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer("");
}
String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
Integer nextInt() throws IOException {
return Integer.parseInt(next());
}
Long nextLong() throws IOException {
return Long.parseLong(next());
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Lcm
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(System.out);
long n=Long.parseLong(br.readLine());
if(n<=2)
pw.println(n);
else
{
if(n%6==0)
{
pw.println(((n-1)*(n-2)*(n-3)));
}
else if(n%2==0)
{
pw.println((n*(n-1)*(n-3)));
}
else
{
pw.println((n*(n-1)*(n-2)));
}
}
pw.flush();
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.StringTokenizer;
public class ReallyBigNumbers1
{
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);
long n = Long.parseLong(st.nextToken());
long s = Long.parseLong(st.nextToken());
int r = 0 ;
long l = 0L ;
long u = n ;
if( (l-sumDigits(l)< s ) && (u-sumDigits(u)< s ) )
{
out.println(0);
out.flush();
out.close();
return ;
}
long specified = 0L ;
while( true )
{
long m = (l + u) / 2L ;
if( ( m - sumDigits(m) ) >= s && ( (m-1) - sumDigits(m-1) ) < s )
{
specified = m ;
break ;
}
if( l > u )
break ;
else
{
if( ( m - sumDigits(m) ) >= s )
u = m-1 ;
else
l = m+1 ;
}
}
out.println( n-specified+1 );
out.flush();
out.close();
}
public static int sumDigits(long n)
{
char [] a = (n+"").toCharArray();
int sum = 0 ;
for(int k = 0 ; k < a.length ; k++)
{
sum += Integer.parseInt(a[k]+"") ;
}
return sum ;
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main2 {
static int mod = 1000000007;
static FastScanner scanner;
public static void main(String[] args) {
scanner = new FastScanner();
long n = scanner.nextInt();
long k = scanner.nextInt();
if (sum(n) == k) {
System.out.println(0);
return;
}
long s = 0;
long e = n + 1;
while (s < e - 1) {
long m = (s + e) / 2;
long put = sum(n - m);
long candiesLeft = put - m;
if (candiesLeft == k) {
System.out.println(m);
return;
}
if (candiesLeft > k) {
s = m;
} else {
e = m;
}
}
}
static long sum(long n) {
long last = 1 + n - 1;
return ((1 + last) * n) / 2;
}
static class WithIdx {
int val, idx;
public WithIdx(int val, int idx) {
this.val = val;
this.idx = idx;
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
int[] nextIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
long[] nextLongArray(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) res[i] = nextLong();
return res;
}
String[] nextStringArray(int n) {
String[] res = new String[n];
for (int i = 0; i < n; i++) res[i] = nextToken();
return res;
}
}
static class PrefixSums {
long[] sums;
public PrefixSums(long[] sums) {
this.sums = sums;
}
public long sum(int fromInclusive, int toExclusive) {
if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value");
return sums[toExclusive] - sums[fromInclusive];
}
public static PrefixSums of(int[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
public static PrefixSums of(long[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
}
static class ADUtils {
static void sort(int[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
static void reverse(int[] arr) {
int last = arr.length / 2;
for (int i = 0; i < last; i++) {
int tmp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = tmp;
}
}
static void sort(long[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
long a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
}
static class MathUtils {
static long[] FIRST_PRIMES = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89 , 97 , 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051};
static long[] primes(int to) {
long[] all = new long[to + 1];
long[] primes = new long[to + 1];
all[1] = 1;
int primesLength = 0;
for (int i = 2; i <= to; i ++) {
if (all[i] == 0) {
primes[primesLength++] = i;
all[i] = i;
}
for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j]; j++) {
all[(int) (i * primes[j])] = primes[j];
}
}
return Arrays.copyOf(primes, primesLength);
}
static long modpow(long b, long e, long m) {
long result = 1;
while (e > 0) {
if ((e & 1) == 1) {
/* multiply in this bit's contribution while using modulus to keep
* result small */
result = (result * b) % m;
}
b = (b * b) % m;
e >>= 1;
}
return result;
}
static long submod(long x, long y, long m) {
return (x - y + m) % m;
}
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
/* spar5h */
public class cf1 implements Runnable{
public void run() {
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t = 1;
while(t-- > 0) {
int n = s.nextInt(), m = s.nextInt();
int[] a = new int[n + 1];
for(int i = 1; i <= n; i++)
a[i] = s.nextInt();
int[] b = new int[n + 1];
for(int i = 1; i <= n; i++)
b[i] = s.nextInt();
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(a[1]);
for(int i = 2; i <= n; i++) {
list.add(b[i]); list.add(a[i]);
}
list.add(b[1]);
double wt = m;
boolean check = true;
for(int i = list.size() - 1; i >= 0; i--) {
if(list.get(i) <= 1) {
check = false; break;
}
double x = wt / (list.get(i) - 1);
wt += x;
}
if(check)
w.println(wt - m);
else
w.println(-1);
}
w.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new cf1(),"cf1",1<<26).start();
}
}
|
linear
|
1010_A. Fly
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
/* Template for TopCoder and ACMonline. */
public class A {
private static StreamTokenizer in = null;
private static PrintWriter out = null;
static int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
static long nextLong() throws IOException {
in.nextToken();
return (long) in.nval;
}
static double nextDouble() throws IOException {
in.nextToken();
return (double) 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);
// Here is the solution:
new A().solve();
out.flush();
}
public void solve() throws IOException {
int n = nextInt();
int min = Integer.MAX_VALUE;
int res = Integer.MAX_VALUE;
for (int i=0; i<n; ++i) {
int d = nextInt();
if (d<min) {
res = min;
min = d;
} else if (d>min && d<res)
res = d;
}
if (res == Integer.MAX_VALUE)
out.println("NO");
else
out.println(res);
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
/**
* BaZ :D
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main
{
static MyScanner scan;
static PrintWriter pw;
static long MOD = 1_000_000_007;
static long INF = 1_000_000_000_000_000_000L;
static long inf = 2_000_000_000;
public static void main(String[] args) {
new Thread(null, null, "BaZ", 1 << 27) {
public void run() {
try {
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static int n,m;
static int dp[], cnt[][], sum[];
static void solve() throws IOException
{
//initIo(true);
initIo(false);
StringBuilder sb = new StringBuilder();
n = ni();
m = ni();
dp = new int[(1<<m)];
char c[] = ne().toCharArray();
cnt = new int[m][m];
for(int i=0;i+1<n;++i) {
if(c[i]!=c[i+1]) {
++cnt[c[i] - 'a'][c[i+1] - 'a'];
++cnt[c[i+1] - 'a'][c[i] - 'a'];
}
}
sum = new int[1<<m];
calc(0, 0, 0);
Arrays.fill(dp, -1);
pl(f(0));
pw.flush();
pw.close();
}
static void calc(int mask, int S, int pos) {
if(pos==m) {
sum[mask] = S;
return;
}
calc(mask, S, pos+1);
int newSum = S;
for(int i=0;i<pos;++i) {
if((mask&(1<<i))!=0) {
newSum-=cnt[i][pos];
}
else {
newSum+=cnt[i][pos];
}
}
for(int i=pos+1;i<m;++i) {
newSum+=cnt[i][pos];
}
calc(mask|(1<<pos), newSum, pos+1);
}
static int f(int mask) {
if(mask==(1<<m) - 1) {
return 0;
}
if(dp[mask]!=-1) {
return dp[mask];
}
int min = Integer.MAX_VALUE;
for(int i=0;i<m;++i) {
if((mask&(1<<i))==0) {
min = min(min, sum[mask]+f(mask|(1<<i)));
}
}
return dp[mask] = min;
}
static void initIo(boolean isFileIO) throws IOException {
scan = new MyScanner(isFileIO);
if(isFileIO) {
pw = new PrintWriter("/Users/amandeep/Desktop/output.txt");
}
else {
pw = new PrintWriter(System.out, true);
}
}
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 String ne() throws IOException
{
return scan.next();
}
static String nel() throws IOException
{
return scan.nextLine();
}
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 MyScanner
{
BufferedReader br;
StringTokenizer st;
MyScanner(boolean readingFromFile) throws IOException
{
if(readingFromFile) {
br = new BufferedReader(new FileReader("/Users/amandeep/Desktop/input.txt"));
}
else {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String nextLine()throws IOException
{
return br.readLine();
}
String next() throws IOException
{
if(st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException
{
return Integer.parseInt(next());
}
long nextLong() throws IOException
{
return Long.parseLong(next());
}
double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
}
}
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.