src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.util.*;
public class Solution {
public static void main(String [] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int [] a = new int [n];
int i;
int s = 0;
for (i = 0; i < n; i++) {
a[i] = scan.nextInt();
s += a[i];
}
Arrays.sort(a);
int sum = 0;
for (i = n - 1; i > -1; i--) {
sum += a[i];
if (s - sum < sum) {
System.out.println(n - i);
return;
}
}
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author @Ziklon
*/
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);
ABirthday solver = new ABirthday();
solver.solve(1, in, out);
out.close();
}
static class ABirthday {
public void solve(int testNumber, InputReader in, OutputWriter out) {
long N = in.readLong(), M = in.readLong(), K = in.readLong(), L = in.readLong();
long ans = ((L + K) - 1) / M + 1;
if (ans * M > N || ans * M - K < L) out.printLine(-1);
else out.printLine(ans);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
public void printLine(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
constant
|
1068_A. Birthday
|
CODEFORCES
|
import java.io.*;
public class j
{
public static void main(String a[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int n=0,i=0,k=2;
String s="\0",r="\0";
s=b.readLine();
n=s.length()-1;
while(k<=s.length())
{
for(i=0;i<k;i++)
{
r=s.substring(i,i+n);
if(s.indexOf(r)!=s.lastIndexOf(r))
{
System.out.print(n);
System.exit(0);
}
}
k++;
n--;
}
System.out.print("0");
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.*;
public class A23 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
String W = sc.next();
ArrayList<String>Q = new ArrayList<String>();
for (int i = 0; i < W.length(); i++){
String O = "";
for (int k = i; k < W.length(); k++){
O = O + W.charAt(k);
Q.add(O);
}
}
Collections.sort(Q);
String tmp = Q.get(0);
int y = 0;
for (int i = 1; i < Q.size(); i++){
if (Q.get(i).equals(tmp)){
if (Q.get(i).length() > y){
y = Q.get(i).length();
}
}
else {
tmp = Q.get(i);
}
}
System.out.println(y);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
double ans = 0;
int[] candy;
int[] b;
int[] l;
int[] curLoyal;
int n;
int k;
int A;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
k = in.nextInt();
A = in.nextInt();
b = new int[n];
l = new int[n];
for (int i = 0; i < n; i++) {
b[i] = in.nextInt();
l[i] = in.nextInt();
}
candy = new int[n];
curLoyal = new int[n];
comb(0, k);
out.println(ans);
}
void comb(int ind, int unusedCandy) {
if (ind == n) {
for (int i = 0; i < n; i++) {
curLoyal[i] = Math.min(candy[i] * 10 + l[i], 100);
}
calc();
} else {
for (int i = 0; i <= unusedCandy; i++) {
candy[ind] = i;
comb(ind + 1, unusedCandy - i);
}
}
}
void calc() {
double res = 0;
int allBits = (1 << n) - 1;
for (int vote = 0; vote <= allBits; vote++) {
double curProb = 1;
int sumPower = A;
int enemyCnt = 0;
for (int voteInd = 0; voteInd < n; voteInd++) {
if ((vote & (1 << voteInd)) == 0) {
curProb *= 100 - curLoyal[voteInd];
sumPower += b[voteInd];
enemyCnt++;
} else {
curProb *= curLoyal[voteInd];
}
curProb /= 100;
}
if (2 * enemyCnt >= n) {
curProb *= A;
curProb /= sumPower;
}
res += curProb;
}
ans = Math.max(ans, res);
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String next() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
/**
* Created by Daniil on 5/29/2016.
*/
public class TaskB {
public static int strIndex;
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
char[] s = scanner.next().toCharArray();
int[][] r = new int[n][54];
Set<Character> chars = new HashSet<>();
for (int i= 0 ;i < n; ++ i)chars.add(s[i]);
List<Character> all = new ArrayList<>();
for (Character c: chars)all.add(c);
for (int i = n - 1; i >= 0; -- i){
for (int j = 0;j < 54; ++ j){
if (i == n - 1){
r[i][j] = -1;
}else {
r[i][j] = r[i + 1][j];
}
}
r[i][getCode(s[i])] = i;
}
int res = n;
for (int i =0; i < n; ++ i){
int mx = 1;
boolean fl = false;
for (Character c: all){
if (r[i][getCode(c)] == -1){
fl = true;
break;
}
mx = Math.max(mx, r[i][getCode(c)] - i + 1);
}
if (fl){
System.out.println(res);
return;
}
res = Math.min(res, mx);
}
System.out.println(res);
scanner.close();
//reader.close();
}
public static int getCode(char a){
if (Character.isUpperCase(a))return a - 'A';
return (a - 'a') + 26;
}
public static int getLetter(int n){
if (n > 25)return (char)((n - 26) + 'a');
return (char)((n) + 'A');
}
static class IO{
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void init() {
try {
reader = new BufferedReader(new InputStreamReader(System.in),8*1024);
writer = new PrintWriter(System.out);
} catch (Exception e) {
e.printStackTrace();
System.exit(261);
}
}
void destroy() {
writer.close();
System.exit(0);
}
void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
void println(Object... objects) {
print(objects);
writer.println();
}
String nextLine() throws IOException {
return reader.readLine();
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
FastScanner in;
PrintWriter out;
static final String FILE = "";
public void solve() {
out.print(25);
}
public void run() {
if (FILE.equals("")) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
try {
in = new FastScanner(new FileInputStream(FILE +
".in"));
out = new PrintWriter(new FileOutputStream(FILE +
".out"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
solve();
out.close();
}
public static void main(String[] args) {
(new Main()).run();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
}
class Pair<A extends Comparable<A>, B extends Comparable<B>>
implements Comparable<Pair<A, B>> {
public A a;
public B b;
public Pair(A a, B b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Pair<A, B> o) {
if (o == null || o.getClass() != getClass())
return 1;
int cmp = a.compareTo(o.a);
if (cmp == 0)
return b.compareTo(o.b);
return cmp;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (a != null ? !a.equals(pair.a) : pair.a != null) return
false;
return !(b != null ? !b.equals(pair.b) : pair.b != null);
}
}
class PairInt extends Pair<Integer, Integer> {
public PairInt(Integer u, Integer v) {
super(u, v);
}
}
class PairLong extends Pair<Long, Long> {
public PairLong(Long u, Long v) {
super(u, v);
}
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
public class Main {
BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws IOException
{
new Main().run();
}
public void run() throws IOException
{
//in=new BufferedReader(new FileReader("input.txt"));
//out=new PrintWriter(new FileWriter("output.txt"));
in=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
}
public void solve() throws IOException
{
String now=in.readLine();
int l=now.length();
int answ=0;
for(int i=0;i!=l;i++)
for(int j=i+1;j<l;j++)
{
String a=now.substring(i, j);
for(int k=i+1;k<l-j+i+1;k++)
if(a.compareTo(now.substring(k, k+j-i))==0)
answ=Math.max(answ, a.length());
}
out.print(answ);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class P111C{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-9;
int h, w;
void run(){
h=sc.nextInt();
w=sc.nextInt();
solve();
}
void shuffle(int[] is){
Random rand=new Random();
for(int i=is.length-1; i>=1; i--){
int j=rand.nextInt(i+1);
int t=is[i];
is[i]=is[j];
is[j]=t;
}
}
void solve(){
n=w*h;
g=new long[n];
int[] dx={0, 0, -1, 1};
int[] dy={-1, 1, 0, 0};
for(int y=0; y<h; y++){
for(int x=0; x<w; x++){
for(int k=0; k<4; k++){
int x2=x+dx[k];
int y2=y+dy[k];
if(x2>=0&&x2<w&&y2>=0&&y2<h){
g[y*w+x]|=1L<<(y2*w+x2);
}
}
}
}
candidate=new int[n];
xs=new Xorshift();
mds=(1L<<n)-1;
mds(0, 0, 0);
println((n-Long.bitCount(mds))+"");
}
int n;
long[] g;
long mds;
int[] candidate;
Xorshift xs;
void mds(long choosed, long removed, long covered){
if(Long.bitCount(choosed)>=Long.bitCount(mds))
return;
if(covered==((1L<<n)-1)){
if(Long.bitCount(choosed)<Long.bitCount(mds))
mds=choosed;
return;
}
{
long s=covered;
for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){
int i=Long.numberOfTrailingZeros(remained);
s|=(1L<<i)|g[i];
}
if(s!=((1L<<n)-1)){
return;
}
}
int index=0;
int k=-1;
for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){
int i=Long.numberOfTrailingZeros(remained);
if((covered>>>i&1)==1){
if(Long.bitCount(g[i]&~covered)==0){
mds(choosed, removed|(1L<<i), covered);
return;
}else if(Long.bitCount(g[i]&~covered)==1
&&(g[i]&~covered&~removed)!=0){
mds(choosed, removed|(1L<<i), covered);
return;
}
}else{
if(Long.bitCount(g[i]&~removed)==0){
mds(choosed|(1L<<i), removed|(1L<<i), covered|(1L<<i)|g[i]);
return;
}else if(Long.bitCount(g[i]&~removed)==1
&&((g[i]&~removed)|(g[i]&~covered))==(g[i]&~removed)){
int j=Long.numberOfTrailingZeros(g[i]&~removed);
mds(choosed|(1L<<j), removed|(1L<<i)|(1L<<j), covered
|(1L<<j)|g[j]);
return;
}
}
// if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered))
// k=i;
if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)){
index=0;
candidate[index++]=i;
k=i;
}else if(Long.bitCount(g[i]&~covered)==Long.bitCount(g[k]&~covered)){
candidate[index++]=i;
}
}
if(k==-1)
return;
k=candidate[xs.nextInt(index)];
mds(choosed|(1L<<k), removed|(1L<<k), covered|(1L<<k)|g[k]);
mds(choosed, removed|(1L<<k), covered);
}
class Xorshift{
int x, y, z, w;
public Xorshift(){
x=123456789;
y=362436069;
z=521288629;
w=88675123;
}
public Xorshift(int seed){
x=_(seed, 0);
y=_(x, 1);
z=_(y, 2);
w=_(z, 3);
}
int _(int s, int i){
return 1812433253*(s^(s>>>30))+i+1;
}
// 32bit signed
public int nextInt(){
int t=x^(x<<11);
x=y;
y=z;
z=w;
return w=w^(w>>>19)^t^(t>>>8);
}
// error = O(n*2^-32)
public int nextInt(int n){
return (int)(n*nextDouble());
}
// [0, 1) (53bit)
public double nextDouble(){
int a=nextInt()>>>5, b=nextInt()>>>6;
return (a*67108864.0+b)*(1.0/(1L<<53));
}
}
void println(String s){
System.out.println(s);
}
void print(String s){
System.out.print(s);
}
void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args){
Locale.setDefault(Locale.US);
new P111C().run();
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Comparator;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE2 solver = new TaskE2();
solver.solve(1, in, out);
out.close();
}
static class TaskE2 {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt(), m = in.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
}
}
boolean[][] interesting = new boolean[n][m];
boolean[] hasInteresting = new boolean[m];
for (int i = 0; i < n; i++) {
List<Pair> list = new ArrayList<>();
for (int j = 0; j < m; j++) {
list.add(new Pair(a[i][j], j));
}
Collections.sort(list, Comparator.comparing(pair -> -pair.val));
for (int j = 0; j < m && j <= n; j++) {
interesting[i][list.get(j).pos] = true;
hasInteresting[list.get(j).pos] = true;
}
}
boolean[] goodMask = new boolean[1 << n];
for (int mask = 0; mask < 1 << n; mask++) {
int best = Integer.MAX_VALUE;
int cur = mask;
do {
best = Math.min(best, cur);
cur = (cur >> 1) | ((cur & 1) << (n - 1));
} while (cur != mask);
goodMask[mask] = (mask == best);
}
int[] dp = new int[1 << n];
for (int i = 0; i < m; i++) {
if (!hasInteresting[i]) {
continue;
}
for (int j = 0; j < n; j++) {
if (!interesting[j][i]) {
continue;
}
int supermask = (1 << n) - 1 - (1 << j);
int val = a[j][i];
for (int mask = supermask; ; mask = (mask - 1) & supermask) {
if (dp[mask] + val > dp[mask | (1 << j)]) {
dp[mask | (1 << j)] = dp[mask] + val;
}
if (mask == 0) {
break;
}
}
}
for (int mask = 0; mask < 1 << n; mask++) {
if (!goodMask[mask]) {
continue;
}
int best = 0;
int cur = mask;
do {
best = Math.max(best, dp[cur]);
cur = (cur >> 1) | ((cur & 1) << (n - 1));
} while (cur != mask);
do {
dp[cur] = best;
cur = (cur >> 1) | ((cur & 1) << (n - 1));
} while (cur != mask);
}
}
out.println(dp[(1 << n) - 1]);
}
}
class Pair {
int val;
int pos;
public Pair(int val, int pos) {
this.val = val;
this.pos = pos;
}
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public FastScanner(String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (st == null || !st.hasMoreElements()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class D {
FastScanner in;
PrintWriter out;
boolean systemIO = true;
public void solve() {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = in.nextInt();
}
int x = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] > a[j]) {
x++;
}
}
}
boolean ans = x % 2 == 0;
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int len = -in.nextInt() + in.nextInt();
len = len * (len + 1) / 2;
if (len % 2 == 1) {
ans = !ans;
}
if (ans) {
out.println("even");
} else {
out.println("odd");
}
}
}
public void run() {
try {
if (systemIO) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new FastScanner(new File("segments.in"));
out = new PrintWriter(new File("segments.out"));
}
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
public static void main(String[] arg) {
new D().run();
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class D909 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] line = br.readLine().toCharArray();
int n = line.length;
int l = 0;
ArrayList<Node> groups = new ArrayList<>();
Node node = new Node(line[0], 1);
groups.add(node);
for (int i = 1; i < n; i++) {
if (line[i] == groups.get(l).letter) {
groups.get(l).count++;
} else {
node = new Node(line[i], 1);
groups.add(node);
l++;
}
}
int moves = 0;
ArrayList<Node> temp = new ArrayList<>();
while (groups.size() > 1) {
moves++;
l = groups.size();
groups.get(0).count--;
groups.get(l - 1).count--;
for (int i = 1; i < l - 1; i++) {
groups.get(i).count -= 2;
}
int p;
for (p = 0; p < l; p++) {
if (groups.get(p).count > 0) {
temp.add(groups.get(p));
break;
}
}
int lTemp = temp.size();
for (p++; p < l; p++) {
if (groups.get(p).count <= 0) {
continue;
}
if (groups.get(p).letter == temp.get(lTemp - 1).letter) {
temp.get(lTemp - 1).count += groups.get(p).count;
} else {
temp.add(groups.get(p));
lTemp++;
}
}
groups.clear();
groups.addAll(temp);
temp.clear();
}
System.out.println(moves);
}
private static class Node {
char letter;
int count;
Node(char letter, int count) {
this.letter = letter;
this.count = count;
}
}
}
|
linear
|
909_D. Colorful Points
|
CODEFORCES
|
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
int[] A=new int[n];
String[] s=br.readLine().split(" ");
for(int i=0;i<n;i++){
A[i]=Integer.parseInt(s[i]);
}
/*int[][] nck=new int[2000][2000];
for(int i=0;i<=n;i++){
for(int j=0;j<=n;j++){
nck[i][j]=0;
}
}
for(int i=0;i<=n;i++){
nck[i][0]=1;
for(int j=1;j<=i;j++){
nck[i][j]=nck[i-1][j]+nck[i-1][j-1];
nck[i][j]%=2;
}
}*/
int inv=0;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(A[i]>A[j]){
inv++;
}
}
}
StringBuilder sb=new StringBuilder("");
int m=Integer.parseInt(br.readLine());
for(int i=0;i<m;i++){
s=br.readLine().split(" ");
int li=Integer.parseInt(s[0]);
int ri=Integer.parseInt(s[1]);
int tot=ri-li+1;
inv=inv+tot*(tot-1)/2;
if(inv%2==0){
sb.append("even\n");
}
else{
sb.append("odd\n");
}
}
System.out.print(sb);
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.Scanner;
public class Tsk1 {
static void metod() throws Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String s = in.next();
String ss = s + s;
int t = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'T') {
t++;
}
}
if (t == 1 || t == n - 1) {
System.out.println(0);
} else {
int sum = 0;
for (int i = 0; i < t; i++) {
if (s.charAt(i) == 'T') {
sum++;
}
}
int max = sum;
for (int i = 0; i < s.length(); i++) {
if (ss.charAt(i) == 'T') {
if (ss.charAt(i + t) == 'H') {
sum--;
}
} else {
if (ss.charAt(i + t) == 'T') {
sum++;
max = Math.max(max, sum);
}
}
}
System.out.println(t - max);
}
}
public static void main(String[] args) throws Exception {
Tsk1.metod();
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.util.*;
public class A912 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int A = scan.nextInt();
int B = scan.nextInt();
long x = scan.nextInt();
long y = scan.nextInt();
long z = scan.nextInt();
long requiredA = x * 2 + y;
long requiredB = y + z * 3;
long neededA = Math.max(0, requiredA - A);
long neededB = Math.max(0, requiredB - B);
System.out.print(neededA + neededB);
}
}
|
constant
|
912_A. Tricky Alchemy
|
CODEFORCES
|
import java.util.*;
public class A {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++) a[i] = s.nextInt();
int r = 0, an = 0;
Arrays.sort(a);
int t = 0;
for(int z : a) t += z;
for(int i=a.length-1;i>=0;i--){
r += a[i];
an++;
if (r > t - r) break;
}
System.out.println(an);
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.InputMismatchException;
/**
* @author Egor Kulikov (egor@egork.net)
* Created on 14.03.2010
*/
public class TaskA implements Runnable {
private InputReader in;
private PrintWriter out;
public static void main(String[] args) {
// new Thread(new Template()).start();
new TaskA().run();
}
public TaskA() {
// String id = getClass().getName().toLowerCase();
// try {
// System.setIn(new FileInputStream(id + ".in"));
// System.setOut(new PrintStream(new FileOutputStream(id + ".out")));
// System.setIn(new FileInputStream("input.txt"));
// System.setOut(new PrintStream(new FileOutputStream("output.txt")));
// } catch (FileNotFoundException e) {
// throw new RuntimeException();
// }
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
public void run() {
// int numTests = in.readInt();
// for (int testNumber = 0; testNumber < numTests; testNumber++) {
// out.print("Case " + (testNumber + 1) + ": ");
// }
int n = in.readInt();
int min = 101;
int[] a = new int[n];
for (int i = 0; i < n; i++)
min = Math.min(min, a[i] = in.readInt());
int ans = 101;
for (int i = 0; i < n; i++) {
if (a[i] > min)
ans = Math.min(ans, a[i]);
}
if (ans == 101)
out.println("NO");
else
out.println(ans);
out.close();
}
private static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1000];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class D {
static StringTokenizer st;
static BufferedReader in;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
long L = nextLong();
long R = nextLong();
if (L==R) {
System.out.println(0);
return;
}
String s1 = Long.toBinaryString(L), s2 = Long.toBinaryString(R);
while (s1.length() != s2.length())
s1 = "0"+s1;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
int pow = s1.length()-i;
System.out.println((long)Math.pow(2, pow)-1);
return;
}
}
pw.close();
}
private static int nextInt() throws IOException{
return Integer.parseInt(next());
}
private static long nextLong() throws IOException{
return Long.parseLong(next());
}
private static double nextDouble() throws IOException{
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int in = sc.nextInt();
System.out.println(in/2 + in);
System.exit(0);
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class substring {
static BufferedReader br;
static StringTokenizer st;
static PrintWriter out;
public static void main(String[] args) throws IOException {
InputStream input = System.in;
//InputStream input = new FileInputStream("fileIn.in");
OutputStream output = System.out;
//OutputStream output = new FileOutputStream("fileOut.out");
br = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(output);
String in = br.readLine();
int len = in.length();
int doub = len;
boolean found = false;
while (!found)
{
int count = 0;
String[] parts = new String[len - doub + 1];
for (int i = 0; i < len - doub + 1; i++)
parts[i] = in.substring(i,i+doub);
for (int i = 1; i < len - doub + 1; i++)
for (int j = 0; j < i; j++)
if (parts[i].equals(parts[j]))
count++;
if (count >= 1)
found = true;
doub--;
}
out.println(doub+1);
out.close();
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.IOException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class A {
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
String s = sc.next();
int n = s.length();
for (int i = n; i >= 1; i--) {
Set<String> set = new HashSet<String>();
for (int j = 0; j < n-i+1; j++) {
String t = s.substring(j, j+i);
if (set.contains(t)) {
System.out.println(i);
return;
}
set.add(t);
}
}
System.out.println(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
//package round97;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A {
static BufferedReader bf = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer st;
static PrintWriter out = new PrintWriter(System.out);
static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String s = bf.readLine();
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static String nextStr() throws IOException {
return nextToken();
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public static void main(String[] args) throws IOException {
int n = nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
Arrays.sort(a);
for (int q = 0; q < n; q++) {
if (a[q] != 1) {
out.print("1");
for (int i = 1; i < n; i++) {
out.print(" " + a[i - 1]);
}
out.flush();
return;
}
}
for (int i = 0; i < n - 1; i++) {
out.print("1 ");
}
out.println("2");
out.flush();
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.util.Scanner;
public class A {
public static void main(String[] args) {
A problem = new A();
problem.solve();
}
private void solve() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int p = sc.nextInt();
int v = sc.nextInt();
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
}
long aux;
for(int i = 0; i < n -1; i++){
for(int j = i + 1; j < n; j++){
if((a[i]) > (a[j])){
aux = a[j];
a[j] = a[i];
a[i] = aux;
}
}
}
System.out.println(a[v]-a[v-1]);
}
}
|
nlogn
|
169_A. Chores
|
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 Darshandarji
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
boolean[][] g = new boolean[n][n];
for (int i = 0; i < m; ++i) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
g[a][b] = true;
g[b][a] = true;
}
/*for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
g[i][j] = true;*/
long[] am = new long[n + 1];
long[][] ways = new long[1 << n][n];
for (int start = 0; start < n; ++start) {
for (int mask = 0; mask < (1 << (n - start)); ++mask)
for (int last = start; last < n; ++last) {
ways[mask][last - start] = 0;
}
ways[1][0] = 1;
for (int mask = 0; mask < (1 << (n - start)); ++mask) {
int cnt = 0;
int tmp = mask;
while (tmp > 0) {
++cnt;
tmp = tmp & (tmp - 1);
}
for (int last = start; last < n; ++last)
if (ways[mask][last - start] > 0) {
long amm = ways[mask][last - start];
for (int i = start; i < n; ++i)
if ((mask & (1 << (i - start))) == 0 && g[last][i]) {
ways[mask | (1 << (i - start))][i - start] += amm;
}
if (g[last][start])
am[cnt] += ways[mask][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);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(3 * n / 2);
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
final static int MAXN = 100005;
static int n;
static Scanner cin;
static int[] a;
static boolean[] used;
public static int Query(int x) {
System.out.print("? ");
System.out.println(x);
System.out.flush();
int a = cin.nextInt();
return a;
}
public static int Q(int x) {
if(used[x]) return a[x];
used[x] = true;
a[x] = Query(x) - Query(x + n / 2);
if(a[x] == 0) {
System.out.print("! ");
System.out.println(x);
System.out.flush();
cin.close();
System.exit(0);
}
return a[x];
}
public static void main(String[] args) {
cin = new Scanner(System.in);
n = cin.nextInt();
a = new int[MAXN];
used = new boolean[MAXN];
if(n % 4 != 0) {
System.out.println("! -1\n");
System.out.flush();
cin.close();
return;
}
int l = 1, r = n / 2, mid;
while(l <= r) {
mid = (l + r) / 2;
int x = Q(mid);
if(Q(l) * x < 0) {
r = mid - 1;
} else if(x * Q(r) < 0) {
l = mid + 1;
}
}
System.out.println("! -1\n");
System.out.flush();
cin.close();
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
long a = in.nextLong();
long b = in.nextLong();
if (a < b) {
long t = a;
a = b;
b = t;
}
long ans = 0;
while (b > 0) {
ans += a / b;
long t = a % b;
a = b;
b = t;
}
out.println(ans);
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
if (c < 0) {
return null;
}
while (c >= 0 && !isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public long nextLong() {
return Long.parseLong(next());
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = in.nextInt();
Arrays.sort(A);
int cnt = 0;
for (int i = n - 1; i >= 0; i--) {
if (k >= m) {
System.out.println(cnt);
return;
}
cnt++;
k += A[i] - 1;
}
if (k >= m)
System.out.println(cnt);
else
System.out.println(-1);
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* Created by mostafa on 12/29/17.
*/
public class C {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), r = sc.nextInt();
int[] x = new int[n];
for(int i = 0; i < n; i++)
x[i] = sc.nextInt();
double[] ans = new double[n];
for(int i = 0; i < n; i++) {
ans[i] = r;
for(int j = 0; j < i; j++) {
int d = Math.abs(x[i] - x[j]);
if(d > 2 * r)
continue;
int h = 2 * r;
double yd = Math.sqrt(h * h - d * d);
ans[i] = Math.max(ans[i], ans[j] + yd);
}
out.print(ans[i]);
if(i == n - 1)
out.println();
else
out.print(" ");
}
out.flush();
out.close();
}
static class Scanner {
BufferedReader br; StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
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());
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.util.Map.Entry;
public class Codeforces {
static int n;
static double max;
static int[] pre;
public static void findIntensity(int l){
for(int i = 0, j = i + l; j < n + 1; i++, j++){
double res = (pre[j] - pre[i]) / (double) l;
max = Math.max(max, res);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] heat = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++){
heat[i] = Integer.parseInt(st.nextToken());
}
max = 0;
pre = new int[n + 1];
pre[0] = 0;
for(int i = 0; i < n; i++){
pre[i + 1] = pre[i] + heat[i];
}
for(int i = k; i <= n; i++){
findIntensity(i);
}
System.out.println(max);
}
}
|
quadratic
|
1003_C. Intense Heat
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws IOException
{
// StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
FastScanner sc = new FastScanner();
int dp[][]=new int[6000][6000];
char a[]=new char[6000];
final int n=sc.nextInt();
boolean flag=false;
int cnt=0;
char pre='f';
for(int i=1;i<=n;i++)
{
a[i]=sc.next().charAt(0);
}
dp[1][1]=1;
final int mod=(int)1e9+7;
dp[1][1]=1;
for(int i=2;i<=n;i++)
{
if(a[i-1]=='s')
{
int now=0;
for(int j=5050;j>=1;j--)
{
now=(now+dp[i-1][j])%mod;
dp[i][j]=now;
}
}
else
{
for(int j=5050;j>=1;j--)
{
dp[i][j]=dp[i-1][j-1]%mod;
}
}
}
int ans=0;
for(int i=0;i<=5050;i++)
{
ans+= dp[n][i]%mod;
ans%=mod;
}
out.println(ans%mod);
out.flush();
}
/*
6
f
s
f
s
f
s
*/
static class FastScanner {
BufferedReader br;
StringTokenizer st;
private FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
private boolean hasNextToken()
{
if(st.countTokens()!=StreamTokenizer.TT_EOF)
{
return true;
}
else
return false;
}
private String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
private BigInteger nextBigInteger(){return new BigInteger(next());}
private BigDecimal nextBigDecimal(){return new BigDecimal(next());}
private int nextInt() {return Integer.parseInt(next());}
private long nextLong() {return Long.parseLong(next());}
private double nextDouble() {return Double.parseDouble(next());}
private String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
private int[] nextIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
private long[] nextLongArray(int n){
long[] a = new long[n];
for(int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
private double[] nextDoubleArray(int n){
double[] a = new double[n];
for(int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
private char[][] nextGrid(int n, int m){
char[][] grid = new char[n][m];
for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
return grid;
}
private void sort(int arr[])
{
int cnt[]=new int[(1<<16)+1];
int ys[]=new int[arr.length];
for(int j=0;j<=16;j+=16){
Arrays.fill(cnt,0);
for(int x:arr){cnt[(x>>j&0xFFFF)+1]++;}
for(int i=1;i<cnt.length;i++){cnt[i]+=cnt[i-1];}
for(int x:arr){ys[cnt[x>>j&0xFFFF]++]=x;}
{ final int t[]=arr;arr=ys;ys=t;}
}
if(arr[0]<0||arr[arr.length-1]>=0)return;
int i,j,c;
for(i=arr.length-1,c=0;arr[i]<0;i--,c++){ys[c]=arr[i];}
for(j=arr.length-1;i>=0;i--,j--){arr[j]=arr[i];}
for(i=c-1;i>=0;i--){arr[i]=ys[c-1-i];}
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(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, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] ar = new int[n];
for (int i = 0; i < n; i++)
ar[i] = in.nextInt();
Arrays.sort(ar);
boolean[] u = new boolean[n];
int ans = 0;
for (int i = 0; i < n; i++) {
if (!u[i]) {
u[i] = true;
ans++;
for (int j = 0; j < n; j++) {
if (!u[j] && ar[j] % ar[i] == 0) {
u[j] = true;
}
}
}
}
out.println(ans);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author AlexFetisov
*/
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();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
if (n > m) {
int t = m;
m = n;
n = t;
}
// if (n == 1) {
// out.println(m - ((m + 2) / 3));
// } else if (n == 2) {
// int cur = 2;
// for (int i = 2; i <= m; ++i) {
// if (i % 2 == 0 && i > 2) {
// ++cur;
// }
// }
// out.println(n * m - cur);
// } else {
f = new int[n][m];
res = Integer.MAX_VALUE;
cur = 0;
step = 1;
numFree = n * m;
rec(0, 0);
out.println(n * m - res);
// }
}
private void rec(int x, int y) {
if (numFree == 0) {
res = Math.min(res, cur);
return;
}
if (x >= n) return;
if (y >= m) {
rec(x + 1, 0);
return;
}
if (f[x][y] != 0) {
rec(x, y + 1);
return;
}
put(x, y);
rec(x, y + 1);
remove(x, y);
if (isValid(x + 1, y)) {
put(x + 1, y);
rec(x, y + 1);
remove(x + 1, y);
}
if (isValid(x, y + 1)) {
put(x, y + 1);
rec(x, y + 1);
remove(x, y + 1);
}
}
private void put(int x, int y) {
for (int i = 0; i < 5; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
if (isValid(nx, ny)) {
if (f[nx][ny] == 0) {
--numFree;
f[nx][ny] = step;
}
}
}
++step;
++cur;
}
private void remove(int x, int y) {
--step;
for (int i = 0; i < 5; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
if (isValid(nx, ny)) {
if (f[nx][ny] == step) {
++numFree;
f[nx][ny] = 0;
}
}
}
--cur;
}
private boolean isValid(int x, int y) {
return x >= 0 && y >= 0 && x < n && y < m;
}
int n, m;
int[] dx = new int[] {-1, 0, 1, 0, 0};
int[] dy = new int[] {0, 1, 0, -1, 0};
int step;
int numFree;
int cur;
int res;
int[][] f;
}
class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine().trim();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Vaibhav Pulastya
*/
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 {
long mod = (int) 1e9 + 7;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int T = in.nextInt();
int[] t = new int[n];
int[] g = new int[n];
for (int i = 0; i < n; i++) {
t[i] = in.nextInt();
g[i] = in.nextInt();
}
long[] fact = new long[n + 1];
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (fact[i - 1] * i) % mod;
}
ArrayList<Integer> masks = new ArrayList<>();
long val = 0;
for (int i = 1; i < (1 << n); i++) {
int time = 0;
int[] count = new int[3];
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
time += t[j];
count[g[j] - 1]++;
}
}
if (time == T) {
masks.add(i);
Arrays.sort(count);
long v = ((fact[count[0]] * fact[count[1]]) % mod * fact[count[2]]) % mod;
val += ((countUtil(count[0], count[1], count[2])) * v) % mod;
}
}
out.println(val%mod);
}
long countWays(int p, int q, int r, int last) {
// if number of balls of any
// color becomes less than 0
// the number of ways arrangements is 0.
if (p < 0 || q < 0 || r < 0)
return 0;
// If last ball required is
// of type P and the number
// of balls of P type is 1
// while number of balls of
// other color is 0 the number
// of ways is 1.
if (p == 1 && q == 0 && r == 0 && last == 0)
return 1;
// Same case as above for 'q' and 'r'
if (p == 0 && q == 1 && r == 0 && last == 1)
return 1;
if (p == 0 && q == 0 && r == 1 && last == 2)
return 1;
// if last ball required is P
// and the number of ways is
// the sum of number of ways
// to form sequence with 'p-1' P
// balls, q Q Balls and r R balls
// ending with Q and R.
if (last == 0)
return (countWays(p - 1, q, r, 1) +
countWays(p - 1, q, r, 2)) % mod;
// Same as above case for 'q' and 'r'
if (last == 1)
return (countWays(p, q - 1, r, 0) +
countWays(p, q - 1, r, 2)) % mod;
if (last == 2)
return (countWays(p, q, r - 1, 0) +
countWays(p, q, r - 1, 1)) % mod;
return 0;
}
long countUtil(int p, int q, int r) {
// Three cases arise:
return ((countWays(p, q, r, 0) +
countWays(p, q, r, 1)) % mod +
countWays(p, q, r, 2)) % mod;
}
}
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 InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
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.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.StringTokenizer;
public class B {
static FastReader scan;
static PrintWriter out;
public static void main(String[] args) throws FileNotFoundException {
Solver solver = new Solver();
scan = new FastReader();
out = new PrintWriter(System.out);
int testCases = 1;
for(int i = 1; i <= testCases; i++) {
// out.print("Case #" + i + ": ");
solver.solve();
}
out.close();
}
static class Solver {
void solve() {
long n = scan.nextLong(), k = scan.nextLong();
long low = 0, high = n;
while(true) {
long mid = (low+high)/2;
long s = sum(n-mid);
if(s - mid == k) {
out.println(mid);
return;
}
else if(s - mid < k) {
high = mid-1;
}
else low = mid+1;
//out.println(s-mid + " " + mid);
}
}
static long sum(long a) {
if(a == 0) return 0;
return (a+1)*a/2;
}
}
// Sathvik's Template Stuff BELOW!!!!!!!!!!!!!!!!!!!!!!
static class DSU {
int[] root, size;
int n;
DSU(int n) {
this.n = n;
root = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
root[i] = i;
size[i] = 1;
}
}
int findParent(int idx) {
while (root[idx] != idx) {
root[idx] = root[root[idx]];
idx = root[idx];
}
return idx;
}
boolean union(int x, int y) {
int parX = findParent(x);
int parY = findParent(y);
if (parX == parY)
return false;
if (size[parX] < size[parY]) {
root[parY] = parX;
size[parX] += size[parY];
} else {
root[parX] = parY;
size[parY] += size[parX];
}
return true;
}
}
static class Extra {
static void sort(int[] a) {
Integer[] aa = new Integer[a.length];
for (int i = 0; i < aa.length; i++)
aa[i] = a[i];
Arrays.sort(aa);
for (int i = 0; i < aa.length; i++)
a[i] = aa[i];
}
static void sort(long[] a) {
Long[] aa = new Long[a.length];
for (int i = 0; i < aa.length; i++)
aa[i] = a[i];
Arrays.sort(aa);
for (int i = 0; i < aa.length; i++)
a[i] = aa[i];
}
static void sort(double[] a) {
Double[] aa = new Double[a.length];
for (int i = 0; i < aa.length; i++)
aa[i] = a[i];
Arrays.sort(aa);
for (int i = 0; i < aa.length; i++)
a[i] = aa[i];
}
static void sort(char[] a) {
Character[] aa = new Character[a.length];
for (int i = 0; i < aa.length; i++)
aa[i] = a[i];
Arrays.sort(aa);
for (int i = 0; i < aa.length; i++)
a[i] = aa[i];
}
static long gcd(long a, long b) {
while (b > 0) {
long temp = b;
b = a % b;
a = temp;
}
return a;
}
static long lcm(long a, long b) {
return a * (b / gcd(a, b));
}
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (long i = 5; i * i <= n; i = i + 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
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());
}
int[] nextIntArray(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());
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = nextDouble();
return a;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main implements Runnable {
public void _main() throws IOException {
int n = nextInt();
int k = nextInt();
boolean[] p = new boolean[n + 1];
Arrays.fill(p, true);
List<Integer> primes = new ArrayList<Integer>();
for (int i = 2; i <= n; i++)
if (p[i]) {
primes.add(i);
for (int j = i + i; j <= n; j += i)
p[j] = false;
}
boolean[] ok = new boolean[n + 1];
for (int i = 0; i < primes.size() - 1; i++) {
int x = primes.get(i);
int y = primes.get(i + 1);
if (x + y + 1 <= n)
ok[x + y + 1] = true;
}
for (int i = 2; i <= n; i++)
if (p[i] && ok[i]) {
--k;
}
out.println(k <= 0 ? "YES" : "NO");
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
private String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String rl = in.readLine();
if (rl == null)
return null;
st = new StringTokenizer(rl);
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(next());
}
private long nextLong() throws IOException {
return Long.parseLong(next());
}
private double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) {
new Thread(new Main()).start();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
_main();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(202);
}
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.*;
import java.util.Arrays ;
import java .lang.String.* ;
import java .lang.StringBuilder ;
public class Test{
static int pos = 0 ;
static int arr[] ;
static LinkedList l1 = new LinkedList() ;
static void find(int p ,char[]x,int put[],String s){
int c= 0 ;
for (int i = 0; i < s.length(); i++) {
if(x[p]==s.charAt(i)){
c++ ; }
}
put[p] = c ;
}
static int mode(int m ,int[]x ){
int temp = 0 ;
for (int i = x.length-1; i >=0; i--) {
if(x[i]<=m){
temp= x[i] ;
/// break ;
return m-temp ;
}
}
return m-temp ;
}
static int mode2(int m ,int[]x ){
int temp = 0 ;
for (int i = x.length-1; i >=0; i--) {
if(x[i]<=m){
temp= x[i] ;
/// break ;
return x[i] ;
}
}
return 0 ;
}
static int find(int x[],int temp){
int j = 0 ;
for (int i = x.length-1; i >=0; i--) {
if(x[i]==temp) return j+1 ;
j++ ;
}
return -1 ;
}
static String ch(long[]x,long b){
for (int i = 0; i < x.length; i++) {
if(x[i]==b)return "YES" ;
}
return "NO" ;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in) ;
PrintWriter pw = new PrintWriter(System.out);
int k=in.nextInt(), n=in.nextInt(), s=in.nextInt(), p=in.nextInt() ;
int paper =n/s;
if(n%s!=0) paper++ ;
paper*=k ;
int fin = paper/p ;
if(paper%p!=0) fin++ ;
System.out.println( fin );
}
}
|
constant
|
965_A. Paper Airplanes
|
CODEFORCES
|
// discussed with rainboy
import java.io.*;
import java.util.*;
public class CF915E {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
int q = Integer.parseInt(br.readLine());
TreeMap<Integer, Integer> mp = new TreeMap<>();
int ans = 0;
while (q-- > 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken()) - 1;
int r = Integer.parseInt(st.nextToken());
int t = Integer.parseInt(st.nextToken());
Map.Entry<Integer, Integer> e;
int l_, r_;
if (t == 1) {
if ((e = mp.floorEntry(l)) != null && (r_ = e.getValue()) >= l) {
l_ = e.getKey();
ans -= r_ - l_;
l = l_;
r = Math.max(r, r_);
}
while ((e = mp.higherEntry(l)) != null && (l_ = e.getKey()) <= r) {
r_ = e.getValue();
ans -= r_ - l_;
r = Math.max(r, r_);
mp.remove(l_);
}
ans += r - l;
mp.put(l, r);
} else {
r_ = l;
if ((e = mp.floorEntry(l)) != null && (r_ = e.getValue()) > l) {
l_ = e.getKey();
if (l_ < l)
mp.put(l_, l);
else
mp.remove(l_);
ans -= r_ - l;
}
while ((e = mp.higherEntry(l)) != null && (l_ = e.getKey()) < r) {
r_ = e.getValue();
mp.remove(l_);
ans -= r_ - l_;
}
if (r_ > r) {
mp.put(r, r_);
ans += r_ - r;
}
}
pw.println(n - ans);
}
pw.close();
}
}
|
nlogn
|
915_E. Physical Education Lessons
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1[]=br.readLine().split(" ");
String s2[]=br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
int m=Integer.parseInt(s1[1]);
int a[]=new int[n];
int b[]=new int[n];
int c[]=new int[n];
int d[]=new int[n];
HashSet<Integer> hs=new HashSet<Integer>();
hs.add(0);
hs.add(m);
int max=0;
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(s2[i]);
if(i%2==0)
b[i]=1;
hs.add(a[i]);
}
c[0]=a[0];
for(int i=1;i<n;i++)
{
if(b[i]==0)
c[i]=c[i-1];
else
c[i]=c[i-1]+a[i]-a[i-1];
}
if(b[n-1]==0)
d[n-1]=m-a[n-1];
for(int i=n-2;i>=0;i--)
{
if(b[i]==1)
d[i]=d[i+1];
else
d[i]=d[i+1]+a[i+1]-a[i];
}
max=c[n-1];
if(b[n-1]==0)
max+=m-a[n-1];
//System.out.println(max);
for(int i=n-1;i>=0;i--)
{
int u=a[i]-1;
int v=a[i]+1;
if(!hs.contains(u))
{
if(b[i]==0)
{
int r=1+m-a[i]-d[i]+c[i-1];
max=Math.max(max,r);
}
else
{
int l=0;
if(i>0)
l=a[i-1];
int r=c[i]-1+m-a[i]-d[i];
max=Math.max(max,r);
}
}
if(!hs.contains(v))
{
if(b[i]==0)
{
if(i==n-1)
{
int r=c[i]+1;
max=Math.max(max,r);
}
else
{
int r=c[i]+1+m-a[i+1]-d[i+1];
max=Math.max(max,r);
}
}
else
{
if(i==n-1)
{
int r=c[i]+m-a[i]-1;
max=Math.max(max,r);
}
else
{
int r=c[i]+m-a[i+1]-d[i+1]+a[i+1]-1-a[i];
max=Math.max(max,r);
}
}
}
}
System.out.println(max);
}
}
|
linear
|
1000_B. Light It Up
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class CF1027D {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] cc = new int[n];
for (int i = 0; i < n; i++)
cc[i] = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
int[] aa = new int[n];
for (int i = 0; i < n; i++)
aa[i] = Integer.parseInt(st.nextToken()) - 1;
int[] used = new int[n];
int ans = 0;
for (int i = 0; i < n; i++) {
if (used[i] == 2)
continue;
int j = i;
while (used[j] == 0) {
used[j] = 1;
j = aa[j];
}
if (used[j] == 1) {
int c = cc[j];
while (used[j] == 1) {
used[j] = 2;
c = Math.min(c, cc[j]);
j = aa[j];
}
ans += c;
}
j = i;
while (used[j] == 1) {
used[j] = 2;
j = aa[j];
}
}
System.out.println(ans);
}
}
|
linear
|
1027_D. Mouse Hunt
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class G1 {
static int n, T, duration[], type[];
static long dp[][][], mod = (long) 1e9 + 7;
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
public void run() {
try {
solveIt();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}, "Main", 1 << 28).start();
}
public static void solveIt() throws Exception {
Scanner in = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = in.nextInt();
T = in.nextInt();
dp = new long[3][T + 1][1 << n];
duration = new int[n];
type = new int[n];
for (int i = 0; i < n; i++) {
duration[i] = in.nextInt();
type[i] = in.nextInt() - 1;
}
for (long a[][] : dp) for (long b[] : a) Arrays.fill(b, -1);
pw.println(solve(0, T, 0));
pw.close();
}
static long solve(int lastType, int rem, int mask) {
if (rem == 0) return 1;
if (rem < 0) return 0;
if (dp[lastType][rem][mask] != -1) return dp[lastType][rem][mask];
long res = 0;
for (int i = 0; i < n; i++) {
if (!check(mask, i) && (lastType != type[i] || mask == 0) && rem - duration[i] >= 0) {
res += solve(type[i], rem - duration[i], set(mask, i));
if (res >= mod) res -= mod;
}
}
return dp[lastType][rem][mask] = res;
}
static boolean check(int N, int pos) {
return (N & (1 << pos)) != 0;
}
static int set(int N, int pos) {
return N = N | (1 << pos);
}
static int reset(int N, int pos) {
return N = N & ~(1 << pos);
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
// Don't place your source in a package
import java.math.BigInteger;
import java.util.*;
import java.lang.*;
import java.io.*;
// Please name your class Main
public class Main {
static FastScanner fs=new FastScanner();
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int Int() {
return Integer.parseInt(next());
}
long Long() {
return Long.parseLong(next());
}
String Str(){
return next();
}
}
public static void main (String[] args) throws java.lang.Exception {
PrintWriter out = new PrintWriter(System.out);
int T=1;
for(int t=0;t<T;t++){
long k=Long();
Solution sol=new Solution(out);
sol.solution(k);
}
out.flush();
}
public static int Int(){
return fs.Int();
}
public static long Long(){
return fs.Long();
}
public static String Str(){
return fs.Str();
}
}
class Solution{
PrintWriter out;
public Solution(PrintWriter out){
this.out=out;
}
long f[]=new long[15];
public void solution(long k){
f[0]=9;
for(int i=1;i<f.length;i++){
f[i]=10*f[i-1];
}
for(int i=1;i<f.length;i++){
f[i]*=(i+1);
}
long l=1,r=1000000000000l;
long res=-1;
long count=0;
while(l<=r){
long mid=l+(r-l)/2;
long cnt=get(mid);
if(cnt>=k){
res=mid;
count=cnt;
r=mid-1;
}
else{
l=mid+1;
}
}
int extra=(int)(count-k);
String s=res+"";
out.println(s.charAt(s.length()-1-extra));
}
public long get(long n){
long res=0;
long base=0;
int i=0;
while(true){
if(n<=base*10+9){
res=res+(i+1)*(n-base);
break;
}
res+=(f[i]);
i++;
base=base*10+9;
}
return res;
}
}
/*
;\
|' \
_ ; : ;
/ `-. /: : |
| ,-.`-. ,': : |
\ : `. `. ,'-. : |
\ ; ; `-.__,' `-.|
\ ; ; ::: ,::'`:. `.
\ `-. : ` :. `. \
\ \ , ; ,: (\
\ :., :. ,'o)): ` `-.
,/,' ;' ,::"'`.`---' `. `-._
,/ : ; '" `;' ,--`.
;/ :; ; ,:' ( ,:)
,.,:. ; ,:., ,-._ `. \""'/
'::' `:'` ,'( \`._____.-'"'
;, ; `. `. `._`-. \\
;:. ;: `-._`-.\ \`.
'`:. : |' `. `\ ) \
-hrr- ` ;: | `--\__,'
'` ,'
,-'
free bug dog
*/
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;
import java.util.Stack;
public class D527A2 {
public static void main(String[] args) {
FastScanner in = new FastScanner(System.in);
int N = in.nextInt();
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < N; i++) {
int num = in.nextInt() % 2;
if(stack.size() >= 1 && stack.lastElement() == num)
stack.pop();
else
stack.add(num);
}
System.out.println(stack.size() <= 1 ? "YES" : "NO");
}
/**
* Source: Matt Fontaine
*/
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int chars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (chars == -1)
throw new InputMismatchException();
if (curChar >= chars) {
curChar = 0;
try {
chars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (chars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
/*
5
2 1 1 2 5
outputCopy
YES
inputCopy
3
4 5 3
outputCopy
YES
inputCopy
2
10 10
outputCopy
YES
inputCopy
3
1 2 3
outputCopy
NO
5
2 3 2 2 3
YES
*/
|
linear
|
1092_D1. Great Vova Wall (Version 1)
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ReaderFastIO in = new ReaderFastIO(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DConcatenatedMultiples solver = new DConcatenatedMultiples();
solver.solve(1, in, out);
out.close();
}
static class DConcatenatedMultiples {
public void solve(int testNumber, ReaderFastIO in, PrintWriter out) {
Map<Integer, Integer>[] mapMods = new HashMap[11];
int n = in.nextInt();
int k = in.nextInt();
int[] a = in.readArrayInt(n);
for (int i = 0; i < 11; i++) {
mapMods[i] = new HashMap<>();
}
for (int i = 0; i < n; i++) {
int pot = getPot(a[i]);
mapMods[pot].put(a[i] % k, mapMods[pot].getOrDefault(a[i] % k, 0) + 1);
}
long ct = 0;
for (int i = 0; i < n; i++) {
int ownPot = getPot(a[i]);
long suffix = a[i] * 10L;
for (int j = 1; j <= 10; j++) {
int mod = (int) (suffix % k);
int comMod = (k - mod) % k;
int qt = mapMods[j].getOrDefault(comMod, 0);
if (j == ownPot && (a[i] % k) == comMod) {
qt--;
}
ct += qt;
suffix = (suffix * 10L) % k;
}
}
out.println(ct);
}
public int getPot(int x) {
int ct = 0;
while (x != 0) {
x /= 10;
ct++;
}
return ct;
}
}
static class ReaderFastIO {
BufferedReader br;
StringTokenizer st;
public ReaderFastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public ReaderFastIO(InputStream input) {
br = new BufferedReader(new InputStreamReader(input));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] readArrayInt(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
}
}
|
nlogn
|
1029_D. Concatenated Multiples
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class EdC {
static long[] mods = {1000000007, 998244353, 1000000009};
static long mod = mods[0];
public static MyScanner sc;
public static PrintWriter out;
static char[][] grid;
static int n;
static int t;
static int[][] dp;
static int[] times;
static int[] genre;
public static void main(String[] omkar) throws Exception{
// TODO Auto-generated method stub
sc = new MyScanner();
out = new PrintWriter(System.out);
n = sc.nextInt();
t = sc.nextInt();
times = new int[n];
genre = new int[n];
for(int j =0 ;j<n;j++){
times[j] = sc.nextInt();
genre[j] = sc.nextInt();
}
dp = new int[1<<n][4];
for(int j = 0;j<1<<n;j++)
Arrays.fill(dp[j], -1);
int ans = 0;
for(int j=0;j<1<<n;j++){
int time = 0;
for(int k = 0;k<n;k++){
if (((1<<k) & j) != 0){
time+=times[k];
}
}
if (time == t){
letsgodp(j, 1);
letsgodp(j, 2);
letsgodp(j, 3);
ans+=dp[j][1];
ans%=mod;
ans+=dp[j][2];
ans%=mod;
ans+=dp[j][3];
ans%=mod;
}
}
out.println(ans);
out.close();
}
public static void letsgodp(int mask, int dg){
if (dp[mask][dg] != -1)
return;
dp[mask][dg] = 0;
for(int j = 0;j<n;j++){
if (((1<<j) & mask) != 0 && genre[j] == dg){
int submask = mask - (1<<j);
int og1 = genre[j]+1 > 3 ? genre[j]-2 : genre[j]+1;
int og2 = genre[j]+2 > 3 ? genre[j]-1 : genre[j]+2;
if (submask != 0){
letsgodp(submask, og1);
letsgodp(submask, og2);
dp[mask][dg] +=(dp[submask][og1] + dp[submask][og2]);
dp[mask][dg] %=mod;
}
else{
dp[mask][dg] = 1;
}
}
}
}
public static void sort(int[] array){
ArrayList<Integer> copy = new ArrayList<Integer>();
for (int i : array)
copy.add(i);
Collections.sort(copy);
for(int i = 0;i<array.length;i++)
array[i] = copy.get(i);
}
static String[] readArrayString(int n){
String[] array = new String[n];
for(int j =0 ;j<n;j++)
array[j] = sc.next();
return array;
}
static int[] readArrayInt(int n){
int[] array = new int[n];
for(int j = 0;j<n;j++)
array[j] = sc.nextInt();
return array;
}
static int[] readArrayInt1(int n){
int[] array = new int[n+1];
for(int j = 1;j<=n;j++){
array[j] = sc.nextInt();
}
return array;
}
static long[] readArrayLong(int n){
long[] array = new long[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextLong();
return array;
}
static double[] readArrayDouble(int n){
double[] array = new double[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextDouble();
return array;
}
static int minIndex(int[] array){
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(long[] array){
long minValue = Long.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(double[] array){
double minValue = Double.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static long power(long x, long y){
if (y == 0)
return 1;
if (y%2 == 1)
return (x*power(x, y-1))%mod;
return power((x*x)%mod, y/2)%mod;
}
static void verdict(boolean a){
out.println(a ? "YES" : "NO");
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
import java.io.InputStream ;
import java.util.InputMismatchException;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
//Scanner sc = new Scanner();
Reader in = new Reader();
Main solver = new Main();
solver.solve(out, in);
out.flush();
out.close();
}
void solve(PrintWriter out, Reader in) throws IOException{
int n = in.nextInt();
int m = in.nextInt();
int[] vert = new int[n+1];
for(int i=0 ;i<n ;i++) vert[i] = in.nextInt();
vert[n] = (int)1e9;
int cnt=0,x,y;
ArrayList<Integer> arr = new ArrayList<>();
for(int i=0 ;i<m ;i++) {
x = in.nextInt();
y = in.nextInt();
in.nextInt();
if(x==1) arr.add(y);
}
horz = new int[arr.size()];
for(int i=0 ;i<arr.size();i++) horz[i] = arr.get(i);
Arrays.sort(horz);
Arrays.sort(vert);
int ans = 2*(int)1e5+10;
for(int i=0 ;i<=n ;i++){
int lesshorz = bs(vert[i],horz.length);
ans = Math.min(ans,i+horz.length-lesshorz-1);
}
out.println(ans);
}
static int[] horz;
static int bs(int num,int m){
int mid,lo=0,hi=m-1,r=-1;
while(lo<=hi){
mid = (lo+hi)/2;
if(horz[mid]<num){
lo = mid+1;
r = mid;
}else{
hi =mid-1;
}
}
return r;
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
|
nlogn
|
1075_C. The Tower is Going Home
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class loser
{
static class InputReader {
public BufferedReader br;
public StringTokenizer token;
public InputReader(InputStream stream)
{
br=new BufferedReader(new InputStreamReader(stream),32768);
token=null;
}
public String next()
{
while(token==null || !token.hasMoreTokens())
{
try
{
token=new StringTokenizer(br.readLine());
}
catch(IOException e)
{
throw new RuntimeException(e);
}
}
return token.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
static class card{
int l;
int r;
public card(int ch,int i)
{
this.l=ch;
this.r=i;
}
}
static class sort implements Comparator<card>
{
public int compare(card o1,card o2)
{
if(o1.l!=o2.l)
return (int)(o1.l-o2.l);
else
return (int)(o1.r-o2.r);
}
}
static void shuffle(long a[])
{
List<Long> l=new ArrayList<>();
for(int i=0;i<a.length;i++)
l.add(a[i]);
Collections.shuffle(l);
for(int i=0;i<a.length;i++)
a[i]=l.get(i);
}
/*static long gcd(long a,long b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
static int ans1=Integer.MAX_VALUE,ans2=Integer.MAX_VALUE,ans3=Integer.MAX_VALUE,ans4=Integer.MAX_VALUE;
static boolean v[]=new boolean[101];
static void dfs(Integer so,Set<Integer> s[]){
if(!v[so.intValue()])
{
v[so]=true;
for(Integer h:s[so.intValue()])
{
if(!v[h.intValue()])
dfs(h,s);
}
}
}
static class Print{
public PrintWriter out;
Print(OutputStream o)
{
out=new PrintWriter(o);
}
}
static int CeilIndex(int A[], int l, int r, int key)
{
while (r - l > 1) {
int m = l + (r - l) / 2;
if (A[m] >= key)
r = m;
else
l = m;
}
return r;
}
static int LongestIncreasingSubsequenceLength(int A[], int size)
{
// Add boundary case, when array size is one
int[] tailTable = new int[size];
int len; // always points empty slot
tailTable[0] = A[0];
len = 1;
for (int i = 1; i < size; i++) {
if (A[i] < tailTable[0])
// new smallest value
tailTable[0] = A[i];
else if (A[i] > tailTable[len - 1])
// A[i] wants to extend largest subsequence
tailTable[len++] = A[i];
else
// A[i] wants to be current end candidate of an existing
// subsequence. It will replace ceil value in tailTable
tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i];
}
return len;
}*/
/*static int binary(int n)
{
int s=1;
while(n>0)
{
s=s<<1;
n--;
}
return s-1;
}
static StringBuilder bin(int i,int n)
{
StringBuilder s=new StringBuilder();
while(i>0)
{
s.append(i%2);
i=i/2;
}
while(s.length()!=n)
{
s.append(0);
}
return s.reverse();
}*/
static boolean valid(int i,int j,int n,int m)
{
if(i<n && i>=0 && j<m && j>=0)
return true;
else
return false;
}
public static void main(String[] args)
{
InputReader sc=new InputReader(System.in);
int n=sc.nextInt();
int s=sc.nextInt();
card c[]=new card[n];
for(int i=0;i<n;i++)
{
int x=sc.nextInt();
int y=sc.nextInt();
c[i]=new card(x,y);
}
Arrays.sort(c,new sort());
int time=0;
for(int i=n-1;i>=0;i--)
{
time+=s-c[i].l;
if((c[i].r-time)>0)
time+=c[i].r-time;
s=c[i].l;
}
if(c[0].l!=0)
time+=c[0].l;
System.out.println(time);
}
}
|
nlogn
|
608_A. Saitama Destroys Hotel
|
CODEFORCES
|
import java.util.*;
import java.math.*;
public class codeforces {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] data=new int[n];
for(int i=0;i<n;i++)
data[i]=sc.nextInt();
Arrays.sort(data);
if(data[n-1]!=1)
data[n-1]=1;
else
data[n-1]=2;
Arrays.sort(data);
for(int i=0;i<n;i++)
{
System.out.print(data[i]);
if(i!=n-1)
System.out.print(" ");
}
return;
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Built using CHelper plug-in Actual solution is at the top
*/
public class Practice {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
String[] arr1 = new String[n];
String[] arr2 = new String[n];
for (int i = 0; i < n; i++) {
arr1[i] = in.next();
}
for (int i = 0; i < n; i++) {
arr2[i] = in.next();
}
int ans = 0;
boolean arr[]=new boolean[n];
boolean found=false;
for (int i = 0; i < arr1.length; i++) {
for(int j=0;j<arr1.length;j++){
found=false;
if(arr1[i].equals(arr2[j]) && !arr[j]){
found=true;
arr[j]=true;
break;
}
}
if(!found){
ans++;
}
}
out.println(ans);
}
}
public static boolean checkPrime(int n, int p) {
for (int i = 2; i <= Math.sqrt(n) && i <= p; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void mergeArrays(int[] arr1, int[] arr2, int n1,
int n2, int[] arr3) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j]) {
arr3[k++] = arr1[i++];
} else {
arr3[k++] = arr2[j++];
}
}
while (i < n1) {
arr3[k++] = arr1[i++];
}
while (j < n2) {
arr3[k++] = arr2[j++];
}
}
public long GCD(long a, long b) {
if (b == 0) {
return a;
}
return GCD(b, a % b);
}
public static long nCr(int n, int r) {
return n * (n - 1) / 2;
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
quadratic
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Liavontsi Brechka
*/
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
@SuppressWarnings("Duplicates")
class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int MAX = 6000;
int MOD = 1000000007;
int n = in.nextInt();
int[][] dp = new int[n][MAX];
dp[0][0] = 1;
char next;
int current;
for (int i = 0; i < n; i++) {
next = in.next().charAt(0);
if (i == n - 1) continue;
current = 0;
for (int j = MAX - 1; j >= 0; j--) {
if (dp[i][j] != 0) {
if (next == 'f') {
if (j < MAX - 1) dp[i + 1][j + 1] = (dp[i + 1][j + 1] + dp[i][j]) % MOD;
} else {
current = (current + dp[i][j]) % MOD;
}
}
if (next == 's') dp[i + 1][j] = current;
}
}
int res = 0;
for (int i = 0; i < MAX; i++) {
res = (res + dp[n - 1][i]) % MOD;
}
out.print(res);
}
}
static class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(readLine());
}
return tokenizer.nextToken();
}
public String readLine() {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.Scanner;
/**
* Created by IntelliJ IDEA.
* User: Mirza
* Date: 25.03.12
* Time: 18:51
* To change this template use File | Settings | File Templates.
*/
public class main {
static Scanner in; static int next() throws Exception {return in.nextInt();};
//static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;}
// static BufferedReader in;
static PrintWriter out;
public static void main(String[] args) throws Exception {
in = new Scanner(System.in);
// in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
// in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = next();
int a = next();
int b = next();
int k = 0;
int i;
int[] ar = new int[n];
for(i=0;i<n;i++)
ar[i]=next();
Arrays.sort(ar);
k = ar[n-a]-ar[b-1];
if(k<0)
out.print(0);
else out.print(k);
out.close();
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) throws Exception {
int n=nextInt();
int m=nextInt();
int k=nextInt();
int wa=n-m;
if(n/k<=wa){
System.out.println(m);
}else{
int notFull=wa;
int full=n/k-wa;
long res=1;
int power=full+1;
int mod=1000000009;
long powTwo=2;
while(power>0){
if((power&1)==1){
res=(res*powTwo)%mod;
}
power>>=1;
powTwo=(powTwo*powTwo)%mod;
}
res=(((res-2+mod)%mod)*k)%mod;
res=((res+notFull*(k-1))%mod+n%k)%mod;
System.out.println(res);
}
}
static BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
static int nextInt() throws Exception {
return Integer.parseInt(next());
}
static double nextDouble() throws Exception {
return Double.parseDouble(next());
}
static String next() throws Exception {
while (true) {
if (tokenizer.hasMoreTokens()) {
return tokenizer.nextToken();
}
String s = br.readLine();
if (s == null) {
return null;
}
tokenizer = new StringTokenizer(s);
}
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
import java.lang.management.*;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static java.lang.Math.max;
import static java.lang.Math.sqrt;
import static java.lang.Integer.signum;
@SuppressWarnings("unchecked")
public class P1177B {
public void run() throws Exception {
for (long k = nextLong() - 1, d = 1, dc = 9, sv = 1; true; k -= dc, d++, sv *= 10, dc = (sv * 10 - sv) * d) {
if (k <= dc) {
println(Long.toString(sv + k / d).charAt((int)(k % d)));
break;
}
}
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P1177B().run();
br.close();
pw.close();
System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]");
long gct = 0, gcc = 0;
for (GarbageCollectorMXBean garbageCollectorMXBean : ManagementFactory.getGarbageCollectorMXBeans()) {
gct += garbageCollectorMXBean.getCollectionTime();
gcc += garbageCollectorMXBean.getCollectionCount();
}
System.err.println("[GC time : " + gct + " ms, count = " + gcc + "]");
}
static long startTime = System.currentTimeMillis();
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { print("" + o); }
}
void printsp(int [] a) { for (int i = 0, n = a.length; i < n; print(a[i] + " "), i++); }
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
int gcd(int a, int b) {
if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a);
a = Math.abs(a); b = Math.abs(b);
int az = Integer.numberOfTrailingZeros(a), bz = Integer.numberOfTrailingZeros(b);
a >>>= az; b >>>= bz;
while (a != b) {
if (a > b) { a -= b; a >>>= Integer.numberOfTrailingZeros(a); }
else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); }
}
return (a << Math.min(az, bz));
}
long gcd(long a, long b) {
if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a);
a = Math.abs(a); b = Math.abs(b);
int az = Long.numberOfTrailingZeros(a), bz = Long.numberOfTrailingZeros(b);
a >>>= az; b >>>= bz;
while (a != b) {
if (a > b) { a -= b; a >>>= Long.numberOfTrailingZeros(a); }
else { b -= a; b >>>= Long.numberOfTrailingZeros(b); }
}
return (a << Math.min(az, bz));
}
void shuffle(int [] a) { // RANDOM shuffle
Random r = new Random();
for (int i = a.length - 1, j, t; i >= 0; j = r.nextInt(a.length), t = a[i], a[i] = a[j], a[j] = t, i--);
}
void shuffle(int [] a, int m) { // QUICK shuffle
for (int i = 0, n = a.length, j = m % n, t; i < n; t = a[i], a[i] = a[j], a[j] = t, i++, j = (i * m) % n);
}
void shuffle(long [] a) {
Random r = new Random();
for (int i = a.length - 1; i >= 0; i--) {
int j = r.nextInt(a.length);
long t = a[i]; a[i] = a[j]; a[j] = t;
}
}
void shuffle(Object [] a) {
Random r = new Random();
for (int i = a.length - 1; i >= 0; i--) {
int j = r.nextInt(a.length);
Object t = a[i]; a[i] = a[j]; a[j] = t;
}
}
int [] sort(int [] a) {
final int SHIFT = 16, MASK = (1 << SHIFT) - 1, SIZE = (1 << SHIFT) + 1;
int n = a.length, ta [] = new int [n], ai [] = new int [SIZE];
for (int i = 0; i < n; ai[(a[i] & MASK) + 1]++, i++);
for (int i = 1; i < SIZE; ai[i] += ai[i - 1], i++);
for (int i = 0; i < n; ta[ai[a[i] & MASK]++] = a[i], i++);
int [] t = a; a = ta; ta = t;
ai = new int [SIZE];
for (int i = 0; i < n; ai[(a[i] >> SHIFT) + 1]++, i++);
for (int i = 1; i < SIZE; ai[i] += ai[i - 1], i++);
for (int i = 0; i < n; ta[ai[a[i] >> SHIFT]++] = a[i], i++);
return ta;
}
void flush() {
pw.flush();
}
void pause() {
flush(); System.console().readLine();
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Bag implements Runnable {
private void solve() throws IOException {
int xs = nextInt();
int ys = nextInt();
int n = nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; ++i) {
x[i] = nextInt();
y[i] = nextInt();
}
final int[][] pair = new int[n][n];
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]);
final int[] single = new int[n];
for (int i = 0; i < n; ++i) {
single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys));
}
final int[] best = new int[1 << n];
final int[] prev = new int[1 << n];
for (int set = 1; set < (1 << n); ++set) {
int i;
for (i = 0; i < n; ++i)
if ((set & (1 << i)) != 0)
break;
int bestC = best[set ^ (1 << i)] + single[i];
int prevC = 1 << i;
int nextSet = set ^ (1 << i);
int unoI = 1 << i;
int msc = set >> (i + 1);
for (int j = i + 1, unoJ = 1 << (i + 1); msc != 0 && j < n; ++j, unoJ <<= 1, msc >>= 1)
if ((msc & 1) != 0) {
int cur = best[nextSet ^ unoJ] + pair[i][j];
if (cur < bestC) {
bestC = cur;
prevC = unoI | unoJ;
}
}
best[set] = bestC;
prev[set] = prevC;
}
writer.println(best[(1 << n) - 1]);
int now = (1 << n) - 1;
writer.print("0");
while (now > 0) {
int differents = prev[now];
for(int i = 0; i < n; i++)
if((differents & (1 << i)) != 0)
{
writer.print(" ");
writer.print(i + 1);
now ^= 1 << i;
}
writer.print(" ");
writer.print("0");
}
writer.println();
}
public static void main(String[] args) {
new Bag().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
public class test{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int m=s.nextInt();
int arr[]=new int[n];
int max = Integer.MIN_VALUE;
long sum = 0;
for(int i=0;i<n;i++)
{
arr[i] = s.nextInt();
sum = sum + arr[i];
max = Math.max(max,arr[i]);
}
Arrays.sort(arr);
int i = 0;
int count = 0;
int d = 0;
for(i=0; i<n; i++)
{
if(arr[i] > d)
{
count++;
d++;
}
else if(arr[i] == d && arr[i] > 0)
{
count++;
}
}
//System.out.println(count + " " + max);
if(max - d > 0)
{
count = count + max - d;
}
System.out.println(sum - count);}}
|
nlogn
|
1061_B. Views Matter
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Stack;
public class sample {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n+n/2);
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
// import java.awt.Point;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
long MOD = 1_000_000_007;
int inf = Integer.MAX_VALUE;
void solve()
{
int n = ni();
int[] a = new int[n];
for(int i = 0; i < n; i++){
a[i] = ni();
}
long ans = 0;
for(int i = 0; i < n; i++){
for(int j = i+1; j < n; j++){
if(a[j]<a[i]) ans++;
}
}
if(ans%2==0) ans = 0;
else ans = 1;
int m = ni();
for(int i = 0; i < m; i++){
long s = nl();
long g = nl();
long sub = g-s;
long res = sub*(sub+1)/2;
if(res%2==1) ans = 1 - ans;
if(ans==0) out.println("even");
else out.println("odd");
}
}
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];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b) && b != ' ')){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
/*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static long MOD = 1000L * 1000L * 1000L + 7;
private static final int[] dx = {0, -1, 0, 1};
private static final int[] dy = {1, 0, -1, 0};
private static final String yes = "Yes";
private static final String no = "No";
int n;
int m;
char[][] mat;
long base = 397;
void solve() throws IOException {
n = nextInt();
m = nextInt();
mat = new char[n][m];
for (int i = 0; i < n; i++) {
mat[i] = nextString().toCharArray();
}
int alpha = 26;
long[] pow = new long[alpha];
pow[0] = 1;
for (int i = 1; i < alpha; i++) {
pow[i] = pow[i - 1] * base % MOD;
}
long res = 0;
for (int l = 0; l < m; l++) {
//[l, r]
long[] hash = new long[n];
long[] mask = new long[n];
for (int r = l; r < m; r++) {
for (int i = 0; i < n; i++) {
hash[i] += pow[mat[i][r] - 'a'];
hash[i] %= MOD;
mask[i] = mask[i] ^ (1L << (mat[i][r] - 'a'));
}
int start = 0;
while (start < n) {
if ((mask[start] & (mask[start] - 1)) != 0) {
start++;
continue;
}
int end = start;
List<Long> l1 = new ArrayList<>();
while (end < n && (mask[end] & (mask[end] - 1)) == 0) {
l1.add(hash[end]);
end++;
}
start = end;
res += manacher(l1);
}
}
}
outln(res);
}
long manacher(List<Long> arr) {
int len = arr.size();
long[] t = new long[len * 2 + 3];
t[0] = -1;
t[len * 2 + 2] = -2;
for (int i = 0; i < len; i++) {
t[2 * i + 1] = -3;
t[2 * i + 2] = arr.get(i);
}
t[len * 2 + 1] = -3;
int[] p = new int[t.length];
int center = 0, right = 0;
for (int i = 1; i < t.length - 1; i++) {
int mirror = 2 * center - i;
if (right > i) {
p[i] = Math.min(right - i, p[mirror]);
}
// attempt to expand palindrome centered at i
while (t[i + (1 + p[i])] == t[i - (1 + p[i])]) {
p[i]++;
}
// if palindrome centered at i expands past right,
// adjust center based on expanded palindrome.
if (i + p[i] > right) {
center = i;
right = i + p[i];
}
}
long res = 0;
for (int i = 0; i < 2 * len; i++) {
int parLength = p[i + 2];
if (i % 2 == 0) {
res += (parLength + 1) / 2;
}
else {
res += parLength / 2;
}
}
return res;
}
void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
private void formatPrint(double val) {
outln(String.format("%.9f%n", val));
}
public CFA() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFA();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
nlogn
|
1080_E. Sonya and Matrix Beauty
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class Main implements Runnable {
private BufferedReader br;
private StringTokenizer tok;
private PrintWriter out;
static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
int[] a;
int[] b;
int[] p;
int getCeils(int id, int step) {
if (step > a[id] + b[id] - 1) {
return 0;
}
if (a[id] < b[id]) {
if (step < a[id]) {
return step;
}
if (step >= a[id] && step <= b[id]) {
return a[id];
}
++p[id];
return a[id] - p[id];
} else {
if (step < b[id]) {
return step;
}
if (step >= b[id] && step <= a[id]) {
return b[id];
}
++p[id];
return b[id] - p[id];
}
}
void solve() throws IOException {
int n = nextInt(), x = nextInt(), y = nextInt(), c = nextInt();
long s = 1;
int step = 0;
a = new int[4];
b = new int[4];
p = new int[4];
a[0] = x - 1; b[0] = n - y;
a[1] = x - 1; b[1] = y - 1;
a[2] = n - x; b[2] = y - 1;
a[3] = n - x; b[3] = n - y;
int xf = x + 1, xb = x - 1, yf = y + 1, yb = y - 1;
while (s < c) {
++step;
if (xf <= n) {
++s;
++xf;
}
if (xb > 0) {
++s;
--xb;
}
if (yf <= n) {
++s;
++yf;
}
if (yb > 0) {
++s;
--yb;
}
if (step == 1) {
continue;
}
for (int i = 0; i < 4; ++i) {
s += getCeils(i, step - 1);
}
}
out.println(step);
}
public void run() {
try {
if (ONLINE_JUDGE) {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
br = new BufferedReader(new FileReader(new File("input.txt")));
out = new PrintWriter(new File("output.txt"));
}
solve();
br.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
new Main().run();
}
String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
String nextString() throws IOException {
return nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BigInteger nextBigInteger() throws IOException {
return new BigInteger(nextToken());
}
}
|
logn
|
256_B. Mr. Bender and Square
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;
public class F {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
int N = scanner.nextInt();
int M = scanner.nextInt();
int[][] matrix = new int[N][M];
for(int i = 0; i < N; i++) {
for(int j = 0; j < M; j++) {
matrix[i][j] = scanner.nextInt();
}
}
int[][] maxDist = new int[N][N];
for(int i = 0; i < N; i++) {
Arrays.fill(maxDist[i], Integer.MAX_VALUE);
}
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
for(int k = j+1; k < N; k++) {
maxDist[j][k] = Math.min(maxDist[j][k], Math.abs(matrix[k][i] - matrix[j][i]));
maxDist[k][j] = maxDist[j][k];
}
}
}
int[][] distTop = new int[N][N];
for(int i = 0; i < N; i++) {
Arrays.fill(distTop[i], Integer.MAX_VALUE);
}
for(int i = 0; i < M-1; i++) {
for(int j = 0; j < N; j++) {
for(int k = 0; k < N; k++) {
distTop[j][k] = Math.min(distTop[j][k], Math.abs(matrix[j][i] - matrix[k][i+1]));
}
}
}
if (N == 1) {
System.out.println(distTop[0][0]);
System.exit(0);
}
int[] bitLoc = new int[1<<N];
for(int i = 0; i < N; i++) {
bitLoc[1 << i] = i;
}
int[][][] dp = new int[1<<N][N][N];
//iterate over every row
for(int mask = 1; mask < (1 << N); mask++) {
for(int smask = mask; smask > 0; smask &= (smask-1)) {
int i = bitLoc[Integer.lowestOneBit(smask)];
for (int ss = mask ^ 1 << i; ss > 0; ss &= ss - 1) {
int j = bitLoc[Integer.lowestOneBit(ss)];
if (mask == (1 << i ^ 1 << j))
dp[mask][i][j] = maxDist[i][j];
else {
int x = 0;
for (int sss = mask ^ 1 << i ^ 1 << j; sss > 0; sss &= sss - 1) {
int k = bitLoc[sss & -sss];
x = Math.max(x, Math.min(dp[mask ^ 1 << j][i][k], maxDist[k][j]));
}
dp[mask][i][j] = x;
}
}
}
}
int mxMsk = (1 << N) -1;
int max = 0;
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
if (i==j) continue;
max = Math.max(max, Math.min(dp[mxMsk][i][j], distTop[i][j]));
}
}
System.out.println(max);
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
}
}
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import java.util.Scanner;
public class LuckyDivision {
public static void main (String[] args) {
Scanner read = new Scanner(System.in);
int n = read.nextInt();
if (n % 4 == 0 ||
n % 7 == 0 ||
n % 47 == 0 ||
n % 74 == 0 ||
n % 447 == 0 ||
n % 474 == 0 ||
n % 477 == 0 ||
n % 744 == 0 ||
n % 747 == 0 ||
n % 774 == 0) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.Map.Entry;
public class Template {
String fileName = "";
long INF = Long.MAX_VALUE / 3;
int MODULO = 1000*1000*1000+7;
long[] fenwik;
int BORDER = 1000*1000+100;
void solve() throws IOException {
int n = readInt();
int[] a = new int[n];
for(int i=0; i<n; ++i){
a[i] = readInt();
}
fenwik = new long[BORDER];
long ans = 0;
for(int i=n-1;i>=0;--i){
ans+=sumFenwik(a[i]);
incFenwik(a[i],1);
}
boolean even = ans % 2 == 0;
int m = readInt();
for(int i=0; i<m; ++i){
int l = readInt();
int r = readInt();
if(((r-l+1)/2)%2==1){
even = !even;
}
out.println(even?"even":"odd");
}
}
void incFenwik(int i, int delta){
for(;i<BORDER;i = i|(i+1)){
fenwik[i]+=delta;
}
}
long sumFenwik(int r){
long sum = 0;
for(;r>=0;r = (r&(r+1))-1){
sum+=fenwik[r];
}
return sum;
}
int gcd(int a, int b){
return b == 0 ? a : gcd(b, a%b);
}
long binPow(long a, long b, long m) {
if (b == 0) {
return 1;
}
if (b % 2 == 1) {
return ((a % m) * (binPow(a, b - 1, m) % m)) % m;
} else {
long c = binPow(a, b / 2, m);
return (c * c) % m;
}
}
class Fenwik {
long[] t;
int length;
Fenwik(int[] a) {
length = a.length + 100;
t = new long[length];
for (int i = 0; i < a.length; ++i) {
inc(i, a[i]);
}
}
void inc(int ind, int delta) {
for (; ind < length; ind = ind | (ind + 1)) {
t[ind] += delta;
}
}
long getSum(int r) {
long sum = 0;
for (; r >= 0; r = (r & (r + 1)) - 1) {
sum += t[r];
}
return sum;
}
}
class SegmentTree {
int[] t;
SegmentTree(int[] a) {
int n = a.length - 1;
t = new int[n * 4];
build(a, 1, 1, n);
}
void build(int[] a, int v, int tl, int tr) {
if (tl == tr) {
t[v] = a[tl];
return;
}
int mid = (tr + tl) / 2;
build(a, 2 * v, tl, mid);
build(a, 2 * v + 1, mid + 1, tr);
t[v] = Math.max(t[2 * v], t[2 * v + 1]);
}
void update(int v, int tl, int tr, int pos, int value) {
if (tl == tr) {
t[v] = value;
return;
}
int mid = (tl + tr) / 2;
if (pos <= mid) {
update(2 * v, tl, mid, pos, value);
} else {
update(2 * v + 1, mid + 1, tr, pos, value);
}
t[v] = Math.max(t[2 * v], t[2 * v + 1]);
}
int getMax(int v, int tl, int tr, int l, int r) {
if (l > r) {
return -1000 * 1000;
}
if (tl == tr) {
return t[v];
}
if (l == tl && r == tr) {
return t[v];
}
int mid = (tl + tr) / 2;
int max1 = getMax(2 * v, tl, mid, l, Math.min(mid, r));
int max2 = getMax(2 * v + 1, mid + 1, tr, Math.max(mid + 1, l), r);
return Math.max(max1, max2);
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
new Template().run();
}
void run() throws NumberFormatException, IOException {
solve();
out.close();
};
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
String delim = " ";
Random rnd = new Random();
Template() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
if (fileName.isEmpty()) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader(fileName + ".in"));
out = new PrintWriter(fileName + ".out");
}
}
tok = new StringTokenizer("");
}
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) {
return null;
}
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt() throws NumberFormatException, IOException {
return Integer.parseInt(readString());
}
long readLong() throws NumberFormatException, IOException {
return Long.parseLong(readString());
}
double readDouble() throws NumberFormatException, IOException {
return Double.parseDouble(readString());
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.*;
import java.util.*;
/*
* Heart beats fast
* Colors and promises
* How to be brave
* How can I love when I am afraid...
*/
public class Main
{
public static void main(String[] args)
{
long x=nl(),k=nl();
if(x==0)
{
pr(0);
exit();
}
x%=mod;
pr((((x*powm(2,k+1,mod))%mod-powm(2,k,mod)+1)%mod+mod)%mod);
System.out.print(output);
}
///////////////////////////////////////////
///////////////////////////////////////////
///template from here
static class pair
{
long a, b;
pair(){}
pair(long c,long d){a=c;b=d;}
}
static interface combiner
{
public long combine(long a, long b);
}
static final int mod=1000000007;
static final double eps=1e-9;
static final long inf=100000000000000000L;
static Reader in=new Reader();
static StringBuilder output=new StringBuilder();
static Random rn=new Random();
static void reverse(int[]a){for(int i=0; i<a.length/2; i++){a[i]^=a[a.length-i-1];a[a.length-i-1]^=a[i];a[i]^=a[a.length-i-1];}}
static void sort(int[]a)
{
int te;
for(int i=0; i<a.length; i+=2)
{
te=rn.nextInt(a.length);
if(i!=te)
{
a[i]^=a[te];
a[te]^=a[i];
a[i]^=a[te];
}
}
Arrays.sort(a);
}
static void sort(long[]a)
{
int te;
for(int i=0; i<a.length; i+=2)
{
te=rn.nextInt(a.length);
if(i!=te)
{
a[i]^=a[te];
a[te]^=a[i];
a[i]^=a[te];
}
}
Arrays.sort(a);
}
static void sort(double[]a)
{
int te;
double te1;
for(int i=0; i<a.length; i+=2)
{
te=rn.nextInt(a.length);
if(i!=te)
{
te1=a[te];
a[te]=a[i];
a[i]=te1;
}
}
Arrays.sort(a);
}
static void sort(int[][]a)
{
Arrays.sort(a, new Comparator<int[]>()
{
public int compare(int[]a,int[]b)
{
if(a[0]>b[0])
return -1;
if(b[0]>a[0])
return 1;
return 0;
}
});
}
static void sort(pair[]a)
{
Arrays.sort(a,new Comparator<pair>()
{
@Override
public int compare(pair a,pair b)
{
if(a.a>b.a)
return 1;
if(b.a>a.a)
return -1;
return 0;
}
});
}
static int log2n(long a)
{
int te=0;
while(a>0)
{
a>>=1;
++te;
}
return te;
}
static class vector implements Iterable<Integer>
{
int a[],size;
vector(){a=new int[10];size=0;}
vector(int n){a=new int[n];size=0;}
public void add(int b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;}
public void sort(){Arrays.sort(a, 0, size);}
public void sort(int l, int r){Arrays.sort(a, l, r);}
@Override
public Iterator<Integer> iterator() {
Iterator<Integer> hola=new Iterator<Integer>()
{
int cur=0;
@Override
public boolean hasNext() {
return cur<size;
}
@Override
public Integer next() {
return a[cur++];
}
};
return hola;
}
}
//output functions////////////////
static void pr(Object a){output.append(a+"\n");}
static void pr(){output.append("\n");}
static void p(Object a){output.append(a);}
static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");}
static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");}
static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");}
static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");}
static void sop(Object a){System.out.println(a);}
static void flush(){System.out.println(output);output=new StringBuilder();}
//////////////////////////////////
//input functions/////////////////
static int ni(){return Integer.parseInt(in.next());}
static long nl(){return Long.parseLong(in.next());}
static String ns(){return in.next();}
static double nd(){return Double.parseDouble(in.next());}
static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;}
static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;}
static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;}
static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;}
static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;}
//////////////////////////////////
//some utility functions
static void exit(){System.out.print(output);System.exit(0);}
static int min(int... a){int min=a[0];for(int i:a)min=Math.min(min, i);return min;}
static int max(int... a){int max=a[0];for(int i:a)max=Math.max(max, i);return max;}
static int gcd(int... a){int gcd=a[0];for(int i:a)gcd=gcd(gcd, i);return gcd;}
static long min(long... a){long min=a[0];for(long i:a)min=Math.min(min, i);return min;}
static long max(long... a){long max=a[0];for(long i:a)max=Math.max(max, i);return max;}
static long gcd(long... a){long gcd=a[0];for(long i:a)gcd=gcd(gcd, i);return gcd;}
static String pr(String a, long b){String c="";while(b>0){if(b%2==1)c=c.concat(a);a=a.concat(a);b>>=1;}return c;}
static long powm(long a, long b, long m)
{long an=1;long c=a;while(b>0)
{if(b%2==1)an=(an*c)%m;c=(c*c)%m;b>>=1;}return an;}
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 class Reader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Reader() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.Random;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
E2RotateColumnsHardVersion solver = new E2RotateColumnsHardVersion();
int testCount = in.scanInt();
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class E2RotateColumnsHardVersion {
int[][] dp;
int[] cur;
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int m = in.scanInt();
int[][] ar = new int[n][m];
int[][] max = new int[m][2];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
ar[i][j] = in.scanInt();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) max[i][0] = Math.max(max[i][0], ar[j][i]);
max[i][1] = i;
}
CodeHash.shuffle(max);
Arrays.sort(max, (o1, o2) -> -o1[0] + o2[0]);
dp = new int[2][1 << n];
cur = new int[1 << n];
for (int i = 0; i < Math.min(m, n); i++) {
Arrays.fill(dp[i & 1], 0);
for (int k = 0; k < n; k++) {
System.arraycopy(dp[(i - 1) & 1], 0, cur, 0, 1 << n);
for (int l = 0; l < n; l++) {
for (int j = 0; j < 1 << n; j++) {
if ((j & (1 << l)) == 0) {
cur[j ^ (1 << l)] = Math.max(cur[j ^ (1 << l)], cur[j] + ar[(k + l) % n][max[i][1]]);
}
}
}
for (int j = 0; j < 1 << n; j++) dp[i & 1][j] = Math.max(dp[i & 1][j], cur[j]);
}
}
out.println(dp[Math.min(n, m) & 1 ^ 1][(1 << n) - 1]);
}
}
static class CodeHash {
public static void shuffle(int[][] ar) {
Random rd = new Random(new Random().nextInt());
for (int i = 0; i < ar.length; i++) {
int index = rd.nextInt(ar.length);
int[] temp = ar[i];
ar[i] = ar[index];
ar[index] = temp;
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (total <= 0) return -1;
}
return buf[index++];
}
public int scanInt() {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class main
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private PrintWriter pw;
private long mod = 1000000000 + 7;
private StringBuilder ans_sb;
private ArrayList<Integer> primes;
private long ans;
private void soln()
{
int n = nextInt();
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
Segment tree = new Segment(n, arr);
long[] ans = new long[n];
BigInteger fa = BigInteger.ZERO;
HashMap<Long, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++)
{
ans[i] = ((long) i + 1) * arr[i] - tree.query(0, i);
if (map.containsKey(arr[i] - 1))
{
long tmp = map.get(arr[i] - 1);
ans[i] -= tmp;
}
if (map.containsKey(arr[i] + 1))
{
long tmp = map.get(arr[i] + 1);
ans[i] += tmp;
}
if (!map.containsKey(arr[i]))
map.put(arr[i], 0);
map.put(arr[i], map.get(arr[i]) + 1);
fa = fa.add(new BigInteger(Long.toString(ans[i])));
}
// debug(ans);
/*
* Node[] nn = new Node[n]; for(int i=0;i<n;i++) { nn[i] = new Node();
* nn[i].node = i; nn[i].dist = arr[i]; } //debug(fa); Arrays.sort(nn);
* //debug(nn); for(int i=0;i<n-1;i++) { if(nn[i].dist + 1 == nn[i+1].dist) {
* System.out.println(nn[i].node +" "+nn[i+1].node); if(nn[i].node >
* nn[i+1].node) { fa++; }else fa--; } }
*/
pw.println(fa.toString());
// int k = nextInt();
// int n = nextInt();
// String[] arr = new String[k];
// for(int i=0;i<k;i++)
// arr[i] = nextLine();
// HashSet<String> set1 = new HashSet<>();
// for(int i=0;i<k;i++)
// set1.add(arr[i]);
// if(set1.size() == 1) {
// String s = arr[0];
// pw.print(s.charAt(1));
// pw.print(s.charAt(0));
// for(int i=2;i<n;i++)
// pw.print(s.charAt(i));
// }else {
// String s1 = arr[0];
// set1.remove(arr[0]);
// HashSet<Integer>[] aa = new HashSet[set1.size()];
// ArrayList<String> set = new ArrayList<>();
// for(String s:set1)
// set.add(s);
// int k1 = 0;
// boolean f1 = false;
// for(String s:set) {
// aa[k1] = new HashSet<>();
// for(int i=0;i<n;i++)
// if(s1.charAt(i) != s.charAt(i))
// aa[k1].add(i);
// if(aa[k1].size() > 4) {
// pw.println(-1);
// f1 = true;
// }
// k1++;
// }
// //debug(set);
// char[] ch = s1.toCharArray();
//
// boolean[] f11 = new boolean[set.size()];
// int k2 = 0;
// for(String s:set) {
// int[] freq = new int[26];
// for(int i=0;i<n;i++)
// freq[s.charAt(i)-'a']++;
// boolean kuu = false;
// for(int i=0;i<26;i++)
// if(freq[i] >= 2) {
// kuu = true;
// break;
// }
// f11[k2] = true;
// k2++;
// }
// // debug(f11);
//
// for(int i=0;i<n;i++) {
// if(f1)
// break;
// for(int j=i+1;j<n;j++) {
// if(f1)
// break;
// //System.out.println(i+" "+j);
// char tmp = ch[i];
// ch[i] = ch[j];
// ch[j] = tmp;
// k1 = 0;
// HashSet<Integer> haha = new HashSet<>();
// boolean f = true;
// for(String s:set) {
// HashSet<Integer> indi = aa[k1];
// boolean h1 = false;
// boolean h2 = false;
// if(!indi.contains(i)) {
// indi.add(i);
// h1 = true;
// }
// if(!indi.contains(j)) {
// indi.add(j);
// h2 = true;
// }
// int cnt = 0;
// for(int ii:indi) {
// if(s.charAt(ii) != ch[ii])
// cnt++;
// }
// /*if(i==1 && j==3) {
// System.out.println(cnt+" "+i+" "+j+" "+s);
// debug(indi);
// }*/
// if(cnt > 2 ) {
// f = false;
// break;
// }
// if(cnt ==1 && !f11[k1]) {
// f = false;
// break;
// }
// if(h1)
// indi.remove(i);
// if(h2)
// indi.remove(j);
// k1++;
//
// }
// if(f) {
// for(int i1=0;i1<n;i1++) {
// pw.print(ch[i1]);
// }
// f1 = true;
// break;
// }
// tmp = ch[i];
// ch[i] = ch[j];
// ch[j] = tmp;
// }
// }
// if(!f1)
// pw.println(-1);
// }
}
public class Segment
{
private Node[] tree;
private boolean[] lazy;
private int size;
private int n;
private long[] base;
private class Node
{
private int l;
private int r;
private long ans;
private long ans2;
}
public Segment(int n, long[] arr)
{
this.base = arr;
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
size = 2 * (int) Math.pow(2, x) - 1;
tree = new Node[size];
lazy = new boolean[size];
this.n = n;
// this.set = set1;
build(0, 0, n - 1);
}
public void build(int id, int l, int r)
{
if (l == r)
{
tree[id] = new Node();
tree[id].l = l;
tree[id].r = r;
tree[id].ans = base[l];
return;
}
int mid = (l + r) / 2;
build(2 * id + 1, l, mid);
build(2 * id + 2, mid + 1, r);
tree[id] = merge(tree[2 * id + 1], tree[2 * id + 2], l, r);
// System.out.println(l+" "+r+" "+tree[id].l+" "+tree[id].r+" "+tree[id].ans);
}
public Node merge(Node n1, Node n2, int l, int r)
{
Node ret = new Node();
if (n1 == null && n2 == null)
return null;
else if (n1 == null)
{
ret.ans = n2.ans;
}
else if (n2 == null)
{
ret.ans = n1.ans;
} else
{
ret.ans = n1.ans + n2.ans;
}
return ret;
}
public long query(int l, int r)
{
Node ret = queryUtil(l, r, 0, 0, n - 1);
if (ret == null)
{
return 0;
} else
return ret.ans;
}
private Node queryUtil(int x, int y, int id, int l, int r)
{
if (l > y || x > r)
return null;
if (x <= l && r <= y)
{
return tree[id];
}
int mid = l + (r - l) / 2;
// shift(id);
Node q1 = queryUtil(x, y, 2 * id + 1, l, mid);
Node q2 = queryUtil(x, y, 2 * id + 2, mid + 1, r);
return merge(q1, q2, Math.max(l, x), Math.min(r, y));
}
public void update(int x, int y, int c)
{
update1(x, y, c, 0, 0, n - 1);
}
private void update1(int x, int y, int colour, int id, int l, int r)
{
// System.out.println(l+" "+r+" "+x);
if (x > r || y < l)
return;
if (x <= l && r <= y)
{
if (colour != -1)
{
tree[id] = new Node();
tree[id].ans = 1;
} else
tree[id] = null;
return;
}
int mid = l + (r - l) / 2;
// shift(id);
if (y <= mid)
update1(x, y, colour, 2 * id + 1, l, mid);
else if (x > mid)
update1(x, y, colour, 2 * id + 2, mid + 1, r);
else
{
update1(x, y, colour, 2 * id + 1, l, mid);
update1(x, y, colour, 2 * id + 2, mid + 1, r);
}
tree[id] = merge(tree[2 * id + 1], tree[2 * id + 2], l, r);
}
public void print(int l, int r, int id)
{
if (l == r)
{
if (tree[id] != null)
System.out.println(l + " " + r + " " + tree[id].l + " " + tree[id].r + " " + tree[id].ans + " "
+ tree[id].ans2);
return;
}
int mid = l + (r - l) / 2;
print(l, mid, 2 * id + 1);
print(mid + 1, r, 2 * id + 2);
if (tree[id] != null)
System.out.println(
l + " " + r + " " + tree[id].l + " " + tree[id].r + " " + tree[id].ans + " " + tree[id].ans2);
}
public void shift(int id)
{
}
}
private class Node implements Comparable<Node>
{
int node;
long dist;
@Override
public int compareTo(Node arg0)
{
if (this.dist != arg0.dist)
return (int) (this.dist - arg0.dist);
return this.node - arg0.node;
}
public boolean equals(Object o)
{
if (o instanceof Node)
{
Node c = (Node) o;
return this.node == c.node && this.dist == c.dist;
}
return false;
}
public String toString()
{
return this.node + ", " + this.dist;
}
}
private void debug(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
private long pow(long a, long b, long c)
{
if (b == 0)
return 1;
long p = pow(a, b / 2, c);
p = (p * p) % c;
return (b % 2 == 0) ? p : (a * p) % c;
}
private long gcd(long n, long l)
{
if (l == 0)
return n;
return gcd(l, n % l);
}
public static void main(String[] args) throws Exception
{
new Thread(null, new Runnable()
{
@Override
public void run()
{
new main().solve();
}
}, "1", 1 << 26).start();
}
public StringBuilder solve()
{
InputReader(System.in);
/*
* try { InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\in.txt"));
* } catch(FileNotFoundException e) {}
*/
pw = new PrintWriter(System.out);
ans_sb = new StringBuilder();
soln();
pw.close();
// System.out.println(ans_sb);
return ans_sb;
}
public void InputReader(InputStream stream1)
{
stream = stream1;
}
private boolean isWhitespace(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
private int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
private 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;
}
private 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;
}
private String nextToken()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private 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();
}
private int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
private long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private void pArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private void pArray(long[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private char nextChar()
{
int c = read();
while (isSpaceChar(c))
c = read();
char c1 = (char) c;
while (!isSpaceChar(c))
c = read();
return c1;
}
private interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class C {
private static FastReader fr = new FastReader();
private static PrintWriter out=new PrintWriter(System.out);
private static Random random = new Random();
public static void main(String[] args) throws IOException {
StringBuilder sb = new StringBuilder();
// code goes here
int t = fr.nextInt();
while (t-- > 0){
int n = fr.nextInt();
int[] arr = fr.nextIntArray(n);
sb.append(1).append("\n");
List<Integer> state = new ArrayList<>();
state.add(1);
for(int i = 1; i < n; i++){
List<Integer> nextState = new ArrayList<>();
boolean found = false;
int till = -1;
for(int j = state.size() - 1; j >= 0; j--){
if(state.get(j) + 1 == arr[i]){
till = j;
found = true;
break;
}
}
if(found){
for(int j = 0; j < till; j++){
nextState.add(state.get(j));
}
nextState.add(arr[i]);
sb.append(nextState.get(0));
for(int z = 1; z < nextState.size(); z++){
sb.append(".").append(nextState.get(z));
}
sb.append("\n");
}
if(!found){
nextState.addAll(state);
nextState.add(arr[i]);
sb.append(nextState.get(0));
for(int z = 1; z < nextState.size(); z++){
sb.append(".").append(nextState.get(z));
}
sb.append("\n");
}
state = nextState;
}
}
System.out.print(sb.toString());
}
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastReader{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public long[] nextLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
static class Pair<A, B>{
A first;
B second;
public Pair(A first, B second){
this.first = first;
this.second = second;
}
}
static long mod(String num, long a)
{
// Initialize result
long res = 0;
// One by one process all digits of 'num'
for (int i = 0; i < num.length(); i++)
res = (res*10 + num.charAt(i) - '0') %a;
return res;
}
static long binomialCoeff(long n, long k, long MOD)
{
long res = 1;
// Since C(n, k) = C(n, n-k)
if (k > n - k)
k = n - k;
// Calculate value of
// [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
for (int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
res %= MOD;
}
return res;
}
static long power(long x, long y, long p)
{
// Initialize result
long res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static long modInverse(long n, long p)
{
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static long nCrModPFermat(int n, int r,
long p)
{
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
long[] fac = new long[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
// Don't place your source in a package
import javax.swing.*;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.stream.Stream;
// Please name your class Main
public class Main {
static FastScanner fs=new FastScanner();
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int Int() {
return Integer.parseInt(next());
}
long Long() {
return Long.parseLong(next());
}
String Str(){
return next();
}
}
public static void main (String[] args) throws java.lang.Exception {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int T=1;
for(int t=0;t<T;t++){
int n=Int(),k=Int();
int A[][]=new int[n][2];
for(int i=0;i<n;i++){
A[i][0]=Int();
A[i][1]=Int();
}
Solution sol=new Solution(out);
sol.solution(A,k);
}
out.close();
}
public static int Int(){
return fs.Int();
}
public static long Long(){
return fs.Long();
}
public static String Str(){
return fs.Str();
}
}
class Solution{
PrintWriter out;
public Solution(PrintWriter out){
this.out=out;
}
long dp[][];
int mod=1000000007;
int time;
public void solution(int A[][],int t){
this.time=t;
dp=new long[4][1<<A.length+2];
for(int i=0;i<dp.length;i++){
Arrays.fill(dp[i],-1);
}
long a=dfs(A,0,(1<<A.length)-1);
out.println(a);
}
public long dfs(int A[][],int pre,int state){
int use=cal(A,state);
if(time-use==0){
return 1;
}
if(time<use||state==0){
return 0;
}
if(dp[pre][state]!=-1)return dp[pre][state];
long res=0;
for(int i=0;i<A.length;i++){
if(((state&(1<<i))!=0)&&A[i][1]!=pre){
res+=dfs(A,A[i][1],(state^(1<<i)));
res%=mod;
}
}
dp[pre][state]=res;
return res;
}
public int cal(int A[][],int state){
int t=0;
for(int i=0;i<A.length;i++){
if((state&(1<<i))==0){
t+=A[i][0];
}
}
return t;
}
}
/*
;\
|' \
_ ; : ;
/ `-. /: : |
| ,-.`-. ,': : |
\ : `. `. ,'-. : |
\ ; ; `-.__,' `-.|
\ ; ; ::: ,::'`:. `.
\ `-. : ` :. `. \
\ \ , ; ,: (\
\ :., :. ,'o)): ` `-.
,/,' ;' ,::"'`.`---' `. `-._
,/ : ; '" `;' ,--`.
;/ :; ; ,:' ( ,:)
,.,:. ; ,:., ,-._ `. \""'/
'::' `:'` ,'( \`._____.-'"'
;, ; `. `. `._`-. \\
;:. ;: `-._`-.\ \`.
'`:. : |' `. `\ ) \
-hrr- ` ;: | `--\__,'
'` ,'
,-'
free bug dog
*/
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class CF1082D {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] aa = new int[n];
int[] i1 = new int[n];
int[] i2 = new int[n];
int n1 = 0, n2 = 0, m2 = 0;
for (int i = 0; i < n; i++) {
int a = Integer.parseInt(st.nextToken());
aa[i] = a;
if (a == 1)
i1[n1++] = i;
else {
i2[n2++] = i;
m2 += a;
}
}
if (m2 < (n2 - 1) * 2 + n1) {
System.out.println("NO");
return;
}
int m = n2 - 1 + n1;
int d = n2 - 1 + Math.min(n1, 2);
PrintWriter pw = new PrintWriter(System.out);
pw.println("YES " + d);
pw.println(m);
for (int i = 0; i + 1 < n2; i++) {
pw.println((i2[i] + 1) + " " + (i2[i + 1] + 1));
aa[i2[i]]--; aa[i2[i + 1]]--;
}
if (n1 > 0) {
while (n2 > 0 && aa[i2[n2 - 1]] == 0)
n2--;
pw.println((i2[n2 - 1] + 1) + " " + (i1[n1 - 1] + 1));
aa[i2[n2 - 1]]--;
n1--;
}
for (int i = 0, j = 0; j < n1; j++) {
while (aa[i2[i]] == 0)
i++;
pw.println((i2[i] + 1) + " " + (i1[j] + 1));
aa[i2[i]]--;
}
pw.close();
}
}
|
linear
|
1082_D. Maximum Diameter Graph
|
CODEFORCES
|
import java.util.Scanner;
public class Composite {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if (n == 12)
System.out.println("4 8");
else if (n % 2 == 1)
System.out.println((n - 9) + " 9");
else
System.out.println((n - 6) + " 6");
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class A235 {
public static void main(String args[]) throws Exception{
BufferedReader ip = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(ip.readLine());
int a,b,c;
int x = 0,y = 0,z = 0;
BigInteger l,t;
if(n-2 > 1)
{
a = n;
b = n-1;
c = n-2;
}
else
{
a = n;
if(n-1 > 1)
b = n-1;
else
b = 1;
c = 1;
System.out.println(a*b);
return;
}
if(n-3 > 1)
{
x = n-1;
y = n-2;
z = n-3;
}
if(n % 2 == 0)
if(n % 3 == 0)
l = BigInteger.valueOf(x).multiply(BigInteger.valueOf(y).multiply(BigInteger.valueOf(z)));
else
{
l = BigInteger.valueOf(a).multiply(BigInteger.valueOf(b).multiply(BigInteger.valueOf(c-1)));
t = BigInteger.valueOf(x).multiply(BigInteger.valueOf(y).multiply(BigInteger.valueOf(z)));
if(l.compareTo(t) < 0)
l = t;
}
else
l = BigInteger.valueOf(a).multiply(BigInteger.valueOf(b).multiply(BigInteger.valueOf(c)));
System.out.println(l);
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class ProblemA_72 {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException{
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException{
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException{
return Integer.parseInt(readString());
}
public static void main(String[] args){
new ProblemA_72().run();
}
public void run(){
try{
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = "+(t2-t1));
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
void solve() throws IOException{
int n = readInt();
out.print((n + n/2));
}
static class MyAlgo{
long gcd(long a, long b){
if (a == 0) return b;
return gcd(b % a, a);
}
long lcm(long a, long b){
return a / gcd(a, b)*b;
}
long[] gcdPlus(long a, long b){
long[] d = new long[3];
if (a == 0){
d[0] = b;
d[1] = 0;
d[2] = 1;
}else{
d = gcdPlus(b % a, a);
long r = d[1];
d[1] = d[2] - b/a*d[1];
d[2] = r;
}
return d;
}
long binpow(long a, int n){
if (n == 0) return 1;
if ((n & 1) == 0){
long b = binpow(a, n/2);
return b*b;
}else return binpow(a, n-1)*a;
}
long binpowmod(long a, int n, int m){
if (n == 0) return 1;
if ((n & 1) == 0){
long b = binpow(a, n/2);
return (b*b) % m;
}else return binpow(a, n-1)*a % m;
}
long f(long n, int x, int k){ //Кол-во десятичных чисел (включая 0), содержащих в себе цифры от 0 до k-1
if (n == 0) return 1;
long b = binpow(10, x - 1);
long c = n / b;
return (c < k? c: k)*binpow(k, x - 1) + (c < k? 1: 0)*f(n % b, x - 1, k);
}
long fib(int n){
if (n == 0) return 0;
if ((n & 1) == 0){
long f1 = fib(n/2 - 1);
long f2 = fib(n/2 + 1);
return f2*f2 - f1*f1;
}else{
long f1 = fib(n/2);
long f2 = fib(n/2 + 1);
return f1*f1 + f2*f2;
}
}
BigInteger BigFib(int n){
if (n == 0) return BigInteger.ZERO;
if ((n & 1) == 0){
BigInteger f1 = BigFib(n/2 - 1);
f1 = f1.multiply(f1);
BigInteger f2 = BigFib(n/2 + 1);
f2 = f2.multiply(f2);
return f2.subtract(f1);
}else{
BigInteger f1 = BigFib(n/2);
f1 = f1.multiply(f1);
BigInteger f2 = BigFib(n/2 + 1);
f2 = f2.multiply(f2);
return f2.add(f1);
}
}
boolean IsProbablyPrime(long n){
if (n == 1) return false;
if ((n & 1) == 0) return false;
for (int j = 3; j < sqrt(n) + 1; j += 2){
if (n % j == 0) return false;
}
return true;
}
int[] Sieve(int n){
boolean[] b = new boolean[n+1];
Arrays.fill(b, true);
b[0] = false;
b[1] = false;
long nLong = n;
int j=0;
for (int i = 1; i <= n; i++) {
if (b[i]){
j++;
if (((long)i)*i <= nLong) {
for (int k = i*i; k <= n; k += i) {
b[k] = false;
}
}
}
}
int[] p = new int[j];
Arrays.fill(p, 0);
j=0;
for (int i = 2; i <= n; i++) {
if (b[i]){
p[j]=i;
j++;
}
}
return p;
}
public class Permutation {
int[] a;
int n;
public Permutation(int n){
this.n=n;
a=new int[n];
for (int i=0; i<n; i++){
a[i]=i;
}
}
public boolean nextPermutation(){ //Пишется с do{}while(nextPermutation(a));
int i=n-1;
for (i=n-2; i>=0; i--){
if (a[i]<a[i+1]){
break;
}
}
if (i==-1){
return false;
}
int jMin=i+1;
for (int j=n-1; j>i; j--){
if (a[i]<a[j]&&a[j]<a[jMin]){
jMin=j;
}
}
swap(i, jMin);
for (int j=1; j<=(n-i)/2; j++){
swap(i+j, n-j);
}
return true;
}
public int get(int i){
return a[i];
}
void swap(int i, int j){
int r=a[i];
a[i]=a[j];
a[j]=r;
}
}
public class Fraction implements Comparable<Fraction>, Cloneable{
public final Fraction FRACTION_ZERO = new Fraction();
public final Fraction FRACTION_ONE = new Fraction(1);
public long numerator = 0;
public long denominator = 1;
public Fraction(){
numerator = 0;
denominator = 1;
}
public Fraction(long numerator){
this.numerator = numerator;
denominator = 1;
}
public Fraction(long numerator, long denominator){
this.numerator = numerator;
this.denominator = denominator;
Cancellation();
}
public Fraction(double numerator, double denominator, int accuracy){
this.numerator = (long)(numerator*pow(10,accuracy));
this.denominator = (long)(denominator*pow(10,accuracy));
Cancellation();
}
public Fraction(String s){
if (s.charAt(0) == '-'){
denominator = -1;
s = s.substring(1);
}
if (s.indexOf("/") != -1){
denominator *= Integer.parseInt(s.substring(s.indexOf("/") + 1));
}
if (s.indexOf(" ") != -1){
numerator = Integer.parseInt(s.substring(0, s.indexOf(" "))) * abs(denominator) + Integer.parseInt(s.substring(s.indexOf(" ") + 1, s.indexOf("/")));
}else{
if (s.indexOf("/") != -1){
numerator = Integer.parseInt(s.substring(0, s.indexOf("/")));
}else{
numerator = Integer.parseInt(s)*abs(denominator);
}
}
this.Cancellation();
}
void Cancellation(){
long g = gcd(abs(numerator), abs(denominator));
numerator /= g;
denominator /= g;
if (denominator < 0){
numerator *= -1;
denominator *= -1;
}
}
public String toString(){
String s = "";
if (numerator == 0){
return "0";
}
if (numerator < 0){
s += "-";
}
if (abs(numerator) >= denominator){
s += Long.toString(abs(numerator) / denominator) + " ";
}
if (abs(numerator) % denominator != 0){
s += Long.toString(abs(numerator) % denominator);
}else{
s = s.substring(0, s.length()-1);
}
if (denominator != 1){
s += "/" + Long.toString(denominator);
}
return s;
}
public Fraction add(Fraction f){
Fraction fResult = new Fraction();
fResult.denominator = lcm(denominator, f.denominator);
fResult.numerator = numerator * fResult.denominator / denominator + f.numerator * fResult.denominator / f.denominator;
fResult.Cancellation();
return fResult;
}
public Fraction subtract(Fraction f){
Fraction fResult = new Fraction();
fResult.denominator = lcm(denominator, f.denominator);
fResult.numerator = numerator * fResult.denominator / denominator - f.numerator * fResult.denominator / f.denominator;
fResult.Cancellation();
return fResult;
}
public Fraction multiply(Fraction f){
Fraction fResult = new Fraction();
fResult.numerator = numerator * f.numerator;
fResult.denominator = denominator * f.denominator;
fResult.Cancellation();
return fResult;
}
public Fraction divide(Fraction f){
Fraction fResult = new Fraction();
fResult.numerator = numerator * f.denominator;
fResult.denominator = denominator * f.numerator;
fResult.Cancellation();
return fResult;
}
@Override
public int compareTo(Fraction f){
long g = gcd(denominator, f.denominator);
long res = numerator * (f.denominator / g) - f.numerator * (denominator / g);
if (res < 0){
return -1;
}
if (res > 0){
return 1;
}
return 0;
}
public Fraction clone(){
Fraction fResult = new Fraction(numerator, denominator);
return fResult;
}
public Fraction floor(){
Fraction fResult = this.clone();
fResult.numerator = (fResult.numerator / fResult.denominator) * fResult.denominator;
return fResult;
}
public Fraction ceil(){
Fraction fResult = this.clone();
fResult.numerator = (fResult.numerator/fResult.denominator + 1) * fResult.denominator;
return fResult;
}
public Fraction binpow(int n){
if (n==0) return FRACTION_ONE;
if ((n&1)==0){
Fraction f=this.binpow(n/2);
return f.multiply(f);
}else return binpow(n-1).multiply(this);
}
}
class FenwickTree_1{ //One-dimensional array
int n;
long[] t;
public FenwickTree_1(int n){
this.n = n;
t = new long[n];
}
public long sum(int xl, int xr){
return sum(xr) - sum(xl);
}
public long sum(int x){
long result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1){
result += t[i];
}
return result;
}
public void update(int x, long delta){
for (int i = x; i < n; i = (i | (i + 1))){
t[i] += delta;
}
}
}
class FenwickTree_2{ //Two-dimensional array
int n, m;
long[][] t;
public FenwickTree_2(int n, int m){
this.n = n;
this.m = m;
t = new long[n][m];
}
public long sum(int xl, int yl, int xr, int yr){
return sum(xr, yr) - sum(xl - 1, yr) - sum(xr, yl - 1) + sum(xl - 1, yl - 1);
}
public long sum(int x, int y){
long result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1){
for (int j = y; j >= 0; j = (j & (j + 1)) - 1){
result+=t[i][j];
}
}
return result;
}
public void update(int x, int y, long delta){
for (int i = x; i < n; i = (i | (i + 1))){
for (int j = y; j < m; j = (j | (j + 1))){
t[i][j] += delta;
}
}
}
}
class FenwickTree_3{ //Three-dimensional array
int n, m, l;
long[][][] t;
public FenwickTree_3(int n, int m, int l){
this.n = n;
this.m = m;
this.l = l;
t = new long[n][m][l];
}
public long sum(int xl, int yl, int zl, int xr, int yr, int zr){
return sum(xr, yr, zr) - sum(xl - 1, yr, zr)
+ sum(xl - 1, yr, zl - 1) - sum(xr, yr, zl - 1)
- sum(xr, yl - 1, zr) + sum(xl - 1, yl - 1, zr)
- sum(xl - 1, yl - 1, zl - 1) + sum(xr, yl - 1, zl - 1);
}
public long sum(int x, int y, int z){
long result = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1){
for (int j = y; j >= 0; j = (j & (j + 1)) - 1){
for (int k = z; k >= 0; k = (k & (k + 1)) - 1){
result += t[i][j][k];
}
}
}
return result;
}
public void update(int x, int y, int z, long delta){
for (int i = x; i < n; i = (i | (i + 1))){
for (int j = y; j < n; j = (j | (j + 1))){
for (int k = z; k < n; k = (k | (k + 1))){
t[i][j][k] += delta;
}
}
}
}
}
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class template {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
int n = sc.nextInt();
int k = sc.nextInt();
long left = 0;
long right = n;
long mid = left+right/2;
while(left<=right) {
mid = (left+(right))/2;
if(((mid+1)*mid)/2-(n-mid)==k) {
pw.println(n-mid);
pw.close();
break;
}
else if(((mid+1)*mid)/2-(n-mid)>k) {
right = mid-1;
}
else left = mid+1;
}
}
}
@SuppressWarnings("all")
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.*;
public class a {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n = input.nextInt(), m = input.nextInt(), k = input.nextInt();
int[] data = new int[n];
for(int i = 0; i<n; i++)
data[i] = input.nextInt();
Arrays.sort(data);
m -= k;
int at = n-1;
int count = 0;
while(at>=0 && m>0)
{
count++;
m++;
m -= data[at];
at--;
}
if(m>0)
System.out.println(-1);
else
System.out.println(count);
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class A {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
public void solve() throws IOException {
int N = nextInt();
if( N >= 0) {
out.println(N);
return;
}
int ans = N/10;
int ans2 = N/100*10 + N%10;
out.println( Math.max(ans, ans2));
}
/**
* @param args
*/
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
// discussed with rainboy
import java.io.*;
import java.util.*;
public class CF915D {
static ArrayList[] aa;
static boolean[] visited, instack;
static int[] stack;
static int cnt, h_, i_, j_;
static boolean dfs1(int i) {
if (visited[i]) {
if (instack[i]) {
h_ = i;
return true;
}
return false;
}
visited[i] = instack[i] = true;
stack[cnt++] = i;
ArrayList<Integer> adj = aa[i];
for (int j : adj)
if (dfs1(j))
return true;
instack[i] = false;
cnt--;
return false;
}
static boolean dfs2(int i) {
if (visited[i])
return instack[i];
visited[i] = instack[i] = true;
ArrayList<Integer> adj = aa[i];
for (int j : adj)
if (!(i == i_ && j == j_) && dfs2(j))
return true;
instack[i] = false;
return false;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
aa = new ArrayList[n];
for (int i = 0; i < n; i++)
aa[i] = new ArrayList<Integer>();
while (m-- > 0) {
st = new StringTokenizer(br.readLine());
int i = Integer.parseInt(st.nextToken()) - 1;
int j = Integer.parseInt(st.nextToken()) - 1;
aa[i].add(j);
}
visited = new boolean[n];
instack = new boolean[n];
stack = new int[n];
for (int i = 0; i < n; i++)
if (dfs1(i))
break;
if (cnt == 0) {
System.out.println("YES");
return;
}
for (j_ = h_, i_ = stack[--cnt]; ; j_ = i_, i_ = stack[--cnt]) {
Arrays.fill(visited, false);
Arrays.fill(instack, false);
boolean cycle = false;
for (int i = 0; i < n; i++)
if (dfs2(i)) {
cycle = true;
break;
}
if (!cycle) {
System.out.println("YES");
return;
}
if (i_ == h_)
break;
}
System.out.println("NO");
}
}
|
quadratic
|
915_D. Almost Acyclic Graph
|
CODEFORCES
|
import java.awt.Point;
import java.util.LinkedList;
import java.util.Queue;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
Scanner scan = new Scanner("input.txt");
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
int n,m;
n = scan.nextInt();
m = scan.nextInt();
boolean visited[][] = new boolean[n][m];
int numOfStartingPoints;
numOfStartingPoints = scan.nextInt();
int resX = 0, resY = 0;
Queue<Point> que = new LinkedList<Point>();
for (int i = 0; i < numOfStartingPoints; i++) {
int x = scan.nextInt() - 1;
int y = scan.nextInt() - 1;
que.add(new Point(x, y));
visited[x][y] = true;
}
while (true) {
Point current = que.poll();
if (current == null) {
break;
} else {
resX = current.x;
resY = current.y;
if (current.x + 1 < n && !visited[current.x + 1][current.y])
{
que.add(new Point(current.x + 1, current.y));
visited[current.x + 1][current.y] = true;
}
if (current.y + 1 < m && !visited[current.x][current.y + 1])
{
que.add(new Point(current.x, current.y + 1));
visited[current.x][current.y + 1] = true;
}
if (current.x - 1 >= 0 && !visited[current.x - 1][current.y])
{
que.add(new Point(current.x - 1, current.y));
visited[current.x - 1][current.y] = true;
}
if (current.y - 1 >= 0 && !visited[current.x][current.y - 1])
{
que.add(new Point(current.x, current.y - 1));
visited[current.x][current.y - 1] = true;
}
}
}
out.printf("%d %d\n", ++resX, ++resY);
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(String s) throws FileNotFoundException{ br = new BufferedReader(new FileReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
/*
Author : Imran Khan
Language: Java
*/
import java.io.*;
import java.util.*;
public class Main
{
public class BasicInputOutput
{
private StringTokenizer strtoken;
private BufferedReader bufferReader;
private BufferedWriter bufferWriter;
private String delim = " \t\n\r\f";
BasicInputOutput()
{
delim = " \t\n\r\f";
initialize();
}
BasicInputOutput( String s )
{
delim = s;
initialize();
}
private void initialize()
{
bufferReader = new BufferedReader( new InputStreamReader( System.in ));
bufferWriter = new BufferedWriter( new PrintWriter( System.out ));
strtoken = null;
}
private void checkStringTokenizer()throws IOException
{
if ( strtoken == null || strtoken.hasMoreTokens() == false )
strtoken = new StringTokenizer( bufferReader.readLine(), delim );
}
public int getNextInt()throws IOException
{
checkStringTokenizer();
return Integer.parseInt( strtoken.nextToken());
}
public long getNextLong()throws IOException
{
checkStringTokenizer();
return Long.parseLong( strtoken.nextToken());
}
public double getNextDouble()throws IOException
{
checkStringTokenizer();
return Double.parseDouble( strtoken.nextToken());
}
public float getNextFloat()throws IOException
{
checkStringTokenizer();
return Float.parseFloat( strtoken.nextToken());
}
public String getNextString()throws IOException
{
checkStringTokenizer();
return strtoken.nextToken();
}
public String getNextLine()throws IOException
{
checkStringTokenizer();
return bufferReader.readLine();
}
public void skipCurrentLine()throws IOException
{
checkStringTokenizer();
strtoken = null;
}
public void write( String var )throws IOException
{
bufferWriter.write( var );
}
public < T > void write( char sep, T... var )throws IOException
{
if ( var.length == 0 )
return ;
bufferWriter.write( var[0].toString());
for ( int i = 1; i < var.length; i++ )
bufferWriter.write( sep + var[i].toString());
}
public void flush()throws IOException
{
bufferWriter.flush();
}
}
public static void main(String[] args)
{
try
{
new Main().run();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
private BasicInputOutput iohandler;
private int n;
private double[][] mat;
private double[][] sum;
private double[] dp;
private int tolive;
private void run()throws Exception
{
initialize();
solve();
}
private void initialize() throws Exception
{
iohandler=new BasicInputOutput();
n=iohandler.getNextInt();
mat=new double[n][n];
sum=new double[(1<<n)+10][n];
dp=new double[1<<n];
for(int i=0;i<n;i++) for(int j=0;j<n;j++)
{
mat[i][j]=iohandler.getNextDouble();
}
}
private int bitCount(int mask)
{
int ret=0;
while(mask>0) {
ret++;
mask&=(mask-1);
}
return ret;
}
private void solve() throws Exception
{
double[] ans=new double[n];
int ub=1<<n;
for(int i=1;i<ub;i++) {
for(int j=0;j<n;j++) {
sum[i][j]=0;
for(int k=0;k<n;k++) if ((i&(1<<k))!=0) sum[i][j]+=mat[k][j];
int cntbit=bitCount(i);
if (cntbit>1)
sum[i][j]/=((double)cntbit*(cntbit-1.))/2.;
}
}
for(int i=0;i<n;i++)
{
for(int mask=1;mask<ub;mask++) {
dp[mask]=0;
if ((mask&(1<<i))==0) continue;
if (bitCount(mask)==1)
{
dp[mask]=1.;
} else
for(int k=0;k<n;k++) {
if ((mask&(1<<k))==0) continue;
if (i==k) continue;
dp[mask]+=sum[mask][k]*dp[mask-(1<<k)];
}
}
ans[i]=dp[ub-1];
}
iohandler.write(ans[0]+"");
for(int i=1;i<n;i++) iohandler.write(" "+ans[i]);
iohandler.write("\n");
iohandler.flush();
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import static java.util.Arrays.deepToString;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class Main {
static void solve() throws IOException {
int n = nextInt();
if (n >= 0) {
System.out.println(n);
} else {
String string = String.valueOf(n);
int v1 = Integer.valueOf(string.substring(0, string.length() - 1));
int v2 = Integer.valueOf(string.substring(0, string.length() - 2)
+ string.charAt(string.length() - 1));
if (v1 >= v2) {
System.out.println(v1);
} else {
System.out.println(v2);
}
}
}
public static void main(String[] args) throws Exception {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out);
setTime();
solve();
printTime();
printMemory();
writer.close();
}
static BufferedReader reader;
static PrintWriter writer;
static StringTokenizer tok = new StringTokenizer("");
static long systemTime;
static void debug(Object... o) {
System.err.println(deepToString(o));
}
static void setTime() {
systemTime = System.currentTimeMillis();
}
static void printTime() {
System.err.println("Time consumed: "
+ (System.currentTimeMillis() - systemTime));
}
static void printMemory() {
System.err.println("Memory consumed: "
+ (Runtime.getRuntime().totalMemory() - Runtime.getRuntime()
.freeMemory()) / 1000 + "kb");
}
static String next() {
while (!tok.hasMoreTokens()) {
String w = null;
try {
w = reader.readLine();
} catch (Exception e) {
e.printStackTrace();
}
if (w == null)
return null;
tok = new StringTokenizer(w);
}
return tok.nextToken();
}
static int nextInt() {
return Integer.parseInt(next());
}
static long nextLong() {
return Long.parseLong(next());
}
static double nextDouble() {
return Double.parseDouble(next());
}
static BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main{
BufferedReader in;
StringTokenizer str = null;
PrintWriter out;
private String next() throws Exception{
if (str == null || !str.hasMoreTokens())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
private int nextInt() throws Exception{
return Integer.parseInt(next());
}
private long nextLong() throws Exception{
return Long.parseLong(next());
}
private double nextDouble() throws Exception{
return Double.parseDouble(next());
}
public void run() throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));//new FileReader();
out = new PrintWriter(System.out);//new File();
int n = nextInt();
HashSet<Integer> hs = new HashSet<Integer>();
for(int i=0;i<n;i++) hs.add(nextInt());
if (hs.size() == 1){
out.println("NO");
out.close();
return;
}
int a[] = new int[hs.size()];
int yk = 0;
for(int i:hs) a[yk++] = i;
Arrays.sort(a);
out.println(a[1]);
out.close();
}
public static void main(String args[]) throws Exception{
new Main().run();
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
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 Wolfgang Beyer
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long MOD = 1000000007;
long[] current = new long[n + 3];
//long[] sum = new long[n + 3];
current[0] = 1;
for (int i = 0; i < n - 1; i++) {
String s = in.next();
if (s.equals("f")) {
for (int j = i + 1; j > 0; j--) {
current[j] = current[j - 1];
current[j] %= MOD;
}
current[0] = 0;
} else {
for (int j = i + 1; j >= 0; j--) {
//sum[j] = sum[j + 1] + current[j];
current[j] = current[j + 1] + current[j];
current[j] %= MOD;
}
//for (int j = 0; j <= i + 1; j++) {
// current[j] =
//}
}
}
long result = 0;
for (int i = 0; i <= n; i++) {
result += current[i];
result %= MOD;
}
out.println(result);
}
}
static class InputReader {
private static BufferedReader in;
private static StringTokenizer tok;
public InputReader(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
try {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
//tok = new StringTokenizer(in.readLine(), ", \t\n\r\f"); //adds commas as delimeter
}
} catch (IOException ex) {
System.err.println("An IOException was caught :" + ex.getMessage());
}
return tok.nextToken();
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.util.BitSet;
import java.util.Scanner;
public class A {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws Exception {
BitSet primes = primes(1001);
int N = sc.nextInt();
int K = sc.nextInt();
int count = 0;
for (int i = 2; i <= N; ++i) {
if (!primes.get(i)) continue;
int res = i - 1;
boolean found = false;
for (int j = 2; j <= i / 2; ++j) {
if (primes.get(j) && primes.nextSetBit(j + 1) == res - j) {
found = true;
break;
}
}
if (found) {
++count;
}
}
System.out.println(count >= K ? "YES" : "NO");
}
public static BitSet primes(int max) {
BitSet primeSet = new BitSet(max + 1);
if (max < 2) {
return primeSet;
}
int limit = (int) Math.sqrt(max + 1);
primeSet.set(2);
for (int i = 3; i < max + 1; i += 2) {
primeSet.set(i);
}
for (int i = 3; i <= limit; i += 2) {
if (!primeSet.get(i)) {
continue;
}
for (int j = i * i; j < max; j += i) {
primeSet.clear(j);
}
}
return primeSet;
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.lang.*;
public class P11D{
static long mod=1000000007;
public static void main(String[] args) throws Exception{
InputReader in = new InputReader(System.in);
PrintWriter pw=new PrintWriter(System.out);
//int t=in.readInt();
//while(t-->0)
//{
int n=in.readInt();
int m=in.readInt();
boolean v[][]=new boolean[n][n];
for(int i=0;i<m;i++)
{
int x=in.readInt()-1;
int y=in.readInt()-1;
v[x][y]=true;
v[y][x]=true;
}
long dp[][]=new long[1<<n][n];
for(int i=0;i<n;i++)
{
dp[1<<i][i]=1;
}
long ans=0;
for(int mask=1;mask<(1<<n);mask++)
{
int s=-1;
for(int i=0;i<n;i++)
{
if((mask&(1<<i))!=0)
{
s=i;
break;
}
}
for(int i=0;i<n;i++)
{
if(i!=s&&((1<<i)&mask)!=0)
{
for(int j=0;j<n;j++)
{
if((1<<j)!=0&&i!=j&&v[i][j])
{
int rem=(1<<i)^mask;
dp[mask][i]+=dp[rem][j];
}
}
int c=Integer.bitCount(mask);
if(c>=3&&v[i][s])
{
ans+=dp[mask][i];
}
}
}
}
ans/=2;
pw.println(ans);
//}
pw.close();
}
public static long gcd(long x,long y)
{
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y)
{
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int abs(int a,int b)
{
return (int)Math.abs(a-b);
}
public static long abs(long a,long b)
{
return (long)Math.abs(a-b);
}
public static int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b)
{
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b)
{
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b)
{
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static class Pair implements Comparable<Pair>
{
int a,b;
Pair (int a,int b)
{
this.a=a;
this.b=b;
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if(this.a!=o.a)
return Integer.compare(this.a,o.a);
else
return Integer.compare(this.b, o.b);
//return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.a == a && p.b == b;
}
return false;
}
public int hashCode() {
return new Integer(a).hashCode() * 31 + new Integer(b).hashCode();
}
}
static long sort(int a[])
{ int n=a.length;
int b[]=new int[n];
return mergeSort(a,b,0,n-1);}
static long mergeSort(int a[],int b[],long left,long right)
{ long c=0;if(left<right)
{ long mid=left+(right-left)/2;
c= mergeSort(a,b,left,mid);
c+=mergeSort(a,b,mid+1,right);
c+=merge(a,b,left,mid+1,right); }
return c; }
static long merge(int a[],int b[],long left,long mid,long right)
{long c=0;int i=(int)left;int j=(int)mid; int k=(int)left;
while(i<=(int)mid-1&&j<=(int)right)
{ if(a[i]<=a[j]) {b[k++]=a[i++]; }
else { b[k++]=a[j++];c+=mid-i;}}
while (i <= (int)mid - 1) b[k++] = a[i++];
while (j <= (int)right) b[k++] = a[j++];
for (i=(int)left; i <= (int)right; i++)
a[i] = b[i]; return c; }
public static int[] radixSort(int[] f)
{
int[] to = new int[f.length];
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String readLine() {
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 double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//StringBuilder sb=new StringBuilder("");
//InputReader in = new InputReader(System.in);
//PrintWriter pw=new PrintWriter(System.out);
//String line=br.readLine().trim();
//int t=Integer.parseInt(br.readLine());
// while(t-->0)
//{
//int n=Integer.parseInt(br.readLine());
//long n=Long.parseLong(br.readLine());
//String l[]=br.readLine().split(" ");
//int m=Integer.parseInt(l[0]);
//int k=Integer.parseInt(l[1]);
//String l[]=br.readLine().split(" ");
//l=br.readLine().split(" ");
/*int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(l[i]);
}*/
//System.out.println(" ");
//}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
//package contests.CF495;
import java.io.*;
import java.util.HashSet;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int d = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
set.add(arr[i]+d);
set.add(arr[i]-d);
}
int cnt = 0;
for (int loc: set) {
int minDist = (int)2e9;
for (int i = 0; i < n; i++) {
minDist = Math.min(minDist, Math.abs(arr[i]-loc));
}
if(minDist == d)
cnt++;
}
pw.println(cnt);
pw.flush();
pw.close();
}
static int[][] packD(int n, int[] from, int[] to) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int f : from) if(f != -1) p[f]++;
for (int i = 0; i < n; i++) g[i] = new int[p[i]];
for (int i = 0; i < from.length; i++) if(from[i] != -1) {g[from[i]][--p[from[i]]] = to[i];}
return g;
}
static void shuffle(int[] a)
{
int n = a.length;
for(int i = 0; i < n; i++)
{
int r = i + (int)(Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
static class Scanner
{
StringTokenizer st; BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s)));}
public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready();}
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class f{
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt();
int m = sc.nextInt();
int[][] arr = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
arr[i][j] = sc.nextInt();
}
}
if(n==1) {
int min = Integer.MAX_VALUE;
for(int i=0; i<m-1; i++) {
min = Math.min(min, Math.abs(arr[0][i]-arr[0][i+1]));
}
out.println(min);
out.close();
}
int[][] adj = new int[n][n];
int[][] edgeadj = new int[n][n];
for(int i=0; i<n; i++) {
for(int j=i+1; j<n; j++) {
int min = Integer.MAX_VALUE;
for(int k=0; k<m; k++) {
min = Math.min(min, Math.abs(arr[i][k]-arr[j][k]));
}
adj[i][j]=min;
adj[j][i]=min;
int min1 = Integer.MAX_VALUE;
int min2 = Integer.MAX_VALUE;
for(int k=0; k<m-1; k++) {
min1 = Math.min(min1, Math.abs(arr[i][k]-arr[j][k+1]));
min2 = Math.min(min2, Math.abs(arr[i][k+1]-arr[j][k]));
}
edgeadj[i][j]=min1;
edgeadj[j][i]=min2;
}
}
int power = (int)Math.pow(2,n);
int[][][] dp = new int[power][n][n];
for(int i=0; i<n; i++) {
dp[(int)Math.pow(2,i)][i][i] = Integer.MAX_VALUE;
}
for(int bit=0; bit<power; bit++) {
for(int j=0; j<n; j++) {
for(int k=0; k<n; k++) {
if((bit & (1<<j))>0 && (bit & (1<<k))>0 && j!=k) {
int temp = bit;
temp &= ~(1<<k);
int ans = 0;
for(int l=0; l<n; l++) {
if((temp & (1<<l))>0) {
int min = Math.min(dp[temp][j][l], adj[l][k]);
ans = Math.max(ans, min);
}
}
if(j!=k) {
dp[bit][j][k] = ans;
}
// out.println(bit + " " + j + " " + k + " " + dp[bit][j][k]);
}
}
}
}
int answer = 0;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if(i!=j) {
int ans = Math.min(dp[power-1][i][j], edgeadj[i][j]);
answer = Math.max(answer, ans);
}
}
}
// for(int i=0; i<n; i++) {
// for(int j=0; j<n; j++) {
// out.println(dp[power-1][i][j]+" "+edgeadj[i][j]);
// }
// }
out.println(answer);
// Start writing your solution here. -------------------------------------
/*
int n = sc.nextInt(); // read input as integer
long k = sc.nextLong(); // read input as long
double d = sc.nextDouble(); // read input as double
String str = sc.next(); // read input as String
String s = sc.nextLine(); // read whole line as String
int result = 3*n;
out.println(result); // print via PrintWriter
*/
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
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;
}
}
//--------------------------------------------------------
}
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int best = 1;
int bestTime = Integer.MAX_VALUE;
for(int i=0;i<n;i++) {
int time;
int a = sc.nextInt();
time = (a%n==0 || a%n<=i) ? a/n : (a+n)/n;
if(time < bestTime) {
best = i + 1;
bestTime = time;
}
}
pw.println(best);
pw.close();
}
}
|
linear
|
996_B. World Cup
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A {
static StringTokenizer st;
static BufferedReader in;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int n1 = n/10;
int s = n % 10;
int n2 = n / 100 * 10+s;
System.out.println(Math.max(n, Math.max(n1, n2)));
pw.close();
}
private static int nextInt() throws IOException{
return Integer.parseInt(next());
}
private static long nextLong() throws IOException{
return Long.parseLong(next());
}
private static double nextDouble() throws IOException{
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class E {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer>[][] nexts = new ArrayList[13][];
ArrayList<Integer>[] bs = new ArrayList[13];
int[][] index = new int[13][];
int[][] eqcl = new int[13][];
for(int n = 1; n <= 12; n++) {
eqcl[n] = new int[(1 << n)];
bs[n] = new ArrayList<Integer>();
index[n] = new int[(1 << n)];
int ind = 0;
for(int mask = 0; mask < (1 << n); mask++) {
boolean add = true;
for(int k = 0; k < n; k++) {
if(rot(mask, k, n) < mask) add = false;
}
if(add) {
bs[n].add(mask);
index[n][mask] = ind; ind++;
}
}
nexts[n] = new ArrayList[bs[n].size()];
for(int i = 0; i < bs[n].size(); i++) {
int mask = bs[n].get(i);
for(int k = 0; k < n; k++) {
eqcl[n][rot(mask, k, n)] = mask;
}
nexts[n][i] = new ArrayList<>();
for(int y = 0; y < (1 << n); y++) {
if((mask & y) == 0) {
nexts[n][i].add(y);
}
}
}
}
int T = Integer.parseInt(br.readLine());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
for(int test = 0; test < T; test++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[][] arrt = new int[m][n];
for(int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for(int j = 0; j < m; j++) {
arrt[j][i] = Integer.parseInt(st.nextToken());
}
}
Column[] cols = new Column[m];
for(int j = 0; j < m; j++) {
cols[j] = new Column(arrt[j]);
}
Arrays.sort(cols, Collections.reverseOrder());
m = Integer.min(n, m);
int[][] arr = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
arr[i][j] = cols[j].arr[i];
}
}
int[][] max = new int[m][bs[n].size()];
for(int c = 0; c < m; c++) {
for(int mask = 0; mask < (1 << n); mask++) {
int curr = 0;
for(int i = 0; i < n; i++) {
if((mask & (1 << i)) > 0) curr += arr[i][c];
}
int cl = eqcl[n][mask];
max[c][index[n][cl]] = Integer.max(max[c][index[n][cl]], curr);
}
}
int[][] dp = new int[m+1][bs[n].size()];
for(int c = 0; c < m; c++) {
for(int i = 0; i < bs[n].size(); i++) {
int mask = bs[n].get(i);
for(int next: nexts[n][i]) {
int cl = eqcl[n][next];
int dl = eqcl[n][mask | next];
if(dp[c][i] + max[c][index[n][cl]] > dp[c+1][index[n][dl]]) {
dp[c+1][index[n][dl]] = dp[c][i] + max[c][index[n][cl]];
}
}
}
}
bw.write(dp[m][bs[n].size() - 1]+"\n");
}
bw.flush();
}
static int rot(int x, int k, int n) {
int a = x << k;
int b = x >> (n - k);
return (a + b) & ((1 << n) - 1);
}
static class Column implements Comparable<Column>{
int[] arr;
int max;
public Column(int[] arr) {
this.arr = arr;
max = 0;
for(int k: arr) {
max = Integer.max(max, k);
}
}
@Override
public int compareTo(Column col) {
return max - col.max;
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out)));
while (in.hasNext()) {
int n = in.nextInt(), a = in.nextInt(), b = in.nextInt(), c = 0;
int[] p = new int[n];
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
p[i] = in.nextInt();
map.put(p[i], i);
}
if (a > b) {
int t = b;
b = a;
a = t;
c = 1;
}
boolean ok = true;
int[] cls = new int[n];
while (ok && map.size() > 0) {
Entry<Integer, Integer> last = map.lastEntry();
int v = last.getKey();
int idx = last.getValue();
if (map.containsKey(a - v)) {
cls[idx] = 0;
cls[map.get(a - v)] = 0;
map.remove(v);
map.remove(a -v);
} else if (map.containsKey(b - v)) {
cls[idx] = 1;
cls[map.get(b - v)] = 1;
map.remove(v);
map.remove(b -v);
} else
ok = false;
}
if (!ok)
System.out.println("NO");
else {
System.out.println("YES");
for (int j = 0; j < cls.length; j++) {
if (j != 0)
System.out.print(" ");
System.out.print(c ^ cls[j]);
}
System.out.println();
}
out.flush();
}
in.close();
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
/*
1
4
1
1
2
3
*/
public class C {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
int T=fs.nextInt();
PrintWriter out=new PrintWriter(System.out);
for (int tt=0; tt<T; tt++) {
int n=fs.nextInt();
int[] a=fs.readArray(n);
int[] stack=new int[n];
int size=0;
for (int i:a) {
if (i==1) {
stack[size++]=i;
}
else {
while (stack[size-1]!=i-1) {
size--;
}
size--;
stack[size++]=i;
}
for (int j=0; j<size; j++) {
out.print(stack[j]);
if (j!=size-1) out.print('.');
}
out.println();
}
// int[] mapTo=new int[n];
// Arrays.fill(mapTo, -1);
// ArrayDeque<Integer>[] occsOf=new ArrayDeque[1001];
// for (int i=0; i<occsOf.length; i++) occsOf[i]=new ArrayDeque<>();
// int lastOne=-1;
//
// for (int i=0; i<n; i++) {
// if (a[i]==1) {
// mapTo[i]=lastOne;
// lastOne=i;
// }
// }
// for (int value=2; value<occsOf.length; value++) {
// for (int i:occsOf[value]) {
// int mapsTo=occsOf[value-1].removeFirst();
// mapTo[i]=mapsTo;
// }
// }
// System.out.println(Arrays.toString(mapTo));
// for (int i=0; i<n; i++) {
// ArrayList<Integer> listBackwards=new ArrayList<>();
// listBackwards.add(a[i]);
// int at=i;
// while (true) {
//// System.out.println("x");
// if (mapTo[at]==-1) {
// break;
// }
// if (a[mapTo[at]]!=a[at]-1) {
// listBackwards.add(a[mapTo[at]]);
// }
// at=mapTo[at];
// }
// for (int j=listBackwards.size()-1; j>=0; j--) {
// out.print(listBackwards.get(j));
// if (j!=0) out.print('.');
// }
// out.println();
// }
}
out.close();
}
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
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.solve());
}
private int solve() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[m];
for (int i = 0; i < m; ++i) a[i] = in.nextInt();
if (n > m) return 0;
Map<Integer, Integer> map = new HashMap<>();
for (int k: a) map.put(k, map.getOrDefault(k, 0) + 1);
List<Integer> keySet = new ArrayList<>(map.keySet());
int end = m / n;
keySet.sort((u, v) -> -Integer.compare(u, v));
do {
int count = 0;
for (int k: keySet) {
count += map.get(k) / end;
if (count >= n) return end;
}
} while (--end > 0);
return 0;
}
}
|
nlogn
|
1011_B. Planning The Expedition
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.Scanner;
public class Beta97B {
static Scanner in;
static StreamTokenizer st;
static int n;
static int[] a;
static int max = 1;
public static void main(String[] args) throws IOException {
// in = new Scanner(System.in);
st = new StreamTokenizer(new InputStreamReader(System.in));
n = nextInt();
a = new int[n];
int ind = 0;
for (int i = 0; i < n; ++i) {
a[i] = nextInt();
if (a[i] > max) {
max = a[i];
ind = i;
}
}
if (max == 1) {
a[0] = 2;
} else {
a[ind] = 1;
}
Arrays.sort(a);
for (int i = 0; i < n; ++i)
System.out.print(a[i] + " ");
}
private static int nextInt() throws IOException {
st.nextToken();
return (int) st.nval;
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.io.*;
public class ExplorerSpace {
private 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;
}
}
public static int[][][] dp;
public static boolean valid(int i, int j, int n, int m)
{
return i>=0 && i<n &&j>=0 && j<m;
}
public static void solution(int n, int m, int k, int[][] h, int[][] v)
{
if(k%2==1)
{
for(int i = 0; i<n; i++)
{
for(int j = 0; j<m; j++)
out.print(-1+" ");
out.println();
}
return;
}
dp = new int[n][m][k/2+1];
for(int t = 1; t<=k/2; t++)
{
for(int i = 0; i<n; i++)
{
for(int j = 0; j<m; j++)
{
dp[i][j][t] = Integer.MAX_VALUE;
}
}
}
for(int i = 0; i<n; i++)
{
for(int j = 0; j<m; j++)
{
dp[i][j][0] = 0;
}
}
for(int t = 1; t<=k/2; t++)
{
for(int i = 0; i<n; i++)
{
for(int j = 0; j<m; j++)
{
if(valid(i,j+1,n,m))
dp[i][j][t] = Math.min(dp[i][j][t], h[i][j] + dp[i][j+1][t-1]);
if(valid(i,j-1,n,m))
dp[i][j][t] = Math.min(dp[i][j][t], h[i][j-1] + dp[i][j-1][t-1]);
if(valid(i+1,j,n,m))
dp[i][j][t] = Math.min(dp[i][j][t], v[i][j] + dp[i+1][j][t-1]);
if(valid(i-1,j,n,m))
dp[i][j][t] = Math.min(dp[i][j][t], v[i-1][j] + dp[i-1][j][t-1]);
}
}
}
for(int i = 0; i<n; i++)
{
for(int j = 0; j<m; j++)
out.print((dp[i][j][k/2]*2)+" ");
out.println();
}
}
private static PrintWriter out = new PrintWriter(System.out);
public static void main (String[] args)
{
MyScanner s = new MyScanner();
int n = s.nextInt();
int m = s.nextInt();
int k = s.nextInt();
int[][] h = new int[n][m-1];
for(int i = 0; i<n; i++)
{
for(int j = 0; j<m-1; j++)
{
h[i][j] = s.nextInt();
}
}
int[][] v = new int[n-1][m];
for(int i = 0; i<n-1; i++)
{
for(int j = 0; j<m; j++)
{
v[i][j] = s.nextInt();
}
}
solution(n,m,k,h,v);
out.flush();
out.close();
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.*;
public class E14G {
static int[][] choose;
public static void main(String[] args) throws IOException {
init_io();
int N = nint(), M = nint();
choose = new int[N+1][];
long[] ways = new long[N+1];
ways[0] = 1; ways[1] = 1;
for (int i = 0; i <= N; i++) choose[i] = new int[i+1];
for (int i = 0; i <= N; i++) {
choose[i][0] = choose[i][i] = 1;
for (int j = 1; j < i; j++) {
choose[i][j] = (choose[i-1][j-1] + choose[i-1][j]) % M;
}
}
for (int i = 2; i <= N; i++) {
for (int j = 0; j < i; j++) {
ways[i] = (ways[i] + choose[i-1][j]) % M;
}
}
long[][] dp = new long[(N+1)/2+1][N+1];
dp[0][0] = 1;
for (int i = 1; i <= (N+1)/2; i++) {
for (int j = 1; j <= N; j++) {
for (int k = 1; k <= j; k++) {
dp[i][j] = (dp[i][j] + ways[k] * choose[j][k] % M * dp[i-1][j-k] % M) % M;
}
}
}
long ans = 0;
for (int i = 1; i <= (N+1)/2; i++) {
ans = (ans + dp[i][N-(i-1)]) % M;
}
out.println(ans);
out.close();
}
static StreamTokenizer in;
static PrintWriter out;
static BufferedReader br;
static int nint() throws IOException {
in.nextToken();
return (int) in.nval;
}
static void init_io() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
in = new StreamTokenizer(br);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Sockets {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
void solve() throws Exception {
int n = nextInt();
int m = nextInt();
int k = nextInt();
List<Integer> fs = new ArrayList<Integer>();
for (int i = 0; i < n; i++)
fs.add(nextInt());
Collections.sort(fs);
Collections.reverse(fs);
int c = k;
for (int i = 0; i < fs.size(); i++) {
if (c >= m) {
out.println(i);
return;
}
c += (fs.get(i)-1);
}
if (c>=m)
out.println(fs.size());
else
out.println(-1);
}
void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
// in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(System.out);
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
out.close();
}
}
public static void main(String[] args) {
new Sockets().run();
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A {
static double[][] a;
static int N;
static double[] memo;
static double dp(int alive)
{
int count = Integer.bitCount(alive);
if(count == N)
return 1;
if(memo[alive] > -5)
return memo[alive];
double ret = 0;
for(int j = 0; j < N; ++j)
if((alive & (1<<j)) == 0)
ret += die[j][alive | 1<<j] * dp(alive | 1<<j);
return memo[alive] = ret;
}
static double[][] die;
static void f()
{
die = new double[N][1<<N];
for(int i = 0; i < N; ++i)
for(int j = 0; j < 1<<N; ++j)
{
int count = Integer.bitCount(j);
if(count <= 1)
continue;
double prop = 1.0 / (count * (count - 1) >> 1);
for(int k = 0; k < N; ++k)
if((j & (1<<k)) != 0)
die[i][j] += prop * a[k][i];
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
N = sc.nextInt();
a = new double[N][N];
for(int i = 0; i < N; ++i)
for(int j = 0; j < N; ++j)
a[i][j] = sc.nextDouble();
memo = new double[1<<N];
f();
Arrays.fill(memo, -10);
for(int i = 0; i < N - 1; ++i)
out.printf("%.8f ", dp(1 << i));
out.printf("%.8f\n", dp(1 << N - 1));
out.flush();
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready();}
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.*;
/**
* https://codeforces.com/contests
*/
public class TaskA {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
int a = sc.nextInt();
boolean flag = false; // true = не нужно добавлять
List<Integer> toRemove = new ArrayList<>();
for (int b : set) {
if (a % b == 0) {
flag = true;
break;
} else if (b % a == 0 && a < b) {
toRemove.add(b);
}
}
for (int r: toRemove) {
set.remove(r);
}
if (!flag) {
set.add(a);
}
}
System.out.println(set.size());
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1[]=br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
int m=Integer.parseInt(s1[1]);
int a[]=new int[n];
String s2[]=br.readLine().split(" ");
long S=0;
for(int i=0;i<n;i++)
{ a[i]=Integer.parseInt(s2[i]); S+=(long)a[i]; }
Arrays.sort(a);
m=a[n-1];
int last=1;
int t=1;
for(int i=1;i<n-1;i++)
{
if(a[i]==last)
t++;
else
{
t++;
last=last+1;
}
}
if(last<m)
{ t+=m-last; }
else
t++;
System.out.println(S-t);
}
}
|
nlogn
|
1061_B. Views Matter
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.stream.IntStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.util.stream.Stream;
import java.nio.charset.Charset;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author mikit
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
LightScanner in = new LightScanner(inputStream);
LightWriter out = new LightWriter(outputStream);
E1RotateColumnsEasyVersion solver = new E1RotateColumnsEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class E1RotateColumnsEasyVersion {
public void solve(int testNumber, LightScanner in, LightWriter out) {
// out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP);
int testCases = in.ints();
for (int testCase = 0; testCase < testCases; testCase++) {
int n = in.ints(), m = in.ints();
int pow = 1;
for (int i = 0; i < n; i++) pow *= n;
int[][] a = in.ints(n, m);
E1RotateColumnsEasyVersion.P[] columns = new E1RotateColumnsEasyVersion.P[m];
for (int i = 0; i < m; i++) {
int max = 0;
for (int j = 0; j < n; j++) max = Math.max(max, a[j][i]);
columns[i] = new E1RotateColumnsEasyVersion.P(i, max);
}
IntroSort.sort(columns, Comparator.comparing(column -> -column.m));
int ans = 0;
for (int i = 0; i < pow; i++) {
int[] res = new int[n];
int t = i;
for (int j = 0; j < Math.min(n, m); j++) {
int shift = t % n;
t /= n;
for (int k = 0; k < n; k++) {
res[(k + shift) % n] = Math.max(res[(k + shift) % n], a[k][columns[j].i]);
}
}
int sum = 0;
for (int j = 0; j < n; j++) {
sum += res[j];
}
ans = Math.max(ans, sum);
}
out.ans(ans).ln();
}
}
private static class P {
int i;
int m;
P(int i, int m) {
this.i = i;
this.m = m;
}
}
}
static class InsertionSort {
private InsertionSort() {
}
static <T> void sort(T[] a, int low, int high, Comparator<? super T> comparator) {
for (int i = low; i < high; i++) {
for (int j = i; j > low && comparator.compare(a[j - 1], a[j]) > 0; j--) {
ArrayUtil.swap(a, j - 1, j);
}
}
}
}
static class HeapSort {
private HeapSort() {
}
private static <T> void heapfy(T[] a, int low, int high, int i, T val, Comparator<? super T> comparator) {
int child = 2 * i - low + 1;
while (child < high) {
if (child + 1 < high && comparator.compare(a[child], a[child + 1]) < 0) {
child++;
}
if (comparator.compare(val, a[child]) >= 0) {
break;
}
a[i] = a[child];
i = child;
child = 2 * i - low + 1;
}
a[i] = val;
}
static <T> void sort(T[] a, int low, int high, Comparator<T> comparator) {
for (int p = (high + low) / 2 - 1; p >= low; p--) {
heapfy(a, low, high, p, a[p], comparator);
}
while (high > low) {
high--;
T pval = a[high];
a[high] = a[low];
heapfy(a, low, high, low, pval, comparator);
}
}
}
static class QuickSort {
private QuickSort() {
}
private static <T> void med(T[] a, int low, int x, int y, int z, Comparator<? super T> comparator) {
if (comparator.compare(a[z], a[x]) < 0) {
ArrayUtil.swap(a, low, x);
} else if (comparator.compare(a[y], a[z]) < 0) {
ArrayUtil.swap(a, low, y);
} else {
ArrayUtil.swap(a, low, z);
}
}
static <T> int step(T[] a, int low, int high, Comparator<? super T> comparator) {
int x = low + 1, y = low + (high - low) / 2, z = high - 1;
if (comparator.compare(a[x], a[y]) < 0) {
med(a, low, x, y, z, comparator);
} else {
med(a, low, y, x, z, comparator);
}
int lb = low + 1, ub = high;
while (true) {
while (comparator.compare(a[lb], a[low]) < 0) {
lb++;
}
ub--;
while (comparator.compare(a[low], a[ub]) < 0) {
ub--;
}
if (lb >= ub) {
return lb;
}
ArrayUtil.swap(a, lb, ub);
lb++;
}
}
}
static final class BitMath {
private BitMath() {
}
public static int count(int v) {
v = (v & 0x55555555) + ((v >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
v = (v & 0x0f0f0f0f) + ((v >> 4) & 0x0f0f0f0f);
v = (v & 0x00ff00ff) + ((v >> 8) & 0x00ff00ff);
v = (v & 0x0000ffff) + ((v >> 16) & 0x0000ffff);
return v;
}
public static int msb(int v) {
if (v == 0) {
throw new IllegalArgumentException("Bit not found");
}
v |= (v >> 1);
v |= (v >> 2);
v |= (v >> 4);
v |= (v >> 8);
v |= (v >> 16);
return count(v) - 1;
}
}
static interface Verified {
}
static class LightWriter implements AutoCloseable {
private final Writer out;
private boolean autoflush = false;
private boolean breaked = true;
public LightWriter(Writer out) {
this.out = out;
}
public LightWriter(OutputStream out) {
this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset())));
}
public LightWriter print(char c) {
try {
out.write(c);
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter print(String s) {
try {
out.write(s, 0, s.length());
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter ans(String s) {
if (!breaked) {
print(' ');
}
return print(s);
}
public LightWriter ans(int i) {
return ans(Integer.toString(i));
}
public LightWriter ln() {
print(System.lineSeparator());
breaked = true;
if (autoflush) {
try {
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
return this;
}
public void close() {
try {
out.close();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
static class IntroSort {
private static int INSERTIONSORT_THRESHOLD = 16;
private IntroSort() {
}
static <T> void sort(T[] a, int low, int high, int maxDepth, Comparator<T> comparator) {
while (high - low > INSERTIONSORT_THRESHOLD) {
if (maxDepth-- == 0) {
HeapSort.sort(a, low, high, comparator);
return;
}
int cut = QuickSort.step(a, low, high, comparator);
sort(a, cut, high, maxDepth, comparator);
high = cut;
}
InsertionSort.sort(a, low, high, comparator);
}
public static <T> void sort(T[] a, Comparator<T> comparator) {
if (a.length <= INSERTIONSORT_THRESHOLD) {
InsertionSort.sort(a, 0, a.length, comparator);
} else {
sort(a, 0, a.length, 2 * BitMath.msb(a.length), comparator);
}
}
}
static final class ArrayUtil {
private ArrayUtil() {
}
public static <T> void swap(T[] a, int x, int y) {
T t = a[x];
a[x] = a[y];
a[y] = t;
}
}
static class LightScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public LightScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public String string() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return tokenizer.nextToken();
}
public int ints() {
return Integer.parseInt(string());
}
public int[] ints(int length) {
return IntStream.range(0, length).map(x -> ints()).toArray();
}
public int[][] ints(int height, int width) {
return IntStream.range(0, height).mapToObj(x -> ints(width)).toArray(int[][]::new);
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
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 pandusonu
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
// out.print("Case #" + testNumber + ": ");
int n = in.readInt();
int[] a = in.readIntArray(n);
int[][] sol = new int[n][n];
for (int i = 0; i < n; i++) {
sol[0][i] = a[i];
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < n - i; j++) {
sol[i][j] = sol[i - 1][j] ^ sol[i - 1][j + 1];
}
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < n - i; j++) {
sol[i][j] = Math.max(sol[i][j], Math.max(sol[i - 1][j], sol[i - 1][j + 1]));
}
}
int q = in.readInt();
for (int i = 0; i < q; i++) {
int l = in.readInt() - 1;
int r = in.readInt() - 1;
out.println(sol[r - l][l]);
}
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
try {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0)
return -1;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return buf[curChar++];
}
public int readInt() {
return (int) readLong();
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
if (c == -1) throw new RuntimeException();
}
boolean negative = false;
if (c == '-') {
negative = true;
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 negative ? (-res) : (res);
}
public int[] readIntArray(int size) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) arr[i] = readInt();
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
quadratic
|
983_B. XOR-pyramid
|
CODEFORCES
|
/**
* Created by Aminul on 12/12/2017.
*/
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class CF903D {
public static void main(String[] args) throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = in.nextInt();
int a[] = new int[n+1];
int b[] = new int[n+1];
TreeSet<Integer> set = new TreeSet<>();
for(int i = 1; i <= n; i++){
a[i] = in.nextInt();
set.add(a[i]);
}
int k = 0;
HashMap<Integer, Integer> map = new HashMap<>();
int last = set.first();
for(int i : set){
if(i - last > 1) k += 2;
else k += 1;
map.put(i, k);
last = i;
}
for(int i = 1; i <= n; i++){
b[i] = map.get(a[i]);
}
BinaryIndexTree bit = new BinaryIndexTree(k);
BinaryIndexTree freq = new BinaryIndexTree(k);
BigInteger res = BigInteger.ZERO;
for(int i = n; i >= 1; i--){
long l = bit.query(1, b[i]-2), r = bit.query(b[i]+2, k);
long lf = freq.query(1, b[i]-2), rf = freq.query(b[i]+2, k);
res = res.add(BigInteger.valueOf(r));
res = res.add(BigInteger.valueOf(l));
res = res.subtract(BigInteger.valueOf(rf*a[i]));
res = res.subtract(BigInteger.valueOf(lf*a[i]));
bit.add(b[i], a[i]);
freq.add(b[i], 1);
}
pw.println(res);
pw.close();
}
static class BinaryIndexTree{
public long bit[];
int n, len;
public BinaryIndexTree(int nn){
n = nn;
bit = new long[n+1];
len = bit.length;
}
public void add(int index, long value){
for(; index < len;index = index + ( index & -index)){
bit[index] += value;
}
}
public long sum(int index){
if(index <= 0) return 0;
long sum = 0;
for(; index > 0;index = index - (index & -index)){
sum += bit[index];
}
return sum;
}
public long query(int i, int j){
if(j < i) return 0;
return sum(j) - sum(i-1);
}
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
static final int ints[] = new int[128];
public FastReader(InputStream is) {
for (int i = '0'; i <= '9'; i++) ints[i] = i - '0';
this.is = is;
}
public int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
public String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + ints[b];
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + ints[b];
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
/* public char nextChar() {
return (char)skip();
}*/
public char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
/*private char buff[] = new char[1005];
public char[] nextCharArray(){
int b = skip(), p = 0;
while(!(isSpaceChar(b))){
buff[p++] = (char)b;
b = readByte();
}
return Arrays.copyOf(buff, p);
}*/
}
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.