src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.io.*;
import java.util.StringTokenizer;
public class DoubleWord implements Runnable {
boolean isLocalMode =false;
private void doJob() throws Exception {
//do here
String s = nextToken();
int max=0;
for(int i = 0;i<s.length();i++){
for(int j=i+1;j<s.length()+1;j++){
String s1 = s.substring(i, j);
if(s.substring(i+1).contains(s1)){
max = Math.max(max,s1.length());
}
}
}
writer.write(""+max);
}
public static void main(String[] args) {
new DoubleWord().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(getReader());
tokenizer = null;
writer = new PrintWriter(System.out);
//do job
doJob();
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();
}
public Reader getReader() throws FileNotFoundException {
if (isLocalMode) {
return new FileReader("input.txt");
} else {
return new InputStreamReader(System.in);
}
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.awt.geom.Point2D;
import java.text.*;
import java.math.*;
import java.util.*;
public class Main implements Runnable {
final String filename = "";
public int nextPerm(int[] a, int k) {
if (a[0] == k)
return -1;
int last = 0;
for (int i = a.length - 1; i >= 0; i--)
if (a[i] != 0) {
last = i;
break;
}
int mem=a[last];
a[last-1]++;
a[last]=0;
a[a.length-1]=mem-1;
return 0;
}
public double poss(int A,int[][] sen,int[] rasp){
int n=sen.length;
double[] possluck=new double[n];
for(int i=0;i<n;i++)
possluck[i]=Math.min(100, sen[i][1]+rasp[i]*10)/100.0;
double poss=0;
for(int i=0;i<(1<<n);i++){
int kol=0;
for(int j=0;j<n;j++)
if((i%(1<<(j+1)))/(1<<(j))==1)
kol++;
double thisposs=1;
for(int j=0;j<n;j++)
if((i%(1<<(j+1)))/(1<<(j))==1)
thisposs*=possluck[j];
else
thisposs*=(1-possluck[j]);
if(kol>n/2)
poss+=thisposs;
else{
double lvl=0;
for(int j=0;j<n;j++)
if((i%(1<<(j+1)))/(1<<(j))==0)
lvl+=sen[j][0];
poss+=thisposs*(A/(A+lvl));
}
}
return poss;
}
public void solve() throws Exception {
int n = iread(), k = iread(), A = iread();
int[][] sen = new int[n][2];
for (int i = 0; i < n; i++) {
sen[i][0] = iread();
sen[i][1] = iread();
}
double maxposs=0;
int[] rasp=new int[n];
rasp[n-1]=k;
maxposs=Math.max(maxposs, poss(A,sen,rasp));
while(nextPerm(rasp,k)==0)
maxposs=Math.max(maxposs, poss(A,sen,rasp));
out.write(maxposs+"\n");
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter(System.out));
// in = new BufferedReader(new FileReader(filename+".in"));
// out = new BufferedWriter(new FileWriter(filename+".out"));
solve();
out.flush();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public int iread() throws Exception {
return Integer.parseInt(readword());
}
public double dread() throws Exception {
return Double.parseDouble(readword());
}
public long lread() throws Exception {
return Long.parseLong(readword());
}
BufferedReader in;
BufferedWriter out;
public String readword() throws IOException {
StringBuilder b = new StringBuilder();
int c;
c = in.read();
while (c >= 0 && c <= ' ')
c = in.read();
if (c < 0)
return "";
while (c > ' ') {
b.append((char) c);
c = in.read();
}
return b.toString();
}
public static void main(String[] args) {
try {
Locale.setDefault(Locale.US);
} catch (Exception e) {
}
// new Thread(new Main()).start();
new Thread(null, new Main(), "1", 1 << 25).start();
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
StreamTokenizer in;
BufferedReader inb;
PrintWriter out;
public static void main(String[] args) throws Exception {
new Main().run();
}
public void run() throws Exception {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(
System.in)));
inb = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
}
public int nextInt() throws Exception {
in.nextToken();
return (int) in.nval;
}
public int parseInt() throws Exception {
return Integer.parseInt(inb.readLine());
}
public String nextLine() throws Exception {
return inb.readLine();
}
public void solve() throws Exception {
int n = nextInt();
if ((n%4==0)||(n%44==0)||(n%47==0)||(n%74==0)
||(n%744==0)||(n%747==0)||(n%774==0)||(n%777==0)
||(n%7==0)||(n%444==0)||(n%447==0)||(n%474==0)||(n%477==0)||(n%77==0))
{
out.print("YES");
}
else
{
out.print("NO");
}
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class C
{
String line;
StringTokenizer inputParser;
BufferedReader is;
FileInputStream fstream;
DataInputStream in;
void openInput(String file)
{
if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
else
{
try{
fstream = new FileInputStream(file);
in = new DataInputStream(fstream);
is = new BufferedReader(new InputStreamReader(in));
}catch(Exception e)
{
System.err.println(e);
}
}
}
void readNextLine()
{
try {
line = is.readLine();
inputParser = new StringTokenizer(line, " ");
//System.err.println("Input: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
int NextInt()
{
String n = inputParser.nextToken();
int val = Integer.parseInt(n);
//System.out.println("I read this number: " + val);
return val;
}
String NextString()
{
String n = inputParser.nextToken();
return n;
}
void closeInput()
{
try {
is.close();
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
public static void main(String [] argv)
{
String filePath=null;
if(argv.length>0)filePath=argv[0];
C c = new C(filePath);
}
public C(String inputFile)
{
inputFile="input.txt";
openInput(inputFile);
PrintWriter writer=null;
try {
writer = new PrintWriter("output.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
readNextLine();
int N=NextInt();
int M=NextInt();
readNextLine();
int K=NextInt();
readNextLine();
int [] [] p = new int[N][M];
int [] [] init = new int [K][2];
for(int i=0; i<K; i++)
{
int x=NextInt()-1;
int y=NextInt()-1;
p[x][y]=0;
init[i][0]=x;
init[i][1]=y;
}
int max=-1;
int maxX=-1, maxY=-1;
for(int i=0; i<N; i++)
for(int j=0; j<M; j++)
{
p[i][j]=10000;
for(int k=0; k<K; k++)
{
int n=Math.abs(init[k][0]-i)+Math.abs(init[k][1]-j);
if(n<p[i][j])p[i][j]=n;
}
if(p[i][j]>max)
{
max=p[i][j];
maxX=i+1;
maxY=j+1;
}
}
writer.println( maxX+" "+maxY);
closeInput();
writer.close();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main implements Runnable {
//public static final String FileName = "test";
StreamTokenizer ST;
PrintWriter out;
BufferedReader br;
Scanner in;
static final int inf = 1000000000+10;
int nextInt() throws IOException{
ST.nextToken();
return (int)ST.nval;
}
long nextLong() throws IOException{
ST.nextToken();
return (long)ST.nval;
}
String next() throws IOException{
ST.nextToken();
return ST.sval;
}
double nextD() throws IOException{
ST.nextToken();
return ST.nval;
}
public static void main(String[] args) throws IOException {
new Thread(new Main()).start();
// new Main().run();
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//br = new BufferedReader(new FileReader(new File(FileName+".in")));
//out = new PrintWriter(new BufferedWriter(new FileWriter(FileName+".out")));
//in = new Scanner(br);
ST = new StreamTokenizer(br);
solve();
out.close();
//in.close();
br.close();
}
catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}
public void solve() throws IOException {
int[] x = new int[32];
int[] y = new int[32];
x[0] = nextInt();
y[0] = nextInt();
int n = nextInt();
for (int i=1; i<=n; i++) {
x[i] = nextInt();
y[i] = nextInt();
}
n++;
int[][] a = new int[n][n];
int[][] b = new int[n-1][n-1];
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
a[i][j] = (x[i]-x[j])*(x[i]-x[j])+ (y[i]-y[j])*(y[i]-y[j]);
for (int i=1; i<n; i++)
for (int j=1; j<n; j++)
if (i!=j) b[i-1][j-1] = a[0][i]+a[i][j]+a[j][0]; else b[i-1][j-1] = 2*a[0][i];
n--;
int sz = 1<<n;
int[] d = new int[sz];
int[] p = new int[sz];
d[1] = 0;
for (int msk=1; msk<sz; msk++) {
int j = 0;
while ((msk&(1<<j))==0) j++;
int t = inf;
for (int i=0; i<n; i++)
if ((msk&(1<<i))>0)
if (t>d[msk^((1<<i)|(1<<j))]+b[i][j]) {
t = d[msk^((1<<i)|(1<<j))]+b[i][j];
p[msk] = i*n+j;
}
d[msk] = t;
}
out.println(d[sz-1]);
out.print("0 ");
int t = sz-1;
while (t>0) {
int hz = p[t];
int i = hz/n;
int j = hz%n;
if (i!=j) out.print((i+1)+" "+(j+1)+" 0 ");else out.print((i+1)+" 0 ");
t ^= (1<<i)|(1<<j);
}
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Solution
{
static class Reader {
BufferedReader br;
StringTokenizer st;
public Reader() {
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[] nextArr(int n)
{
int a[]=new int[n];
for (int i=0;i<n;i++)a[i]=nextInt();
return a;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static class Ele implements Comparable<Ele>
{
public int x,y;
Ele(int x1,int y1)
{
x=x1;y=y1;
}
public int compareTo(Ele ob) {
if(ob.x!=x)return x-ob.x;
return this.y-ob.y;
}
public String toString()
{
return "["+x+","+y+"]";
}
}
void disp(PrintWriter o,boolean b)
{
if (b) o.println("Yes");
else o.println("No");
}
void disp(PrintWriter o,int ...a)
{
o.println(Arrays.toString(a));
}
void disp(PrintWriter o,long ...a)
{
o.println(Arrays.toString(a));
}
void func(PrintWriter o,ArrayList<Integer> a)
{
for (int i=0;i<a.size();i++)
{
if (i!=a.size()-1)
o.print(a.get(i)+".");
else o.println(a.get(i));
}
}
int dp[][];
public static void main(String[] args) throws IOException
{
Reader sc=new Reader();Solution G=new Solution();//MyMath mm=new MyMath();
PrintWriter o = new PrintWriter(System.out);
int t=1;t=sc.nextInt();
int mod=(int)1e9+7;
int x,x0,x1,x2;int y,y0,y1,y2;int s,s0,s1,s2;
int n,m;int a[],b[],in[],in1[];
long k,l;boolean v[],b1,b2;String ss;char c1[];
//long l;long a[];
ArrayList<ArrayList<Integer>> ll=new ArrayList<>();
ArrayList<Integer> a1=new ArrayList<>();
ArrayList<Integer> a2=new ArrayList<>();
PriorityQueue<Integer> pq1=new PriorityQueue<>();
PriorityQueue<Integer> pq2=new PriorityQueue<>(Collections.reverseOrder());
ArrayDeque<Integer> dq=new ArrayDeque<>();
TreeSet<Integer> h0=new TreeSet<>();
TreeSet<Integer> h1=new TreeSet<>();
TreeMap<Integer,Integer> h=new TreeMap<>();
try{
while (t-->0)
{
n=sc.nextInt();a=sc.nextArr(n);b=new int[(int)1e4];
a1.add(a[0]);b[1]=a[0];
for (int i=1;i<n;i++)
{
G.func(o,a1);
x=a1.get(a1.size()-1);
if (a[i]==1)
{
a1.add(a[i]);
b[a1.size()]=a[i];
}
else if (a[i]==x+1)
{
a1.remove(a1.size()-1);
a1.add(a[i]);
b[a1.size()]=a[i];
}
else
{
while (a1.get(a1.size()-1)!=a[i]-1)
a1.remove(a1.size()-1);
a1.remove(a1.size()-1);
a1.add(a[i]);
}
}
G.func(o,a1);
//o.println();
//o.println(n);
//o.println();
//o.println();
//o.println(h);
//o.println(x2);
//o.println();
h0.clear();ll.clear();a1.clear();a2.clear();h1.clear();h.clear();pq1.clear();pq2.clear();
}
}
catch (Throwable e)
{
e.printStackTrace();
}
//o.println("HI");
o.flush();
o.close();
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class C {
InputStream is;
int __t__ = 1;
int __f__ = 0;
int __FILE_DEBUG_FLAG__ = __f__;
String __DEBUG_FILE_NAME__ = "src/C4";
FastScanner in;
PrintWriter out;
int charToIndex(char c) {
if (Character.isLowerCase(c))
return c - 'a';
else if (Character.isUpperCase(c))
return c - 'A' + 26;
return -1;
}
int CH_NUM = 52;
public void solve() {
int n = in.nextInt();
String s = in.next();
boolean[] exist = new boolean[CH_NUM];
int typeNum = 0;
for (int i = 0; i < n; i++) {
int idx = charToIndex(s.charAt(i));
if (!exist[idx]) {
exist[idx] = true;
typeNum++;
}
}
int get = 0;
int tail = 0, head = 0;
int res = Integer.MAX_VALUE;
int[] cnt = new int[CH_NUM];
while (tail < n || head < n) {
if (head == n || typeNum == get) {
int idx = charToIndex(s.charAt(tail++));
if (cnt[idx] == 1) get--;
cnt[idx]--;
} else {
int idx = charToIndex(s.charAt(head++));
if (cnt[idx] == 0) get++;
cnt[idx]++;
}
if (typeNum == get)
res = Math.min(res, head - tail);
}
System.out.println(res);
/*
int[] currentRightMost = new int[CH_NUM];
Arrays.fill(currentRightMost, -1);
int[][] next = new int[n+1][CH_NUM];
for (int i = 0; i < n + 1; i++) {
Arrays.fill(next[i], 1 << 30);
}
for (int i = 0; i < n; i++) {
int idx = charToIndex(s.charAt(i));
for (int j = 0; j < CH_NUM; j++) if (exist[j]) {
if (currentRightMost[j] != -1)
next[currentRightMost[j]][idx] = Math.min(next[currentRightMost[j]][idx], i);
}
currentRightMost[idx] = i;
}
int res = Integer.MAX_VALUE;
for (int leftMost = 0; leftMost < n; leftMost++) {
int maxRightMost = 0;
int idx = charToIndex(s.charAt(leftMost));
for (int j = 0; j < CH_NUM; j++) if (exist[j]) {
if (j != idx)
maxRightMost = Math.max(maxRightMost, next[leftMost][j]);
}
res = Math.min(res, maxRightMost - leftMost + 1);
}
System.out.println(res);
*/
}
public void run() {
if (__FILE_DEBUG_FLAG__ == __t__) {
try {
is = new FileInputStream(__DEBUG_FILE_NAME__);
} catch (FileNotFoundException e) {
// TODO θͺεηζγγγ catch γγγγ―
e.printStackTrace();
}
System.out.println("FILE_INPUT!");
} else {
is = System.in;
}
in = new FastScanner(is);
out = new PrintWriter(System.out);
solve();
}
public static void main(String[] args) {
new C().run();
}
public void mapDebug(int[][] a) {
System.out.println("--------map display---------");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%3d ", a[i][j]);
}
System.out.println();
}
System.out.println("----------------------------");
System.out.println();
}
public void debug(Object... obj) {
System.out.println(Arrays.deepToString(obj));
}
class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
//stream = new FileInputStream(new File("dec.in"));
}
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++];
}
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;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
int[] nextIntArray(int n, int margin) {
int[] array = new int[n + margin];
for (int i = 0; i < n; i++)
array[i + margin] = nextInt();
return array;
}
int[][] nextIntMap(int n, int m) {
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextIntArray(m);
}
return map;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
long[] nextLongArray(int n, int margin) {
long[] array = new long[n + margin];
for (int i = 0; i < n; i++)
array[i + margin] = nextLong();
return array;
}
long[][] nextLongMap(int n, int m) {
long[][] map = new long[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextLongArray(m);
}
return map;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
return nextDoubleArray(n, 0);
}
double[] nextDoubleArray(int n, int margin) {
double[] array = new double[n + margin];
for (int i = 0; i < n; i++)
array[i + margin] = nextDouble();
return array;
}
double[][] nextDoubleMap(int n, int m) {
double[][] map = new double[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextDoubleArray(m);
}
return map;
}
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();
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++)
array[i] = next();
return array;
}
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();
}
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.util.InputMismatchException;
import java.io.*;
import java.util.HashMap;
/**
* Generated by Contest helper plug-in
* Actual solution is at the bottom
*/
public class Main {
public static void main(String[] args) {
InputReader in = new StreamInputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in, out);
}
public static void run(InputReader in, PrintWriter out) {
Solver solver = new SimpleCycles();
solver.solve(1, in, out);
Exit.exit(in, out);
}
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(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++];
}
@Override
public void close() {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
abstract class InputReader {
private boolean finished = false;
public abstract int read();
public int nextInt() {
return Integer.parseInt(nextToken());
}
public String nextToken() {
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;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public abstract void close();
}
interface Solver {
public void solve(int testNumber, InputReader in, PrintWriter out);
}
class Exit {
private Exit() {
}
public static void exit(InputReader in, PrintWriter out) {
in.setFinished(true);
in.close();
out.close();
}
}
class SimpleCycles implements Solver {
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 u = in.nextInt();
int v = in.nextInt();
--u;
--v;
g[u][v] = g[v][u] = true;
}
HashMap<Integer, Integer> pointer = new HashMap<Integer, Integer> () ;
for (int i =0 ; i < n; ++i) {
pointer.put(1 << i, i);
}
long[][] dm = new long[1 << n][n];
for (int i = 0; i < n; ++i) {
dm[1 << i][i] = 1;
}
for (int i = 0; i < (1 << n); ++i) {
for (int j = 0; j < n; ++j) {
if (dm[i][j] == 0) continue;
int k = pointer.get(i - (i & (i - 1)));
for (int u = k + 1; u < n; ++u) {
if (g[j][u] && (i & (1 << u)) == 0) {
dm[i | (1 << u)][u] += dm[i][j];
}
}
}
}
long res = 0;
for (int i = 0; i < (1 << n); ++i) {
for (int j = 0; j < n; ++j)
if (Integer.bitCount(i) >= 3) {
int c = pointer.get(i - (i & (i - 1)));
if (g[c][j]) res += (long) dm[i][j];
}
}
out.print(res / 2);
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main implements Runnable {
public void _main() throws IOException {
int height = nextInt();
int width = nextInt();
int k = nextInt();
int[] r = new int[k];
int[] c = new int[k];
for (int i = 0; i < k; i++) {
r[i] = nextInt() - 1;
c[i] = nextInt() - 1;
}
int res = 0, R = r[0], C = c[0];
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++) {
int cur = Integer.MAX_VALUE;
for (int z = 0; z < k; z++)
cur = Math.min(cur, Math.abs(i - r[z]) + Math.abs(j - c[z]));
if (res < cur) {
res = cur;
R = i;
C = j;
}
}
out.print((R + 1) + " " + (C + 1));
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
private String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
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);
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
_main();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(202);
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
public class Main{
void solve(){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int n1 = n/10;
int n2 = n/100*10 + n%10;
int ans = n;
ans = Math.max(ans, n1);
ans = Math.max(ans, n2);
System.out.println(ans);
}
public static void main(String[] args){
new Main().solve();
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class VtoraiaStat implements Runnable {
boolean isLocalMode = false;
private void doJob() throws Exception {
int n = nextInt();
int[] r = new int[n];
for(int i =0;i<n;i++){
r[i]=nextInt();
}
Arrays.sort(r);
int m = r[0];
for(int i=0;i<n;i++){
if(r[i]!=m){
writer.write(""+r[i]);
return;
}
}
writer.write("NO");
}
public static void main(String[] args) {
new VtoraiaStat().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(getReader());
tokenizer = null;
writer = new PrintWriter(System.out);
//do job
doJob();
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();
}
public Reader getReader() throws FileNotFoundException {
if (isLocalMode) {
return new FileReader("input.txt");
} else {
return new InputStreamReader(System.in);
}
}
}
|
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.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 kessido
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
BTheHat solver = new BTheHat();
solver.solve(1, in, out);
out.close();
}
static class BTheHat {
PrintWriter out;
InputReader in;
int n;
public void solve(int testNumber, InputReader in, PrintWriter out) {
this.out = out;
this.in = in;
n = in.NextInt();
int desiredPair = -1;
int result = query(1);
if (result != 0) {
int l = 2, r = 1 + n / 2;
while (l < r) {
int m = (l + r) / 2;
int mRes = query(m);
if (mRes == 0) {
desiredPair = m;
break;
} else if (mRes == result) {
l = m + 1;
} else {
r = m;
}
}
} else {
desiredPair = 1;
}
out.println("! " + desiredPair);
}
private int query(int i) {
int iV = queryValue(i);
int iN2V = queryValue(i + n / 2);
if (iV < iN2V) {
return -1;
} else if (iV > iN2V) {
return 1;
}
return 0;
}
private int queryValue(int i) {
out.println("? " + i);
out.flush();
return in.NextInt();
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine(), " \t\n\r\f,");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int NextInt() {
return Integer.parseInt(next());
}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.util.Scanner;
public class inversion__count {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n=s.nextInt();
int[] a = new int[n+1];
for(int i=1;i<=n;i++){
a[i]=s.nextInt();
}
int m=s.nextInt();
int count=0;
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
if(a[i]>a[j]){
count++;
}
}
}
if(count%2==0){
count=0;
}else{
count=1;
}
//System.out.println(count);
for(int i=0;i<m;i++){
int l=s.nextInt();
int r=s.nextInt();
if(l==r){
if((count&1)==1){
System.out.println("odd");
}else{
System.out.println("even");
}
continue;
}
int d=r-l+1;
int segcount = 0;
int temp = (d*(d-1))/2;
if((temp&1)==1 && (count&1)==1){
count=0;
System.out.println("even");
}else if((temp&1)==1 && (count&1)==0){
count=1;
System.out.println("odd");
}else{
if((count&1)==1){
System.out.println("odd");
}else{
System.out.println("even");
}
}
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class LookingOrder {
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
String[] line=in.readLine().split("\\s+");
int xs= Integer.parseInt(line[0]);
int ys= Integer.parseInt(line[1]);
int n=Integer.parseInt(in.readLine());
int []x=new int[n];
int []y=new int[n];
for(int i=0;i<n;++i){
line=in.readLine().split("\\s+");
x[i]= Integer.parseInt(line[0]);
y[i]= Integer.parseInt(line[1]);
}
int maxBitmap=1<<n;
long[] dis=new long[maxBitmap];
int[] last=new int[maxBitmap];
dis[0]=0;
int ci=0;
int[][] dismap=new int[n][n];
for(int i=0;i<n;++i){
for(int j=0;j<=i;++j){
int delx,dely;
if(i==j){
delx=x[i]-xs;
dely=y[i]-ys;
}else{
delx=x[i]-x[j];
dely=y[i]-y[j];
}
dismap[i][j]=delx*delx+dely*dely;
}
}
for(int i=1;i<maxBitmap;++i){
if((i&(1<<ci))==0)
++ci;
int i2=i-(1<<ci);
long min=dis[i2]+2*dismap[ci][ci];
last[i]=ci;
for(int j=0;j<ci;++j){
if((i&(1<<j))!=0){
long m=dis[i2-(1<<j)]+dismap[ci][ci]+dismap[j][j]+dismap[ci][j];
if(m<min){
min=m;
last[i]=j;
}
}
}
dis[i]=min;
}
out.write(""+dis[maxBitmap-1]);
out.newLine();
out.write("0");
int bmap=maxBitmap-1;
ci=n-1;
while(bmap!=0){
while((bmap&(1<<ci))==0&&ci>=0)--ci;
int ci2=last[bmap];
if(ci2!=ci){
out.write(" "+(ci+1)+" "+(ci2+1)+ " 0");
bmap-=(1<<ci)+(1<<ci2);
}else{
out.write(" "+(ci+1)+" 0");
bmap-=1<<ci;
}
}
out.close();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
import java.util.function.Function;
public class P1196D2 {
static boolean multipleIndependent = true;
void run() {
int n = in.nextInt();
int k = in.nextInt();
char[] s = in.next().toCharArray();
int[] dp = new int[3];
char[] c = {'R', 'G', 'B'};
int min = Integer.MAX_VALUE;
for (int i = 0; i < k; i++) {
dp[0] += s[i] == c[(i + 0) % 3] ? 0 : 1;
dp[1] += s[i] == c[(i + 1) % 3] ? 0 : 1;
dp[2] += s[i] == c[(i + 2) % 3] ? 0 : 1;
}
min = Math.min(Math.min(Math.min(dp[0], dp[1]), dp[2]), min);
// System.out.println(Arrays.toString(dp));
for (int i = k; i < n; i++) {
dp[0] += (s[i] == c[(i + 0) % 3] ? 0 : 1) - (s[i - k] == c[(i - k + 0) % 3] ? 0 : 1);
dp[1] += (s[i] == c[(i + 1) % 3] ? 0 : 1) - (s[i - k] == c[(i - k + 1) % 3] ? 0 : 1);
dp[2] += (s[i] == c[(i + 2) % 3] ? 0 : 1) - (s[i - k] == c[(i - k + 2) % 3] ? 0 : 1);
min = Math.min(Math.min(Math.min(dp[0], dp[1]), dp[2]), min);
// System.out.println(Arrays.toString(dp));
}
System.out.println(min);
}
/* -----: Template :----- */
static InputReader in = new InputReader(System.in);
public static void main(String[] args) {
P1196D2 p = new P1196D2();
int q = multipleIndependent ? in.nextInt() : 1;
while (q-- > 0) {
p.run();
}
}
int numLength(long n) {
int l = 0;
while (n > 0) {
n /= 10;
l++;
}
return l;
}
<R> long binarySearch(long lowerBound, long upperBound,
R value, Function<Long, R> generatorFunction, Comparator<R> comparator) {
if (lowerBound <= upperBound) {
long mid = (lowerBound + upperBound) / 2;
int compare = comparator.compare(generatorFunction.apply(mid), value);
if (compare == 0) {
return mid;
} else if (compare < 0) {
return binarySearch(mid + 1, upperBound, value, generatorFunction, comparator);
} else {
return binarySearch(lowerBound, mid - 1, value, generatorFunction, comparator);
}
} else {
return -1;
}
}
<T> Integer[] sortSimultaneously(T[] key, Comparator<T> comparator,
Object[]... moreArrays) {
int n = key.length;
for (Object[] array : moreArrays) {
if (array.length != n) {
throw new RuntimeException("Arrays must have equals lengths");
}
}
Integer[] indices = new Integer[n];
for (int i = 0; i < n; i++) {
indices[i] = i;
}
Comparator<Integer> delegatingComparator = (a, b) -> {
return comparator.compare(key[a], key[b]);
};
Arrays.sort(indices, delegatingComparator);
reorder(indices, key);
for (Object[] array : moreArrays) {
reorder(indices, array);
}
return indices;
}
void reorder(Integer[] indices, Object[] arr) {
if (indices.length != arr.length) {
throw new RuntimeException("Arrays must have equals lengths");
}
int n = arr.length;
Object[] copy = new Object[n];
for (int i = 0; i < n; i++) {
copy[i] = arr[indices[i]];
}
System.arraycopy(copy, 0, arr, 0, n);
}
int prodMod(int a, int b, int mod) {
return (int) (((long) a) * b % mod);
}
long prodMod(long a, long b, long mod) {
long res = 0;
a %= mod;
b %= mod;
while (b > 0) {
if ((b & 1) > 0) {
res = (res + a) % mod;
}
a = (a << 1) % mod;
b >>= 1;
}
return res;
}
long sumMod(int[] b, long mod) {
long res = 0;
for (int i = 0; i < b.length; i++) {
res = (res + b[i] % mod) % mod;
}
return res;
}
long sumMod(long[] a, long mod) {
long res = 0;
for (int i = 0; i < a.length; i++) {
res = (res + a[i] % mod) % mod;
}
return res;
}
long sumProdMod(int[] a, long b, long mod) {
long res = sumMod(a, mod);
return prodMod(res, b, mod);
}
long sumProdMod(long[] a, long b, long mod) {
long res = sumMod(a, mod);
return prodMod(res, b, mod);
}
long sumProdMod(int[] a, int[] b, long mod) {
if (a.length != b.length) {
throw new RuntimeException("Arrays must have equals lengths");
}
long res = 0;
for (int i = 0; i < a.length; i++) {
res = (res + prodMod(a[i], b[i], mod)) % mod;
}
return res;
}
long sumProdMod(long[] a, long[] b, long mod) {
if (a.length != b.length) {
throw new RuntimeException("Arrays must have equals lengths");
}
long res = 0;
for (int i = 0; i < a.length; i++) {
res = (res + prodMod(a[i], b[i], mod)) % mod;
}
return res;
}
int[] toPrimitive(Integer[] arr) {
int[] res = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
res[i] = arr[i];
}
return res;
}
int[][] toPrimitive(Integer[][] arr) {
int[][] res = new int[arr.length][];
for (int i = 0; i < arr.length; i++) {
res[i] = toPrimitive(arr[i]);
}
return res;
}
long[] toPrimitive(Long[] arr) {
long[] res = new long[arr.length];
for (int i = 0; i < arr.length; i++) {
res[i] = arr[i];
}
return res;
}
long[][] toPrimitive(Long[][] arr) {
long[][] res = new long[arr.length][];
for (int i = 0; i < arr.length; i++) {
res[i] = toPrimitive(arr[i]);
}
return res;
}
Integer[] toWrapper(int[] arr) {
Integer[] res = new Integer[arr.length];
for (int i = 0; i < arr.length; i++) {
res[i] = arr[i];
}
return res;
}
Integer[][] toWrapper(int[][] arr) {
Integer[][] res = new Integer[arr.length][];
for (int i = 0; i < arr.length; i++) {
res[i] = toWrapper(arr[i]);
}
return res;
}
Long[] toWrapper(long[] arr) {
Long[] res = new Long[arr.length];
for (int i = 0; i < arr.length; i++) {
res[i] = arr[i];
}
return res;
}
Long[][] toWrapper(long[][] arr) {
Long[][] res = new Long[arr.length][];
for (int i = 0; i < arr.length; i++) {
res[i] = toWrapper(arr[i]);
}
return res;
}
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 int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public <T> T[] nextIntArray(int n, Function<Integer, T> function, Class<T> c) {
T[] arr = (T[]) Array.newInstance(c, n);
for (int i = 0; i < n; i++) {
arr[i] = function.apply(nextInt());
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public <T> T[] nextLongArray(int n, Function<Long, T> function, Class<T> c) {
T[] arr = (T[]) Array.newInstance(c, n);
for (int i = 0; i < n; i++) {
arr[i] = function.apply(nextLong());
}
return arr;
}
public int[][] nextIntMap(int n, int m) {
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
map[i] = nextIntArray(m);
}
return map;
}
public long[][] nextLongMap(int n, int m) {
long[][] map = new long[n][m];
for (int i = 0; i < n; i++) {
map[i] = nextLongArray(m);
}
return map;
}
public char[][] nextCharMap(int n) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) {
map[i] = next().toCharArray();
}
return map;
}
public void readColumns(Object[]... columns) {
int n = columns[0].length;
for (Object[] column : columns) {
if (column.length != n) {
throw new RuntimeException("Arrays must have equals lengths");
}
}
for (int i = 0; i < n; i++) {
for (Object[] column : columns) {
column[i] = read(column[i].getClass());
}
}
}
public <T> T read(Class<T> c) {
throw new UnsupportedOperationException("To be implemented");
}
}
}
|
quadratic
|
1196_D2. RGB Substring (hard version)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Template implements Runnable {
private void solve() throws IOException {
int n = nextInt();
int m = nextInt();
boolean[][] g = new boolean[n][n];
for (int i = 0; i < m; ++i) {
int a = nextInt() - 1;
int b = 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 - 1)][n];
for (int start = 0; start < n; ++start) {
for (int mask = 0; mask < (1 << (n - start - 1)); ++mask)
for (int last = start; last < n; ++last) {
ways[mask][last - start] = 0;
}
ways[1 >> 1][0] = 1;
for (int mask = 1; mask < (1 << (n - start)); mask += 2) {
int cnt = 0;
int tmp = mask;
while (tmp > 0) {
++cnt;
tmp = tmp & (tmp - 1);
}
for (int last = start; last < n; ++last)
if (ways[mask >> 1][last - start] > 0) {
long amm = ways[mask >> 1][last - start];
for (int i = start; i < n; ++i)
if ((mask & (1 << (i - start))) == 0 && g[last][i]) {
ways[(mask | (1 << (i - start))) >> 1][i - start] += amm;
}
if (g[last][start])
am[cnt] += ways[mask >> 1][last - start];
}
}
}
long res = 0;
for (int cnt = 3; cnt <= n; ++cnt) {
if (am[cnt] % (2) != 0)
throw new RuntimeException();
res += am[cnt] / (2);
}
writer.println(res);
}
public static void main(String[] args) {
new Template().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
|
11_D. A Simple Task
|
CODEFORCES
|
//package codeforces;
import java.util.Scanner;
public class Fingerprints {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] code = new int[scanner.nextInt()];
int[] prints = new int[scanner.nextInt()];
for (int i = 0; i < code.length; i++) {
code[i] = scanner.nextInt();
}
for (int i = 0; i < prints.length; i++) {
prints[i] = scanner.nextInt();
}
for (int i = 0; i < code.length; i++) {
for (int j = 0; j < prints.length; j++) {
if (code[i] == prints[j]) {
System.out.print(prints[j] + " ");
}
}
}
scanner.close();
}
}
|
quadratic
|
994_A. Fingerprints
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
private static PrintWriter out;
private static FastReader in;
private static class FastReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastReader(InputStream inputStream) {
reader = new BufferedReader(
new InputStreamReader(inputStream), 1 << 16);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] args) throws FileNotFoundException, InterruptedException {
in = new FastReader(System.in);
out = new PrintWriter(System.out);
int n = in.nextInt();
int a = ((n & 1) == 0) ? a = 6 : 9;
int b = n - a;
out.println(a + " " + b);
out.flush();
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author BSRK Aditya (bsrkaditya@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int m = in.readInt();
int k = in.readInt();
int [] filters = new int[n];
for(int i = 0; i < n; ++i) filters[i] = in.readInt();
Arrays.sort(filters);
int nS = 0, tN = k;
while(tN < m && nS < n) {
tN += filters[n-1-nS] - 1;
nS++;
}
if(tN >= m) out.printLine(nS);
else out.printLine(-1);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ToyArmy {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
System.out.println(n / 2 * 3);
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
//package round429;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class C2 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
for(int i = 0;i < n;i++){
int v = a[i];
for(int j = 2;j*j <= v;j++){
while(v % (j*j) == 0){
v /= j*j;
}
}
a[i] = v;
}
Arrays.sort(a);
int[] f = new int[n];
int p = 0;
for(int i= 0;i < n;i++){
if(i > 0 && a[i] != a[i-1]){
p++;
}
f[p]++;
}
f = Arrays.copyOf(f, p+1);
int mod = 1000000007;
int[][] fif = enumFIF(1000, mod);
long[] res = countSameNeighborsSequence(f, fif, mod);
long ans = res[0];
for(int v : f){
ans = ans * fif[0][v] % mod;
}
out.println(ans);
}
public static int[][] enumFIF(int n, int mod) {
int[] f = new int[n + 1];
int[] invf = new int[n + 1];
f[0] = 1;
for (int i = 1; i <= n; i++) {
f[i] = (int) ((long) f[i - 1] * i % mod);
}
long a = f[n];
long b = mod;
long p = 1, q = 0;
while (b > 0) {
long c = a / b;
long d;
d = a;
a = b;
b = d % b;
d = p;
p = q;
q = d - c * q;
}
invf[n] = (int) (p < 0 ? p + mod : p);
for (int i = n - 1; i >= 0; i--) {
invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod);
}
return new int[][] { f, invf };
}
public static long[] countSameNeighborsSequence(int[] a, int[][] fif, int mod)
{
int n = a.length;
int bef = a[0];
int aft = a[0];
long[] dp = new long[bef];
dp[bef-1] = 1;
for(int u = 1;u < n;u++){
int v = a[u];
aft += v;
long[][] ldp = new long[bef][aft];
for(int i = 0;i < dp.length;i++){
ldp[i][0] = dp[i];
}
for(int i = 0;i < v;i++){
long[][] ndp = new long[bef][aft];
for(int j = 0;j < bef;j++){
for(int k = 0;j+k < aft;k++){
if(ldp[j][k] == 0)continue;
// XX -> XCX
if(j > 0){
ndp[j-1][k] += ldp[j][k] * j;
ndp[j-1][k] %= mod;
}
// CC -> CCC
if(k > 0){
ndp[j][k+1] += ldp[j][k] * k;
ndp[j][k+1] %= mod;
}
// XC -> XCC
// #XC = 2*(i-k)
if(2*(i-k) > 0){
ndp[j][k+1] += ldp[j][k] * (2*(i-k));
ndp[j][k+1] %= mod;
}
// XY -> XCY
// #XY = bef+i+1-#XC-#CC-#XX
if(bef+i+1-j-k-2*(i-k) > 0){
ndp[j][k] += ldp[j][k] * (bef+i+1-j-k-2*(i-k));
ndp[j][k] %= mod;
}
}
}
ldp = ndp;
}
dp = new long[aft];
for(int j = 0;j < bef;j++){
for(int k = 0;j+k < aft;k++){
dp[j+k] += ldp[j][k];
if(dp[j+k] >= mod)dp[j+k] -= mod;
}
}
for(int j = 0;j < aft;j++)dp[j] = dp[j] * fif[1][v] % mod;
bef = aft;
}
return dp;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new C2().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
cubic
|
840_C. On the Bench
|
CODEFORCES
|
import java.util.*;
import java.io.*;
/**
* Created by HREN_VAM.
*/
public class A implements Runnable{
BufferedReader in;
PrintWriter out;
StringTokenizer st;
public static final String filename = "";
public void solve() throws IOException{
int n = nextInt();
int[] a = new int[n + 1];
ArrayList<Integer> pr = new ArrayList<Integer>();
for(int i = 2;i < n + 1;i ++){
if(a[i] != 0)continue;
pr.add(i);
for(int j = 2 * i;j < n + 1;j += i){
a[j] = 1;
}
}
int k = nextInt();
for(int i = 2;i < n + 1;i ++){
if(a[i] != 0)continue;
for(int j = 1;j < pr.size();j ++){
if(i == pr.get(j) + pr.get(j - 1) + 1){
k --;
break;
}
}
}
if(k > 0){
out.println("NO");
return;
}
out.println("YES");
}
public void run(){
try{
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
//in = new BufferedReader(new FileReader(filename + ".in"));
out = new PrintWriter(System.out);
//out = new PrintWriter(new FileWriter(filename + ".out"));
st = new StringTokenizer("");
solve();
out.close();
} catch(IOException e){
throw new RuntimeException(e);
}
}
public static void main(String[] args){
new Thread(new A()).start();
}
public String nextToken() throws IOException{
while(!st.hasMoreTokens()){
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws IOException{
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException{
return Double.parseDouble(nextToken());
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class D {
static boolean[][] adj;
static int n;
static int first;
public static void main(String[] args) throws IOException {
InputReader in = new InputReader();
n = in.nextInt();
// n = 19;?
int m = in.nextInt();
adj = new boolean[n][n];
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < n; j++) {
// adj[i][j] = true;
// }
// }
dp = new long[1 << n][n];
for (int i = 0; i < m; i++) {
int f = in.nextInt() - 1;
int t = in.nextInt() - 1;
adj[f][t] = adj[t][f] = true;
}
boolean[] v = new boolean[1 << n];
long res = 0;
for (int f = 0; f < n; f++) {
first = f;
int cnt;
for (int i = 0; i < 1 << n; i+=(1<<first))
if ((i & (1 << first)) == 0)
for (int j = 0; j < n; j++)
dp[i][j] = -1;
for (int i = 0; i < 1 << n; i+= (1<<first)) {
cnt = Integer.bitCount(i);
if ((i & (1 << first)) == 0 && !v[i | (1 << first)] && cnt > 1) {
v[i | (1 << first)] = true;
res += solve(i, first, cnt);
}
}
}
System.out.println(res / 2);
}
static long[][] dp;
public static long solve(int msk, int lst, int cnt) {
if (cnt == 0)
return (adj[lst][first]) ? 1 : 0;
if (dp[msk][lst] != -1)
return dp[msk][lst];
long res = 0;
for (int i = 0; i < n; i++)
if (adj[lst][i] && (msk & (1 << i)) > 0)
res += solve(msk ^ (1 << i), i, cnt - 1);
return dp[msk][lst] = res;
}
static class InputReader {
BufferedReader in;
StringTokenizer st;
public InputReader() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(in.readLine());
}
public String next() throws IOException {
while (!st.hasMoreElements())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
//package codeforces;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class SameSumBlocksHard {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in .nextInt();
long[] a = new long[n + 1];
long[] sum = new long[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
sum[i] = sum[i - 1] + a[i];
}
Map<Long, List<int[]>> map = new HashMap<>();
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
long x = sum[j] - sum[i - 1];
List<int[]> list = map.get(x);
if (list == null) {
list = new ArrayList<>();
map.put(x, list);
}
list.add(new int[] {i, j});
}
}
List<int[]> ans = new ArrayList<>();
for (Map.Entry<Long, List<int[]>> entry : map.entrySet()) {
List<int[]> list = entry.getValue();
List<int[]> tmp = new ArrayList<>();
calc(list, tmp);
if (tmp.size() > ans.size()) {
ans.clear();
ans.addAll(tmp);
}
}
System.out.println(ans.size());
for (int[] pair : ans) {
System.out.println(pair[0] + " " + pair[1]);
}
in.close();
}
static void calc(List<int[]> list, List<int[]> tmp) {
Collections.sort(list, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[1] < o2[1]) {
return -1;
} else if (o1[1] > o2[1]) {
return 1;
} else {
return 0;
}
}
});
int last = -1;
for (int[] p : list) {
if (last == -1) {
last = p[1];
tmp.add(p);
} else if (p[0] > last) {
last = p[1];
tmp.add(p);
}
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class Round111ProbA {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[]a = new int[n];
int s =0;
for(int i =0 ; i < n;i++)
{
a[i] = in.nextInt();
s += a[i];
}
Arrays.sort(a);
int x =0;
int c =0;
for(int i =n-1 ; i >-1;i-- )
{
x +=a[i];
s -= a[i];
c++;
if(x > s)break;
}
System.out.println(c);
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
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);
APaintTheNumbers solver = new APaintTheNumbers();
solver.solve(1, in, out);
out.close();
}
static class APaintTheNumbers {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int[] hash = new int[101];
boolean[] hash1 = new boolean[101];
for (int i = 0; i < n; i++) hash[in.scanInt()]++;
int ans = 0;
for (int i = 1; i <= 100; i++) {
if (hash1[i]) continue;
if (hash[i] == 0) continue;
for (int j = i; j <= 100; j += i) hash1[j] = true;
ans++;
}
out.println(ans);
}
}
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;
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
boolean[][] graph = new boolean[n][n];
for (int i = 0; i < m; i++) {
int u = scan.nextInt() - 1;
int v = scan.nextInt() - 1;
graph[u][v] = true;
graph[v][u] = true;
}
long[][] dp = new long[1 << n][n];
long sum = 0;
for (int i = 0; i < n; i++)
dp[1 << i][i] = 1;
for (int mask = 1; mask < (1 << n); mask++) {
int first = Integer.numberOfTrailingZeros(mask);
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) == 0 || first == i)
continue;
for (int j = 0; j < n; j++) {
if (graph[i][j] && (mask & (1 << j)) != 0)
dp[mask][i] += dp[mask ^ 1 << i][j];
}
if (Integer.bitCount(mask) >= 3 && graph[i][first])
sum += dp[mask][i];
}
}
System.out.println(sum / 2);
scan.close();
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.*;
import java.math.*;
import static java.lang.Character.isDigit;
import static java.lang.Character.isLowerCase;
import static java.lang.Character.isUpperCase;
import static java.lang.Math.*;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Character.isDigit;
public class Main{
static void debug(Object...os){
System.err.println(deepToString(os));
}
int n,A;
int[] bs,ls;
void run(){
n=nextInt();int k=nextInt();A=nextInt();
bs=new int[n];ls=new int[n];
for(int i=0;i<n;i++) {
bs[i]=nextInt();ls[i]=nextInt();
}
dfs(k,0);
System.out.println(res);
}
double res=0;
private void dfs(int k,int i){
if(i==n) {
double val=0;
for(int j=0;j<1<<n;j++) {// 1 approve
double p=1;
int B=0;
for(int l=0;l<n;l++)p*= (j>>l&1)==1 ? ls[l]/100.0 : (100-ls[l])/100.0;
for(int l=0;l<n;l++)if((j>>l&1)==0)B += bs[l];
if(Integer.bitCount(j) > n/2) {
val += p;
}else {
val += p * A / (A+B);
}
}
res=max(res,val);
return;
}
for(int j=0;j<k+1;j++) {
ls[i]+=j*10;
if(ls[i]<=100) {
dfs(k-j,i+1);
}
ls[i]-=j*10;
}
}
int nextInt(){
try{
int c=System.in.read();
if(c==-1) return c;
while(c!='-'&&(c<'0'||'9'<c)){
c=System.in.read();
if(c==-1) return c;
}
if(c=='-') return -nextInt();
int res=0;
do{
res*=10;
res+=c-'0';
c=System.in.read();
}while('0'<=c&&c<='9');
return res;
}catch(Exception e){
return -1;
}
}
long nextLong(){
try{
int c=System.in.read();
if(c==-1) return -1;
while(c!='-'&&(c<'0'||'9'<c)){
c=System.in.read();
if(c==-1) return -1;
}
if(c=='-') return -nextLong();
long res=0;
do{
res*=10;
res+=c-'0';
c=System.in.read();
}while('0'<=c&&c<='9');
return res;
}catch(Exception e){
return -1;
}
}
double nextDouble(){
return Double.parseDouble(next());
}
String next(){
try{
StringBuilder res=new StringBuilder("");
int c=System.in.read();
while(Character.isWhitespace(c))
c=System.in.read();
do{
res.append((char)c);
}while(!Character.isWhitespace(c=System.in.read()));
return res.toString();
}catch(Exception e){
return null;
}
}
String nextLine(){
try{
StringBuilder res=new StringBuilder("");
int c=System.in.read();
while(c=='\r'||c=='\n')
c=System.in.read();
do{
res.append((char)c);
c=System.in.read();
}while(c!='\r'&&c!='\n');
return res.toString();
}catch(Exception e){
return null;
}
}
public static void main(String[] args){
new Main().run();
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class template {
public static void main(String[] args) throws Exception {
new template().run();
}
long MOD = 1_000_000_007;
public void run() throws Exception {
FastScanner f = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = f.nextInt(), m = f.nextInt();
int[] t = new int[n], g = new int[n], c = new int[3];
for(int i = 0; i < n; i++) {
t[i] = f.nextInt();
c[g[i] = f.nextInt()-1]++;
}
long[][] dp1 = new long[c[0]+1][m+1];
long[][][] dp2 = new long[c[1]+1][c[2]+1][m+1];
dp1[0][0] = 1;
dp2[0][0][0] = 1;
for(int i = 0; i < n; i++) {
if(g[i] == 0) {
for(int j = dp1.length-2; j >= 0; j--)
for(int k = m-t[i]; k >= 0; k--)
dp1[j+1][k+t[i]] = (dp1[j+1][k+t[i]] + dp1[j][k]) % MOD;
} else if(g[i] == 1) {
for(int j = dp2.length-2; j >= 0; j--)
for(int k = dp2[j].length-1; k >= 0; k--)
for(int l = m-t[i]; l >= 0; l--)
dp2[j+1][k][l+t[i]] = (dp2[j+1][k][l+t[i]] + dp2[j][k][l]) % MOD;
} else {
for(int j = dp2.length-1; j >= 0; j--)
for(int k = dp2[j].length-2; k >= 0; k--)
for(int l = m-t[i]; l >= 0; l--)
dp2[j][k+1][l+t[i]] = (dp2[j][k+1][l+t[i]] + dp2[j][k][l]) % MOD;
}
}
long[][][][] combo = new long[c[0]+1][c[1]+1][c[2]+1][3];
if(c[0] != 0) combo[1][0][0][0] = 1;
if(c[1] != 0) combo[0][1][0][1] = 1;
if(c[2] != 0) combo[0][0][1][2] = 1;
for(int i = 0; i <= c[0]; i++) {
for(int j = 0; j <= c[1]; j++) {
for(int k = 0; k <= c[2]; k++) {
for(int a = 0; a < 3; a++) {
if(a != 0 && i < c[0]) combo[i+1][j][k][0] = (combo[i+1][j][k][0] + combo[i][j][k][a] * (i+1) % MOD) % MOD;
if(a != 1 && j < c[1]) combo[i][j+1][k][1] = (combo[i][j+1][k][1] + combo[i][j][k][a] * (j+1) % MOD) % MOD;
if(a != 2 && k < c[2]) combo[i][j][k+1][2] = (combo[i][j][k+1][2] + combo[i][j][k][a] * (k+1) % MOD) % MOD;
}
}
}
}
long ans = 0;
for(int s = 0; s <= m; s++) {
for(int x = 0; x <= c[0]; x++)
for(int y = 0; y <= c[1]; y++)
for(int z = 0;z <= c[2]; z++) {
ans = (ans + dp1[x][s] * dp2[y][z][m-s] % MOD * ((combo[x][y][z][0] + combo[x][y][z][1] + combo[x][y][z][2]) % MOD) % MOD) % MOD;
}
}
/*
for(int i = 0; i < dp1.length; i++)
out.println(Arrays.toString(dp1[i]));
out.println("-----");
for(int i = 0; i < dp2.length; i++) {
for(int j = 0; j < dp2[i].length; j++)
out.println(Arrays.toString(dp2[i][j]));
out.println();
}
for(int i = 0; i <= c[0]; i++) for(int j = 0; j <= c[1]; j++) for(int k = 0; k <= c[2]; k++) out.printf("%d %d %d: %d%n", i, j, k, combo[i][j][k][0] + combo[i][j][k][1] + combo[i][j][k][2]); */
out.println(ans);
///
out.flush();
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
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();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
cubic
|
1185_G2. Playlist for Polycarp (hard version)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer=null;
public static void main(String[] args) throws IOException
{
new Main().execute();
}
void debug(Object...os)
{
System.out.println(Arrays.deepToString(os));
}
int ni() throws IOException
{
return Integer.parseInt(ns());
}
long nl() throws IOException
{
return Long.parseLong(ns());
}
double nd() throws IOException
{
return Double.parseDouble(ns());
}
String ns() throws IOException
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(br.readLine());
return tokenizer.nextToken();
}
String nline() throws IOException
{
tokenizer=null;
return br.readLine();
}
//Main Code starts Here
int totalCases, testNum;
int n,a,b;
long arr[];
void execute() throws IOException
{
totalCases = 1;
for(testNum = 1; testNum <= totalCases; testNum++)
{
if(!input())
break;
solve();
}
}
void solve() throws IOException
{
Arrays.sort(arr);
long x1 = arr[b-1];
long x2 = arr[b];
System.out.println(x2-x1);
}
boolean input() throws IOException
{
n = ni();
a = ni();
b = ni();
arr = new long[n];
for(int i = 0;i<n;i++)
{
arr[i] = nl();
}
return true;
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
//package contese_476;
import java.util.*;
public class q1
{
int m=(int)1e9+7;
public class Node
{
int a;
int b;
public void Node(int a,int b)
{
this.a=a;
this.b=b;
}
}
public int mul(int a ,int b)
{
a=a%m;
b=b%m;
return((a*b)%m);
}
public int pow(int a,int b)
{
int x=1;
while(b>0)
{
if(b%2!=0)
x=mul(x,a);
a=mul(a,a);
b=b/2;
}
return x;
}
public static long gcd(long a,long b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
HashMap<Integer,Integer> h=new HashMap();
//HashMap<Integer,Integer> h1=new HashMap();
int[] a=new int[n];
int x=sc.nextInt();
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
if(h.get(a[i])==null)
{
h.put(a[i], 1);
//h1.put(a[i],i);
}
else
{
System.out.print(0);
System.exit(0);
}
}
for(int i=0;i<n;i++)
{
int num=a[i]&x;
if(num==a[i])
continue;
if(h.get(num)==null)
continue;
else
{
System.out.print(1);
System.exit(0);
}
}
for(int i=0;i<n;i++)
{
int num=a[i]&x;
if(num==a[i])
continue;
if(h.get(num)==null)
h.put(num, 1);
else
{
System.out.print(2);
System.exit(0);
}
}
System.out.print(-1);
}
}
|
linear
|
1013_B. And
|
CODEFORCES
|
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author BSRK Aditya
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
long numQuestions = in.nextInt();
long numCorrectlyAnsweredQuestions = in.nextInt();
long sizeForDoublingScore = in.nextInt();
long score = 0;
long numIncorrectlyAnsweredQuestions = numQuestions - numCorrectlyAnsweredQuestions;
long numDoublings = Math.max(numQuestions / sizeForDoublingScore - numIncorrectlyAnsweredQuestions, 0);
score += 2*sizeForDoublingScore*Long.parseLong(new BigInteger("2").modPow(new BigInteger(String.valueOf(numDoublings)), new BigInteger("1000000009")).subtract(BigInteger.ONE).toString());
score += numCorrectlyAnsweredQuestions - sizeForDoublingScore*numDoublings;
score %= 1000000009;
out.println(score);
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
static Scanner console;
public static void main(String[] args) {
console = new Scanner(System.in);
int n = console.nextInt();
List<Integer> arr= new ArrayList<>();
for(int i = 0; i < n; i++) arr.add( console.nextInt());
Collections.sort(arr);
List<Integer> groups = new ArrayList<>();
// System.out.println(arr);
for(int i = 0; i < arr.size() - 1; i++) {
int j = i+1;
groups.add(arr.get(i));
// System.out.println(groups);
while(j < arr.size()) {
// System.out.println(j);
if(arr.get(j) % arr.get(i) == 0) {
arr.remove(j);
}
else {
// groups.add(arr.get(j));
j++;
}
}
}
// System.out.println(arr);
System.out.println(arr.size());
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
public class D {
private static void run() throws IOException {
int n = in.nextInt();
int m = in.nextInt();
int p = in.nextInt();
int[] dx = {1, -1, 0, 0};
int[] dy = {0, 0, 1, -1};
int[][][] map = new int[n][m][4];
ArrayList<Edge> edges = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m - 1; j++) {
int len = in.nextInt();
edges.add(new Edge(new Point[]{new Point(i, j), new Point(i, j + 1)}, len));
map[i][j][2] = map[i][j + 1][3] = len;
}
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m; j++) {
int len = in.nextInt();
edges.add(new Edge(new Point[]{new Point(i, j), new Point(i + 1, j)}, len));
map[i][j][0] = map[i + 1][j][1] = len;
}
}
if (p % 2 != 0) {
int[] ans = new int[m];
for (int i = 0; i < m; i++) {
ans[i] = -1;
}
for (int i = 0; i < n; i++) {
print_array(ans);
}
return;
}
edges.sort(Comparator.comparingInt(o -> o.len));
int[][][] dp = new int[2][n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int min = Integer.MAX_VALUE;
for (int k = 0; k < 4; k++) {
if (map[i][j][k] == 0) continue;
min = Math.min(min, map[i][j][k]);
}
dp[1][i][j] = min * 2;
}
}
for (int k = 2; k <= p / 2; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
dp[k & 1][i][j] = Integer.MAX_VALUE;
for (int d = 0; d < 4; d++) {
int nx = i + dx[d];
int ny = j + dy[d];
if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
dp[k & 1][i][j] = Math.min(dp[(k - 1) & 1][nx][ny] + map[i][j][d] * 2, dp[k&1][i][j]);
}
}
}
}
for (int i = 0; i < n; i++) {
print_array(dp[(p / 2) & 1][i]);
}
}
static class Edge {
Point[] points;
int len;
public Edge(Point[] points, int len) {
this.points = points;
this.len = len;
}
}
static class Point {
final int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
// int t = in.nextInt();
// for (int i = 0; i < t; i++) {
// }
run();
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static void print_array(int[] array) {
for (int now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String args[] ) {
FastReader sc = new FastReader();
int n = sc.nextInt();
int m = sc.nextInt();
int[] arr = new int[105];
for(int i=0;i<m;i++){
int a = sc.nextInt();
arr[a]++;
}
for(int i=1;i<=1000;i++){
int sum=0;
for(int a:arr){
if(a!=0){
sum+=(a/i);
}
}
if(sum<n){
System.out.println(i-1);
return;
}
}
}
}
|
quadratic
|
1011_B. Planning The Expedition
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.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 gaidash
*/
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);
ARaskrashivanieChisel solver = new ARaskrashivanieChisel();
solver.solve(1, in, out);
out.close();
}
static class ARaskrashivanieChisel {
public void solve(int testNumber, InputReader in, OutputWriter out) {
final int MAX = 100;
int n = in.nextInt();
int[] a = in.nextSortedIntArray(n);
int ret = 0;
boolean[] used = new boolean[MAX + 1];
for (int i = 0; i < n; i++) {
if (!used[a[i]]) {
used[a[i]] = true;
ret++;
for (int j = i + 1; j < n; j++) {
if (a[j] % a[i] == 0 && !used[a[j]]) {
used[a[j]] = true;
}
}
}
}
out.println(ret);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int[] nextSortedIntArray(int n) {
int array[] = nextIntArray(n);
Arrays.sort(array);
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
import javax.sound.midi.Synthesizer;
public class Main {
static int V;
static ArrayList<Integer> adjList [];
static int first(int a){
int idx = 0;
while (a > 0 && (a & 1) == 0) {
idx++;
a>>=1;
}
return idx;
}
static long Number_Of_Simple_Cycles () { // Time Complexity O(2 ^ n * n ^ 2)
long dp [][] = new long[1 << V][V];
for (int i = 0 ; i < V ; ++i)
dp[1 << i][i] = 1;
for (int mask = 1 ; mask < 1 << V ; ++mask) {
if (Integer.bitCount(mask) <= 1) continue;
for (int current = 0 ; current < V ; ++current) {
if (((1 << current) & mask) == 0) continue;
for (int last : adjList[current])
if (current != first(mask))
{
dp[mask][current] += dp[mask ^ (1 << current)][last];
}
}
}
long ans = 0 ;
int allVisited = (1 << V) - 1;
for (int mask = 1 ; mask < 1 << V ; ++mask) {
if (Integer.bitCount(mask) < 3) continue;
for (int u = 0 ; u < V ; ++u) {
if (adjList[u].contains(first (mask)))
ans += dp[mask][u];
}
}
return ans >> 1;
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
PrintWriter out = new PrintWriter(System.out);
V = sc.nextInt();
adjList = new ArrayList[V];
for (int i = 0 ; i < V ; ++i) adjList[i] = new ArrayList<>();
int E = sc.nextInt();
while (E -- > 0) {
int v = sc.nextInt() - 1;
int u = sc.nextInt() - 1;
adjList[v].add(u);
adjList[u].add(v);
}
out.print(Number_Of_Simple_Cycles());
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 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 {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.*;
public class global{
public static void main(String s[]){
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
String st = String.valueOf(n);
if(st.length()==1){
System.out.println(n);
}else{
long val = 1;
long prev=9;
long total=9;
long late=9;
for(int i=2;i<=12;i++){
val*=10;
total+=i*(val*9);
if(n<=total){
long diff = n-late;
long div = diff/i;
long mod = diff%i;
if(mod==0){
prev+=div;
System.out.println((prev)%10);
break;
}else{
prev+=div+1;
String fg = String.valueOf(prev);
System.out.println(fg.charAt((int)mod-1));
break;
}
}
prev+=(9*val);
late=total;
}
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Sparsh Sanchorawala
*/
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 = (long) 1e9 + 7;
public void solve(int testNumber, InputReader s, PrintWriter w) {
int n = s.nextInt(), T = s.nextInt();
int[] t = new int[n + 1];
int[] g = new int[n + 1];
int[] f = new int[4];
for (int i = 1; i <= n; i++) {
t[i] = s.nextInt();
g[i] = s.nextInt();
f[g[i]]++;
}
long[] fact = new long[n + 1];
fact[0] = 1;
for (int i = 1; i <= n; i++)
fact[i] = fact[i - 1] * i % mod;
long[][][][] perm = new long[f[1] + 1][f[2] + 1][f[3] + 1][3 + 1];
long[][][] sumPerm = new long[f[1] + 1][f[2] + 1][f[3] + 1];
perm[0][0][0][0] = 1;
for (int a = 0; a <= f[1]; a++) {
for (int b = 0; b <= f[2]; b++) {
for (int c = 0; c <= f[3]; c++) {
if (a - 1 >= 0)
perm[a][b][c][1] = (sumPerm[a - 1][b][c] - perm[a - 1][b][c][1] + mod) % mod;
if (b - 1 >= 0)
perm[a][b][c][2] = (sumPerm[a][b - 1][c] - perm[a][b - 1][c][2] + mod) % mod;
if (c - 1 >= 0)
perm[a][b][c][3] = (sumPerm[a][b][c - 1] - perm[a][b][c - 1][3] + mod) % mod;
for (int i = 0; i <= 3; i++)
sumPerm[a][b][c] = (sumPerm[a][b][c] + perm[a][b][c][i]) % mod;
}
}
}
long[][][][][] dp = new long[n + 1][f[1] + 1][f[2] + 1][f[3] + 1][T + 1];
dp[0][0][0][0][0] = 1;
for (int i = 1; i <= n; i++) {
for (int a = 0; a <= f[1]; a++) {
for (int b = 0; b <= f[2]; b++) {
for (int c = 0; c <= f[3]; c++) {
for (int j = 0; j <= T; j++) {
dp[i][a][b][c][j] = dp[i - 1][a][b][c][j];
if (j - t[i] >= 0) {
if (g[i] == 1 && a > 0) {
dp[i][a][b][c][j] = (dp[i][a][b][c][j] + dp[i - 1][a - 1][b][c][j - t[i]]) % mod;
} else if (g[i] == 2 && b > 0) {
dp[i][a][b][c][j] = (dp[i][a][b][c][j] + dp[i - 1][a][b - 1][c][j - t[i]]) % mod;
} else if (g[i] == 3 && c > 0) {
dp[i][a][b][c][j] = (dp[i][a][b][c][j] + dp[i - 1][a][b][c - 1][j - t[i]]) % mod;
}
}
}
}
}
}
}
long res = 0;
for (int a = 0; a <= f[1]; a++)
for (int b = 0; b <= f[2]; b++)
for (int c = 0; c <= f[3]; c++)
res = (res + dp[n][a][b][c][T] * sumPerm[a][b][c] % mod * fact[a] % mod * fact[b] % mod * fact[c] % mod) % mod;
w.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 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);
}
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
import java.util.stream.IntStream;
public class B {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
Solver solver = new Solver();
solver.solve(in, out);
out.close();
}
static class Solver {
int n;
int n2;
InputReader in;
PrintWriter out;
public void solve(InputReader in, PrintWriter out) {
this.in = in;
this.out = out;
n = in.readInt();
n2 = n/2;
int res = find();
out.print("! ");
out.println(res);
}
public int find() {
if (n%4 != 0) return -1;
int c = compare(0);
if (c == 0) return 1;
int s = 1;
int f = n2-1;
if (c > 0) {
s = n2+1;
f = n-1;
}
while (s <= f) {
int m = (s+f)/2;
int v = compare(m);
if (v == 0) return m+1;
else if (v < 0) s = m+1;
else f = m-1;
}
return -1;
}
public int compare(int z) {
out.print("? ");
out.println(z+1);
out.flush();
int r1 = in.readInt();
out.print("? ");
out.println((z+n2)%n+1);
out.flush();
int r2 = in.readInt();
return r1-r2;
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
}
public String read() {
try {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return tokenizer.nextToken();
}
public int readInt() {
return Integer.parseInt(read());
}
public long readLong() {
return Long.parseLong(read());
}
public void readIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readInt();
}
}
}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class C908 {
public static class mPoint implements Comparable<mPoint> {
public double a, b;
public mPoint(int a, double b) {
this.a = a; this.b = b;
}
public int compareTo(mPoint p) {
return b < p.b ? 1 : (b > p.b) ? -1 : 0;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), r = in.nextInt();
int[] ar = new int[n];
ArrayList<mPoint> disks = new ArrayList<>();
double[] ans = new double[n];
for (int i = 0; i < n; i++) {
ar[i] = in.nextInt();
double max = -1;
for (int j = 0; j < disks.size(); j++) {
if (inRange(ar[i], disks.get(j).a, r)) {
double h = 4*r*r - (ar[i]-disks.get(j).a) * (ar[i]-disks.get(j).a);
max = Math.max(max, Math.sqrt(h) + disks.get(j).b);
}
}
mPoint p = null;
if (max == -1) {
p = new mPoint(ar[i], r);
} else {
p = new mPoint(ar[i], max);
}
disks.add(p);
ans[i] = p.b;
}
for (int i = 0; i < ans.length - 1; i++) {
System.out.print(ans[i] + " ");
}
System.out.println(ans[ans.length - 1]);
}
public static boolean inRange(int a, double b, int r) {
if (Math.abs(b - a) <= 2*r) return true; return false;
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
import static java.lang.Math.cos;
import static java.lang.Math.min;
public class E_fast {
static int g[][];
static int n, m;
static char[] s;
static int dp[], inf = (int) 2e9;
static int cost[][];
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = in.nextInt();
m = in.nextInt();
s = in.next().toCharArray();
g = new int[m][m];
for (int i = 1; i < n; i++) {
int x = s[i - 1] - 'a', y = s[i] - 'a';
if (x != y) {
g[x][y]++;
g[y][x]++;
}
}
cost = new int[m][1 << m];
for (int i = 0; i < m; i++) {
int w = 0;
for (int j = 0; j < m; j++) w += g[i][j];
pre(i, 0, 0, -w);
}
dp = new int[1 << m];
Arrays.fill(dp, -1);
pw.println(solve(0, 0));
pw.close();
}
static void pre(int x, int pos, int mask, int w) {
if (pos >= m) {
cost[x][mask] = w;
return;
}
pre(x, pos + 1, mask, w);
pre(x, pos + 1, set(mask, pos), w + 2 * g[x][pos]);
}
static int solve(int pos, int mask) {
if (pos >= m) return 0;
if (dp[mask] != -1) return dp[mask];
int min = inf;
for (int i = 0; i < m; i++) {
if (!check(mask, i)) {
int res = cost[i][mask] * pos + solve(pos + 1, set(mask, i));
min = min(min, res);
}
}
return dp[mask] = min;
}
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
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
/**
* @author: Mehul Raheja
*/
import java.util.*;
import java.io.*;
public class p4 {
/*
Runtime = O()
*/
static int N, M, K;
static String s;
static StringTokenizer st;
static int[] d;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//int[] x = {1,2,3,4,5,6,7,8,9,10};
int N = Integer.parseInt(br.readLine());
int[] d = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
d[i] = Integer.parseInt(st.nextToken());
}
boolean cur = ((inv(d)) % 2) == 1;
// System.out.println(cur);
int Q = Integer.parseInt(br.readLine());
for (int i = 0; i < Q; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int dif = b - a + 1;
if (dif / 2 % 2 == 1) {
cur = !cur;
}
System.out.println((cur) ? "odd" : "even");
}
// for (int i = 0; i < 30; i++) {
// int[] x = new int[i];
// for (int j = 0; j < i; j++) {
// x[j] = j + 1;
// }
// int[] y = new int[x.length];
// for (int k = 0; k < x.length; k++) {
// y[x.length - 1 - k] = x[k];
// }
//
//// System.out.println(inv(x));
//// System.out.println(inv(y));
// System.out.println(i + " " + ((inv(y) - inv(x))%2 == 1));
// }
}
static class BIT {
int[] tree;
int N;
public BIT(int N) {
this.N = N;
tree = new int[N + 1];
}
public BIT(int N, int[] d) {
this.N = N;
tree = new int[N + 1];
for (int i = 1; i < d.length; i++) {
update(i, d[i]);
}
}
public int query(int K) {
int sum = 0;
for (int i = K; i > 0; i -= (i & -i)) {
sum += tree[i];
}
return sum;
}
public void update(int K, int val) {
for (int i = K; i <= N; i += (i & -i)) {
tree[i] += val;
}
}
}
public static int[] toRel(int[] d) {
pair[] p = new pair[d.length];
for (int i = 0; i < d.length; i++) {
p[i] = new pair(d[i], i + 1);
}
Arrays.sort(p);
int[] fin = new int[d.length];
for (int i = 0; i < d.length; i++) {
fin[i] = p[i].b;
}
return fin;
}
public static int inv(int[] d) {
int ans = 0;
int N = d.length;
int[] x = toRel(d);
BIT b = new BIT(N + 1);
for (int i = N - 1; i >= 0; i--) {
ans += b.query(x[i]);
b.update(x[i], 1);
}
return ans;
}
}
class pair implements Comparable<pair> {
int a, b;
public pair(int _a, int _b) {
this.a = _a;
this.b = _b;
}
@Override
public int compareTo(pair t) {
return (a == t.a) ? b - t.b : a - t.a;
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
String str=in.next();
int cnt=0;
for(int i=0;i<str.length();++i) {
if(str.charAt(i)=='1') {
++cnt;
}
}
int i=0;
for(;i<str.length();++i) {
if(str.charAt(i)=='0') {
System.out.print("0");
}
else if(str.charAt(i)=='2') {
while(cnt-->0) {//
System.out.print("1");
}
System.out.print("2");
}
}
while(cnt-->0) {
System.out.print("1");
}
in.close();
}
}
|
linear
|
1009_B. Minimum Ternary String
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main{
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt(), min[] = new int[n];
boolean used[] = new boolean[n];
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
min[i] = scan.nextInt();
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (min[i] > min[j]) {
if (min[i] % min[j] == 0)
min[i] = min[j];
}
else if (min[j] % min[i] == 0)
min[j] = min[i];
}
}
for (int i = 0; i < n; i++) {
set.add(min[i]);
}
System.out.print(set.size());
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.regex.*;
import static java.lang.Math.*;
public class A {
public A() throws Exception {
int n = in.nextInt();
int[] arr = new int[n];
for (int i=0;i<n;i++)
arr[i] = in.nextInt();
if (n==1&&arr[0]==1) {
System.out.println(2);
return;
}
Arrays.sort(arr);
if (arr[n-1]==1)
arr[n-2] = 2;
buf.append(1);
for (int i=0;i<n-1;i++)
buf.append(' ').append(arr[i]);
buf.append('\n');
System.out.print(buf);
}
Scanner in = new Scanner(System.in);
StringBuilder buf = new StringBuilder();
public static void main(String[] args) throws Exception { // {{{
new A();
} // }}}
public static void debug(Object... arr) { // {{{
System.err.println(Arrays.deepToString(arr));
} // }}}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class b{
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader sc = new FastReader();
//PrintWriter out = new PrintWriter(System.out);
double n = (double)sc.nextLong();
double k = (double)sc.nextLong();
double div = 9+8*n+8*k;
double ss = Math.sqrt(div);
//System.out.println(ss);
ss = (ss-3)/2;
System.out.println( (int)(n-ss) );
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.Scanner;
public class CodeforcesRound176B {
/**
* @param args
*/
public static void main(String[] args)
{
Scanner kde =new Scanner (System.in);
Long n = kde.nextLong(); //Π΄ΠΎΠΌΠ° ΠΈ ΠΊΠΎΠ» ΡΡΡΠ±
Long k = kde.nextLong(); // ΡΠ°Π·Π²Π΅ΡΠ»ΠΈΡΠ΅Π»ΠΈ
if(((k-1)*(k-2)+2*k)<(n*(long)2))
{
System.out.println(-1);
return;
}
Long a,b;
if(n==1)
{
System.out.println(0);
return;
}
if(k>=n)
{
System.out.println(1);
return;
}
else
{
a=(long)2;
b=k-1;
}
boolean flag =false;
while(true)
{
if(a>=b)
{
break;
}
long c =(a+b)/2;
if(2*(k-c+1)+(k-1+k-c+1)*(c-1)<(n*2))
{
a=c+1;
}
else
{
b=c;
}
flag=true;
}
if(flag==true )
{
System .out.println(a);
}
else
{
System .out.println(a);
}
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class ProblemA {
public static void main (String args[]) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
String s1=br.readLine();
String[] s=s1.split(" ");
int a[] = new int[n];
for(int i = 0;i<n;i++)
{
a[i]=Integer.parseInt(s[i]);
}
Arrays.sort(a);
System.out.println(findColour(a,n));
}
public static int findColour(int [] a , int n)
{
Map <Integer,Integer> mp = new HashMap<Integer,Integer>();
int f=0;
for(int i = 0; i<n;i++)
{
f=0;
for (Map.Entry<Integer,Integer> entry : mp.entrySet())
{
if(a[i] % entry.getKey()==0)
{
f=1;
break;
}
}
if(f==0)
{
mp.put(a[i],1);
}
}
return mp.size();
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
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
*/
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);
CNastyaAndAWardrobe solver = new CNastyaAndAWardrobe();
solver.solve(1, in, out);
out.close();
}
static class CNastyaAndAWardrobe {
public void solve(int testNumber, InputReader in, PrintWriter out) {
long x = in.nextLong(), k = in.nextLong();
if (x != 0) {
long m = (int) 1e9 + 7;
x = x % m;
long res = in.fastPowerMod(2, k, m);
long res1 = (2 * res) % m;
long ans = ((res1 * x) % m - (res - 1) % m) % m;
ans = (ans + m) % m;
out.println(ans);
} else {
out.println(0);
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public 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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public long fastPowerMod(long x, long y, long m) {
long res = 1;
x = x % m;
while (y > 0) {
if ((y & 1) == 1) {
res = (x * res) % m;
}
x = (x * x) % m;
y = y >> 1;
}
return res % m;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.*;
public class CF23A implements Runnable{
public static void main(String args[]){
new CF23A().run();
}
@Override
public void run(){
try{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
tok = null;
solve();
in.close();
out.close();
}
catch(IOException e){
e.printStackTrace();
System.exit(0);
}
}
int nextInt()throws IOException{
return Integer.parseInt(nextToken());
}
double nextDouble()throws IOException{
return Double.parseDouble(nextToken());
}
long nextLong() throws IOException{
return Long.parseLong(nextToken());
}
String nextToken()throws IOException{
while(tok == null || !tok.hasMoreTokens()){
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
private void solve()throws IOException{
String s = nextToken();
int l = s.length();
int ans = 0;
for(int i = 0; i < l - 1; i++){
for(int j = i + 1; j < l; j++){
String now = s.substring(i, j);
if(s.substring(i + 1).indexOf(now) >= 0){
ans = Math.max(ans, j - i);
}
}
}
out.println(ans);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
/**
* Created by IntelliJ IDEA.
* User: mac
* Date: 11-12-9
* Time: δΈε10:48
* To change this template use File | Settings | File Templates.
*/
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 {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
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);
}
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextInt();
}
Arrays.sort(a);
if (a[a.length - 1] == 1) {
for (int i = 0; i < a.length - 1; i++) {
writer.print(1 + " ");
}
writer.println(2 + "");
return;
}
for (int i = 0; i < a.length; i++) {
if (i == 0)
writer.print(1 + " ");
else
writer.print(a[i - 1] + " ");
}
writer.println();
}
static public void main(String[] args) {
new A().run();
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception{
BufferedReader jk = new BufferedReader(new InputStreamReader( System.in)) ;
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)) ;
StringTokenizer ana = new StringTokenizer(jk.readLine()) ;
int n = Integer.parseInt(ana.nextToken()) ;
int t[]= new int[101] ;
ArrayList<Integer> v = new ArrayList<>() ;
ana = new StringTokenizer(jk.readLine()) ;
for(int i=0 ; i<n ;i++)
{
int y = Integer.parseInt(ana.nextToken()) ;
t[y]=1 ;
v.add(y) ;
}
Collections.sort(v);
int c= 0;
for(int ele : v)
{
if(t[ele]==1)
{
for(int i=ele ; i<=100 ; i+=ele)
{
t[i]=2 ;
}
c++ ;
}
}
out.println(c);
out.flush();
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
String filename = "";
final int INF = 1_000_000_000;
void solve() {
int n = readInt();
int[] a = new int[n];
for(int i = 0;i<n;i++){
a[i] = readInt();
}
Map<Integer, Integer>[] maps = new Map[n];
Map<Integer, Integer> sums = new HashMap();
for(int i = 0;i<n;i++){
maps[i] = new HashMap<>();
}
for(int i = 0;i<n;i++){
int summ = 0;
for(int j = i;j<n;j++){
summ += a[j];
if(!maps[i].containsKey(summ)) maps[i].put(summ, j);
int x = sums.getOrDefault(summ, 0);
sums.put(summ, x + 1);
}
}
int max = 0;
int goodSumm = 0;
for(int summ : sums.keySet()){
if(sums.get(summ) <= max) continue;
int right = -1;
int ans = 0;
for(int j = 0;j<n;j++){
if(!maps[j].containsKey(summ)) continue;
int end = maps[j].get(summ);
if(right == -1){
right = end;
ans++;
continue;
}
if(j > right){
right = end;
ans++;
continue;
}
if(end < right){
right = end;
}
}
if(max < ans){
max = ans;
goodSumm = summ;
}
}
int left = -1;
int right = -1;
List<Integer> ans = new ArrayList<>();
for(int j = 0;j<n;j++){
if(!maps[j].containsKey(goodSumm)) continue;
int start = j;
int end = maps[j].get(goodSumm);
if(right == -1){
left = j;
right = end;
continue;
}
if(start > right){
ans.add(left + 1);
ans.add(right + 1);
left = start;
right = end;
continue;
}
if(end < right){
left = start;
right = end;
}
}
ans.add(left + 1);
ans.add(right + 1);
out.println(max);
for(int i = 0;i<ans.size();i+=2){
out.println(ans.get(i) + " " + ans.get(i + 1));
}
}
public static void main(String[] args) throws FileNotFoundException {
new A().run();
}
void run() throws FileNotFoundException {
init();
solve();
out.close();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
if(!filename.equals("")) {
in = new BufferedReader(new FileReader(new File(filename + ".in")));
out = new PrintWriter(new File(filename + ".out"));
return;
}
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
String readLine(){
try{
return in.readLine();
}catch (Exception e){
throw new RuntimeException(e);
}
}
String readString(){
while(!tok.hasMoreTokens()){
String nextLine = readLine();
if(nextLine == null) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt(){
return Integer.parseInt(readString());
}
long readLong(){
return Long.parseLong(readString());
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
//package round503;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class B2 {
Scanner in;
PrintWriter out;
String INPUT = "";
// 12123432
// 12343212
int qc = 0;
int n;
int[] table;
int val(int x)
{
if(table[x] != Integer.MIN_VALUE)return table[x];
if(qc > 60)throw new RuntimeException();
out.println("? " + (x+1));
out.flush();
table[x] = ni();
if(table[x] == table[(x+table.length/2) % table.length]){
if(x >= n/2)x -= n/2;
out.println("! " + (x+1));
out.flush();
throw new IllegalStateException();
}
return table[x];
}
void solve()
{
n = ni();
if(n % 4 != 0){
out.println("! -1");
out.flush();
return;
}
table = new int[n];
Arrays.fill(table, Integer.MIN_VALUE);
Random gen = new Random(1);
try{
outer:
while(true){
int pu = gen.nextInt(n);
int pd = (pu+n/2)%n;
int pl = (pu + gen.nextInt(n/2-1)+1)%n;
int pr = (pl+n/2)%n;
int vu = val(pu), vd = val(pd);
int vl = val(pl), vr = val(pr);
if(cross(vu, vl, vd, vr)){
}else if(cross(vu, vr, vd, vl)){
int npu = pr, npl = pu;
int npd = pl, npr = pd;
pu = npu; pl = npl;
pd = npd; pr = npr;
vu = val(pu);
vl = val(pl);
vd = val(pd);
vr = val(pr);
}else{
continue outer;
}
// u-l d-r
while(true){
int pul = h(pu, pl, n);
int vul = val(pul);
int pdr = h(pd, pr, n);
int vdr = val(pdr);
if(cross(vul, vu, vdr, vd)){
pl = pul; vl = vul;
pr = pdr; vr = vdr;
}else{
pu = pul; vu = vul;
pd = pdr; vd = vdr;
}
}
}
}catch(IllegalStateException e)
{
}
}
int h(int a, int b, int n)
{
if(a > b){
b += n;
}
int u = (a+b)/2;
if(u >= n)u -= n;
return u;
}
boolean cross(int a, int b, int c, int d)
{
return Integer.signum(c-a) != Integer.signum(d-b);
}
void run() throws Exception
{
in = oj ? new Scanner(System.in) : new Scanner(INPUT);
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception
{
new B2().run();
}
int ni() { return Integer.parseInt(in.next()); }
long nl() { return Long.parseLong(in.next()); }
double nd() { return Double.parseDouble(in.next()); }
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
//
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Cf1017A {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int result = 1;
int thomasSum = 0;
StringTokenizer stk;
stk = new StringTokenizer(br.readLine());
int first = Integer.parseInt(stk.nextToken());
int second = Integer.parseInt(stk.nextToken());
int third = Integer.parseInt(stk.nextToken());
int fourth = Integer.parseInt(stk.nextToken());
thomasSum = first + second + third + fourth;
int tmp;
for (int i = 1; i < n; i++) {
stk = new StringTokenizer(br.readLine());
first = Integer.parseInt(stk.nextToken());
second = Integer.parseInt(stk.nextToken());
third = Integer.parseInt(stk.nextToken());
fourth = Integer.parseInt(stk.nextToken());
tmp = first + second + third + fourth;
if (tmp > thomasSum)
result++;
}
System.out.println(result);
}
}
|
linear
|
1017_A. The Rank
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class main {
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int n = nextInt();
int d = nextInt();
int ans = 2;
int b[] = new int [n];
Arrays.sort(b);
for (int i = 0; i < n; i++) {
b[i] = nextInt();
}
for (int i = 1; i < n; i++) {
if (b[i] - b[i - 1] >= d * 2) {
ans++;
}
if (b[i] - b[i - 1] > d * 2) {
ans++;
}
}
pw.println(ans);
pw.close();
}
static BufferedReader br;
static StringTokenizer st = new StringTokenizer("");
public static int nextInt() throws IOException {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return Integer.parseInt(st.nextToken());
}
public static String next() throws IOException {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public static double nextDouble() throws IOException {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return Double.parseDouble(st.nextToken());
}
public static long nextLong() throws IOException {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return Long.parseLong(st.nextToken());
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import static java.util.Arrays.*;
import static java.lang.Math.*;
import static java.math.BigInteger.*;
import java.util.*;
import java.math.*;
import java.io.*;
public class B implements Runnable
{
String file = "input";
boolean TEST = false;
double EPS = 1e-8;
void solve() throws IOException
{
int n = nextInt(), k = nextInt(), A = nextInt();
int[] level = new int[n];
int[] loyal = new int[n];
for(int i = 0; i < n; i++)
{
level[i] = nextInt();
loyal[i] = nextInt();
}
double res = 0;
for(int mask = 0; mask < 1 << (n + k - 1); mask++)
{
if(Integer.bitCount(mask) != k) continue;
int[] L = new int[n];
int x = mask;
for(int i = 0; i < n; i++)
{
L[i] = loyal[i];
while(x % 2 == 1)
{
L[i] += 10;
x /= 2;
}
L[i] = min(L[i], 100);
x /= 2;
}
double tmp = 0;
for(int w = 0; w < 1 << n; w++)
{
double p = 1.;
double B = 0;
for(int i = 0; i < n; i++)
if((w >> i & 1) != 0) p *= L[i] / 100.;
else
{
p *= (100 - L[i]) / 100.;
B += level[i];
}
if(Integer.bitCount(w) * 2 > n) tmp += p;
else tmp += p * (A / (A + B));
}
res = max(res, tmp);
}
out.printf("%.8f\n", res);
}
class Player
{
}
String next() throws IOException
{
while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(input.readLine());
return st.nextToken();
}
int nextInt() throws IOException
{
return Integer.parseInt(next());
}
long nextLong() throws IOException
{
return Long.parseLong(next());
}
double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
void print(Object... o)
{
System.out.println(deepToString(o));
}
void gcj(Object o)
{
String s = String.valueOf(o);
out.println("Case #" + test + ": " + s);
System.out.println("Case #" + test + ": " + s);
}
BufferedReader input;
PrintWriter out;
StringTokenizer st;
int test;
void init() throws IOException
{
if(TEST) input = new BufferedReader(new FileReader(file + ".in"));
else input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
}
public static void main(String[] args) throws IOException
{
new Thread(null, new B(), "", 1 << 20).start();
}
public void run()
{
try
{
init();
if(TEST)
{
int runs = nextInt();
for(int i = 0; i < runs; i++) solve();
}
else solve();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
long b=0;long p=1;
Scanner s=new Scanner(System.in);
long m=s.nextLong();
long x=1;
do{
p=(m+b)/x;
b=10*b+10;
x++;
}while(p/(long)Math.pow(10, x-1)!=0);
rest :
x--;b=b/10-1;
b=x*p-b;
b=m-b;
b=x-b-1;
p/=(long)Math.pow(10, b);
p%=10;
System.out.println(p);
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.util.*;
public class A {
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int a[] = new int[n+1];
for(int i=1 ; i<=n ; i++) a[i] = sc.nextInt();
int cnt = 0;
for(int i=1 ; i<=n ; i++) {
for(int j=i-1 ; j>=1 ; j--) {
if(a[i]<a[j])
++cnt;
}
}
//System.out.println(cnt);
int q = sc.nextInt();
cnt = cnt % 2;
while(q-->0) {
int x = sc.nextInt();
int y = sc.nextInt();
int r = y-x+1;
long ok = (r*(r-1))/2;
if(ok%2==0) {
}
else {
cnt ^= 1 ;
}
System.out.println(cnt==0?"even":"odd");
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
/*input
3
2 3
2 5 7
4 2 4
3 6
4 1 5 2 10 4
8 6 6 4 9 10
5 4 9 5 8 7
3 3
9 9 9
1 1 1
1 1 1
*/
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.util.Random;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.*;
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);
int T = in.nextInt();
for (int cT = 1; cT <= T; cT++) {
Task solver = new Task();
solver.solve(cT, in, out);
}
out.close();
}
static class data {
int val, col;
data(int _val, int _col) {
val = _val; col = _col;
}
@Override
public String toString() {
return String.format("(%d,%d)", val, col);
}
}
static class Task {
int[][] a;
int[][] b;
int[][] dp;
int[][] mb;
ArrayList<data> all = new ArrayList<>();
Set<Integer> st = new HashSet<>();
int n, m;
int cal(int col, int mask) {
if (col == m) {
if (Integer.bitCount(mask) == n) return 0;
return (int)(-1e9);
}
int ret = dp[col][mask];
if (ret != -1) return ret;
int rmask = mask ^ ((1 << n) - 1);
// ret is not a reference
for (int mask2 = rmask; mask2 > 0; mask2 = rmask & (mask2 - 1)) {
int now = cal(col + 1, mask | mask2) + mb[col][mask2];
ret = Math.max(ret, now);
}
ret = Math.max(ret, cal(col + 1, mask));
dp[col][mask] = ret;
return ret;
}
public static int fsb(int n) {
return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
void prepMb() {
// col, cyclic, mask
for (int col = 0; col < m; col++) {
for (int mask = 1; mask < (1 << n); mask++) {
int nmask = mask;
while ((nmask & 1) == 0) nmask >>= 1;
if (nmask == mask) {
for (int shift = 0; shift < n; shift++) {
int sum = 0;
int tmask = mask;
while (tmask > 0) {
int i = Integer.numberOfTrailingZeros(tmask);
sum += b[(i + shift) % n][col]; tmask ^= (1 << i);
}
mb[col][mask] = Math.max(mb[col][mask], sum);
}
} else {
mb[col][mask] = mb[col][nmask];
}
}
}
}
void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt(); m = in.nextInt();
a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
all.add(new data(a[i][j], j));
}
}
Collections.sort(all, new Comparator<data>() {
@Override
public int compare(final data o1, final data o2) {
return -(o1.val - o2.val);
}
});
for (data it : all) {
if (st.size() == n) break;
st.add(it.col);
}
b = new int[n][st.size()];
int rcol = 0;
for (int col : st) {
for (int row = 0; row < n; row++)
b[row][rcol] = a[row][col];
rcol++;
}
m = st.size();
dp = new int[n][(1 << n)];
mb = new int[m][(1 << n)];
prepMb();
for (int i = 0; i < n; i++)
Arrays.fill(dp[i], -1);
System.out.println(cal(0, 0));
}
}
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());
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;
public class B {
static Vector<Integer> primes;
public static void main(String[] args) throws IOException {
InputReader myScanner = new InputReader();
int n = myScanner.nextInt(), k = myScanner.nextInt();
myScanner.hasNext();
int all[] = new int[n];
boolean numbers[] = new boolean[100100];
int diff[] = new int[n];
all[0] = myScanner.nextInt();
diff[0] = 1;
numbers[all[0]] = true;
int r = -1;
if (k == 1)
r = 1;
for (int i = 1; i < all.length; i++) {
all[i] = myScanner.nextInt();
diff[i] = diff[i - 1];
if (!numbers[all[i]]) {
if (r == -1 && diff[i] + 1 == k)
r = i + 1;
numbers[all[i]] = true;
diff[i]++;
}
}
if (r == -1)
System.out.println(-1 + " " + -1);
else {
numbers = new boolean[100010];
int l = 0, cnt = 1;
numbers[all[r - 1]] = true;
if (k == 1)
System.out.println(1 + " " + 1);
else {
for (int i = r - 2; i >= 0; i--) {
if (!numbers[all[i]]) {
numbers[all[i]] = true;
cnt++;
}
if (cnt == k) {
l = i + 1;
break;
}
}
System.out.println(l + " " + r);
}
}
}
static class InputReader {
BufferedReader buff;
StringTokenizer tok;
String cur;
public InputReader() throws IOException {
buff = new BufferedReader(new InputStreamReader(System.in));
tok = new StringTokenizer(cur = buff.readLine());
}
public boolean hasNext() throws IOException {
if (!tok.hasMoreElements()) {
cur = buff.readLine();
if (cur == null)
return false;
tok = new StringTokenizer(cur);
}
return true;
}
public String next() throws IOException {
while (!tok.hasMoreElements())
tok = new StringTokenizer(cur = buff.readLine());
return tok.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
public long nextLong() throws NumberFormatException, IOException {
while (!tok.hasMoreElements())
tok = new StringTokenizer(cur = buff.readLine());
return Long.parseLong(next());
}
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
import java.util.Scanner;
public class Seq2 {
static void metod() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
int min = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < min)
min = a[i];
}
int min2 = min;
boolean t = false;
for (int i = 0; i < a.length; i++) {
if (a[i] != min) {
if (!t) {
min2 = a[i];
t = true;
} else {
if (min2 > a[i])
min2 = a[i];
}
}
}
System.out.println((min == min2) ? "NO" : min2);
}
public static void main(String[] args) {
Seq2.metod();
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) throws IOException {
new D().solve();
}
void solve() throws IOException {
Scanner sc = new Scanner(System.in);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] sp;
long L = sc.nextLong();
long R = sc.nextLong();
if (L == R) {
System.out.println(0);
} else {
System.out.println(Long.highestOneBit(R ^ L) * 2 - 1);
}
}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
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 Ideone
{
static double p[][];
static double dp[];
static int n;
public static int BitCount(int u) {
int uCount;
uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
return ((uCount + (uCount >> 3)) & 030707070707) % 63;
}
public static double f(int mask) {
if (dp[mask] > -0.5)
return dp[mask];
dp[mask] = 0;
int ones = BitCount(mask);
double pairs = (((ones * (ones + 1))) >> 1);
//System.out.println(pairs);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((mask & (1 << i)) != 0 && (mask & (1 << j)) == 0)
dp[mask] += f(mask | (1 << j)) * p[i][j] / pairs;
}
}
return dp[mask];
}
public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(bf.readLine());
p = new double[n][n];
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(bf.readLine());
for (int j = 0; j < n; j++) {
p[i][j] = Double.parseDouble(st.nextToken());
}
}
dp = new double[1 << n];
Arrays.fill(dp, -1.0);
dp[(1 << n) - 1] = 1.;
for (int i = 0; i < n - 1; i++) {
System.out.print(f(1 << i) + " ");
}
System.out.println(f((1 << (n - 1))));
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
/**
* Created by IntelliJ IDEA.
* User: Taras_Brzezinsky
* Date: 8/14/11
* Time: 9:53 PM
* To change this template use File | Settings | File Templates.
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.FileReader;
import java.util.StringTokenizer;
import java.io.IOException;
import java.util.Arrays;
public class Fish extends Thread {
public Fish() {
this.input = new BufferedReader(new InputStreamReader(System.in));
this.output = new PrintWriter(System.out);
this.setPriority(Thread.MAX_PRIORITY);
}
static int getOnes(int mask) {
int result = 0;
while (mask != 0) {
mask &= mask - 1;
++result;
}
return result;
}
private void solve() throws Throwable {
int n = nextInt();
double[][] a = new double[n][n];
double[] dp = new double[(1 << n)];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
a[i][j] = nextDouble();
}
}
int limit = (1 << n) - 1;
//dp[mask] = probability of current subset (mask) to remain in the end
dp[limit] = 1.0;
for (int mask = limit; mask > 0; --mask) {
int cardinality = getOnes(mask);
if (cardinality < 2) {
continue;
}
int probability = cardinality * (cardinality - 1) / 2;
for (int first = 0; first < n; ++first) {
if ((mask & powers[first]) != 0) {
for (int second = first + 1; second < n; ++second) {
if ((mask & powers[second]) != 0) {
dp[mask - powers[first]] += dp[mask] * a[second][first] / probability;
dp[mask - powers[second]] += dp[mask] * a[first][second] / probability;
}
}
}
}
}
for (int i = 0; i < n; ++i) {
output.printf("%.10f ", dp[powers[i]]);
}
}
public void run() {
try {
solve();
} catch (Throwable e) {
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(666);
} finally {
output.flush();
output.close();
}
}
public static void main(String[] args) {
new Fish().start();
}
private String nextToken() throws IOException {
while (tokens == null || !tokens.hasMoreTokens()) {
tokens = new StringTokenizer(input.readLine());
}
return tokens.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static final int powers[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144};
private BufferedReader input;
private PrintWriter output;
private StringTokenizer tokens = null;
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.lang.reflect.Array;
public class codeforces
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = in.nextInt();
long U = in.nextLong();
long[] E = new long[n];
double max = -1;
for(int i=0;i<n;i++)
E[i] = in.nextLong();
for(int k=1;k<n-1;k++)
{
int i = k + 1, j = n - 1, mid = 0;
double T = 0;
while(i < j)
{
mid = (int)Math.ceil((double)(i+j)/2);
if(E[mid] - E[k-1] <= U)
i = mid;
else
j = mid - 1;
}
j = k;
k = i;
i = j - 1;
T = E[k] - E[j];
T /= E[k] - E[i];
if(E[k] - E[i] <= U)
max = Math.max(max, T);
k = j;
}
pw.println(max);
pw.flush();
pw.close();
}
/* public static void DFS(int sourse)
{
int count = 0;
visited[sourse] = true;
for(int u : adj[sourse])
{
if(!visited[u])
{
DFS(u);
}
}
}*/
public static ArrayList Divisors(long n)
{
ArrayList<Long> div = new ArrayList<>();
for (long i=1; i<=Math.sqrt(n); i++)
{
if (n%i == 0)
{
div.add(i);
if(n/i != i)
div.add(n/i);
}
}
return div;
}
public static int BinarySearch(long[] a, long k)
{
int n = a.length;
int i = 0, j = n-1;
int mid = 0;
if(k < a[0])
return 0;
else if(k >= a[n-1])
return n;
else
{
while(j - i > 1)
{
mid = (i+j)/2;
if(k >= a[mid])
i = mid;
else
j = mid;
}
}
return i+1;
}
public static long GCD(long a,long b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
static class pair implements Comparable<pair>
{
Integer x, y;
pair(int x,int y)
{
this.x=x;
this.y=y;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString()
{
return x+" "+y;
}
public boolean equals(Object o)
{
if (o instanceof pair)
{
pair p = (pair)o;
return p.x - x == 0 && p.y - y == 0 ;
}
return false;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode();
}
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
static class CodeX {
public static void sort(long arr[]) {
merge_sort(arr, 0, arr.length - 1);
}
private static void merge_sort(long A[], long start, long end) {
if (start < end) {
long mid = (start + end) / 2;
merge_sort(A, start, mid);
merge_sort(A, mid + 1, end);
merge(A, start, mid, end);
}
}
private static void merge(long A[], long start,long mid, long end) {
long p = start, q = mid + 1;
long Arr[] = new long[(int)(end - start + 1)];
long k = 0;
for (int i = (int)start; i <= end; i++) {
if (p > mid)
Arr[(int)k++] = A[(int)q++];
else if (q > end)
Arr[(int)k++] = A[(int)p++];
else if (A[(int)p] < A[(int)q])
Arr[(int)k++] = A[(int)p++];
else
Arr[(int)k++] = A[(int)q++];
}
for (int i = 0; i < k; i++) {
A[(int)start++] = Arr[i];
}
}
}
}
|
nlogn
|
957_C. Three-level Laser
|
CODEFORCES
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.text.*;
public class cf276d {
static BufferedReader br;
static Scanner sc;
static PrintWriter out;
public static void initA() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new FileReader("input.txt"));
sc = new Scanner(System.in);
//out = new PrintWriter("output.txt");
out = new PrintWriter(System.out);
} catch (Exception e) {
}
}
public static void initB() {
try {
br = new BufferedReader(new FileReader("input.txt"));
sc = new Scanner(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
}
}
public static String getString() {
try {
return br.readLine();
} catch (Exception e) {
}
return "";
}
public static Integer getInt() {
try {
return Integer.parseInt(br.readLine());
} catch (Exception e) {
}
return 0;
}
public static Integer[] getIntArr() {
try {
StringTokenizer temp = new StringTokenizer(br.readLine());
int n = temp.countTokens();
Integer temp2[] = new Integer[n];
for (int i = 0; i < n; i++) {
temp2[i] = Integer.parseInt(temp.nextToken());
}
return temp2;
} catch (Exception e) {
}
return null;
}
public static Long[] getLongArr() {
try {
StringTokenizer temp = new StringTokenizer(br.readLine());
int n = temp.countTokens();
Long temp2[] = new Long[n];
for (int i = 0; i < n; i++) {
temp2[i] = Long.parseLong(temp.nextToken());
}
return temp2;
} catch (Exception e) {
}
return null;
}
public static String[] getStringArr() {
try {
StringTokenizer temp = new StringTokenizer(br.readLine());
int n = temp.countTokens();
String temp2[] = new String[n];
for (int i = 0; i < n; i++) {
temp2[i] = (temp.nextToken());
}
return temp2;
} catch (Exception e) {
}
return null;
}
public static int getMax(Integer[] ar) {
int t = ar[0];
for (int i = 0; i < ar.length; i++) {
if (ar[i] > t) {
t = ar[i];
}
}
return t;
}
public static void print(Object a) {
out.println(a);
}
public static int nextInt() {
return sc.nextInt();
}
public static double nextDouble() {
return sc.nextDouble();
}
public static void main(String[] ar) {
initA();
solve();
out.flush();
}
public static void print2(Object o){System.out.println(o);}
public static void solve() {
Long xx[] = getLongArr();
long l = xx[0];
long r = xx[1];
BigInteger a = BigInteger.valueOf(l);
BigInteger b = BigInteger.valueOf(r);
if(l==r){
print(0);return;
}
String a2 = a.toString(2);
String b2 = b.toString(2);
int selisihpjg = Math.abs(a2.length() - b2.length());
while (selisihpjg-- > 0) {
a2 = "0" + a2;
//print2("wewe");
}
//print2(a2);
//print2(b2);
String out = "";
for (int i = 0; i < b2.length(); i++) {
//print2("i="+i);
if (a2.charAt(i) != b2.charAt(i)) {
for (int ii = i; ii < b2.length(); ii++) {
out += "1";
}
//print2(out);
print2(new BigInteger(out, 2));
return;
}
}
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main implements Runnable {
public void _main() throws IOException {
int n = nextInt();
int even = 0, odd = 0, atEven = -1, atOdd = -1;
for (int i = 0; i < n; i++) {
if (nextInt() % 2 == 0) {
atEven = i;
++even;
}
else {
atOdd = i;
++odd;
}
}
if (odd == 1)
out.print(atOdd + 1);
else
out.print(atEven + 1);
}
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
|
25_A. IQ test
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.HashSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author sheep
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
HashSet<Integer> set = new HashSet<Integer>();
int a[] = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
}
Arrays.sort(a);
int ans = 0;
int ptr = -1;
boolean chosen[] = new boolean[n];
for (int i = 0; i < n; ++i) {
while (ptr + 1 < i && a[ptr + 1] * (long)k <= a[i]) {
++ptr;
}
if (a[i] % k != 0 || ptr == -1 || !chosen[ptr] || a[ptr] * (long)k != a[i]) {
++ans;
chosen[i] = true;
}
}
out.println(ans);
}
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new UnknownError();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
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.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author caoash
*/
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);
BObtainingTheString solver = new BObtainingTheString();
solver.solve(1, in, out);
out.close();
}
static class BObtainingTheString {
public void solve(int testNumber, FastScanner br, PrintWriter pw) {
int n = br.nextInt();
String s = br.nextString();
String t = br.nextString();
char[] sarr = new char[n];
char[] tarr = new char[n];
int[] sAppear = new int[26];
int[] tAppear = new int[26];
for (int i = 0; i < s.length(); i++) {
sarr[i] = s.charAt(i);
tarr[i] = t.charAt(i);
sAppear[s.charAt(i) - 'a']++;
tAppear[t.charAt(i) - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (sAppear[i] != tAppear[i]) {
pw.println(-1);
pw.close();
}
}
ArrayList<Integer> ans = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
char curr = tarr[i];
for (int j = i + 1; j < n; j++) {
if (sarr[j] == curr) {
for (int k = j; k > i; k--) {
ans.add(k);
char temp = sarr[k - 1];
sarr[k - 1] = sarr[k];
sarr[k] = temp;
}
break;
}
}
}
pw.println(ans.size());
for (int e : ans) {
pw.print(e + " ");
}
pw.close();
}
}
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastScanner.SpaceCharFilter filter;
public FastScanner(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 String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
quadratic
|
1015_B. Obtaining the String
|
CODEFORCES
|
//package round8;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
public class C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int x = ni(), y = ni();
int n = ni();
int[][] co = new int[n][];
for(int i = 0;i < n;i++){
co[i] = new int[]{ni()-x, ni()-y};
}
int[] c1 = new int[n];
int[][] c2 = new int[n][n];
for(int i = 0;i < n;i++){
c1[i] = (co[i][0]*co[i][0]+co[i][1]*co[i][1])*2;
}
for(int i = 0;i < n;i++){
for(int j = i+1;j < n;j++){
c2[i][j] = c2[j][i] = (co[i][0]*co[i][0]+co[i][1]*co[i][1])+(co[j][0]*co[j][0]+co[j][1]*co[j][1])+(co[j][0]-co[i][0])*(co[j][0]-co[i][0])+(co[j][1]-co[i][1])*(co[j][1]-co[i][1]);
}
}
int[] dp = new int[1<<n];
int[] prev = new int[1<<n];
prev[0] = -1;
for(int i = 1;i < 1<<n;i++){
int a = Integer.numberOfTrailingZeros(i);
dp[i] = c1[a] + dp[i^1<<a];
prev[i] = 1<<a;
for(int j = a+1;j < n;j++){
if(i<<31-j<0){
int v = dp[i^1<<a^1<<j] + c2[a][j];
if(v < dp[i]){
dp[i] = v;
prev[i] = 1<<a^1<<j;
}
}
}
}
out.println(dp[(1<<n)-1]);
int cur = (1<<n)-1;
out.print("0");
while(true){
int targ;
if(prev[cur] == -1){
targ = cur;
}else{
targ = prev[cur];
cur ^= prev[cur];
}
int a = Integer.numberOfTrailingZeros(targ);
int b = Integer.numberOfTrailingZeros(targ&targ-1);
if(targ == 1<<a){
out.print(" " + (a+1));
}else{
out.print(" " + (a+1));
out.print(" " + (b+1));
}
out.print(" 0");
if(cur == 0)break;
}
out.println();
}
void run() throws Exception
{
// int n = 24, m = 99999;
// Random gen = new Random();
// StringBuilder sb = new StringBuilder();
// sb.append(0 + " " + 0 + " " + n + " ");
// for(int i = 0;i < n;i++){
// sb.append(gen.nextInt(100) + " ");
// sb.append(gen.nextInt(100) + " ");
// }
// INPUT = sb.toString();
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception
{
new C().run();
}
public int ni()
{
try {
int num = 0;
boolean minus = false;
while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
if(num == '-'){
num = 0;
minus = true;
}else{
num -= '0';
}
while(true){
int b = is.read();
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
}
} catch (IOException e) {
}
return -1;
}
public long nl()
{
try {
long num = 0;
boolean minus = false;
while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
if(num == '-'){
num = 0;
minus = true;
}else{
num -= '0';
}
while(true){
int b = is.read();
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
}
} catch (IOException e) {
}
return -1;
}
public String ns()
{
try{
int b = 0;
StringBuilder sb = new StringBuilder();
while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
if(b == -1)return "";
sb.append((char)b);
while(true){
b = is.read();
if(b == -1)return sb.toString();
if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
sb.append((char)b);
}
} catch (IOException e) {
}
return "";
}
public char[] ns(int n)
{
char[] buf = new char[n];
try{
int b = 0, p = 0;
while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
if(b == -1)return null;
buf[p++] = (char)b;
while(p < n){
b = is.read();
if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
buf[p++] = (char)b;
}
return Arrays.copyOf(buf, p);
} catch (IOException e) {
}
return null;
}
double nd() { return Double.parseDouble(ns()); }
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
//package global14;
import java.io.*;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Queue;
public class E2 {
InputStream is;
FastWriter out;
String INPUT = "";
public static int[][] enumFIF(int n, int mod) {
int[] f = new int[n + 1];
int[] invf = new int[n + 1];
f[0] = 1;
for (int i = 1; i <= n; i++) {
f[i] = (int) ((long) f[i - 1] * i % mod);
}
long a = f[n];
long b = mod;
long p = 1, q = 0;
while (b > 0) {
long c = a / b;
long d;
d = a;
a = b;
b = d % b;
d = p;
p = q;
q = d - c * q;
}
invf[n] = (int) (p < 0 ? p + mod : p);
for (int i = n - 1; i >= 0; i--) {
invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod);
}
return new int[][]{f, invf};
}
public static long[] enumPows(int a, int n, int mod)
{
a %= mod;
long[] pows = new long[n+1];
pows[0] = 1;
for(int i = 1;i <= n;i++)pows[i] = pows[i-1] * a % mod;
return pows;
}
void solve()
{
int N = ni();
final int mod = ni();
long[] p2 = enumPows(2, 1000, mod);
int[][] fif = enumFIF(1000, mod);
long[][] dp = new long[N+2][N+1];
dp[0][0] = 1;
for(int i = 0;i <= N+1;i++){
for(int j = 0;j <= N;j++){
// 11110
for(int k = 1;i+k+1 <= N+1 && j+k <= N;k++){
dp[i+k+1][j+k] += dp[i][j] * fif[1][k] % mod * p2[k-1];
dp[i+k+1][j+k] %= mod;
}
}
// tr(dp[i]);
}
long ans = 0;
for(int i = 1;i <= N;i++){
ans += dp[N+1][i] * fif[0][i];
ans %= mod;
}
out.println(ans);
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new FastWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new E2().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private long[] nal(int n)
{
long[] a = new long[n];
for(int i = 0;i < n;i++)a[i] = nl();
return a;
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[][] nmi(int n, int m) {
int[][] map = new int[n][];
for(int i = 0;i < n;i++)map[i] = na(m);
return map;
}
private int ni() { return (int)nl(); }
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public static class FastWriter
{
private static final int BUF_SIZE = 1<<13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter(){out = null;}
public FastWriter(OutputStream os)
{
this.out = os;
}
public FastWriter(String path)
{
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b)
{
buf[ptr++] = b;
if(ptr == BUF_SIZE)innerflush();
return this;
}
public FastWriter write(char c)
{
return write((byte)c);
}
public FastWriter write(char[] s)
{
for(char c : s){
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
}
return this;
}
public FastWriter write(String s)
{
s.chars().forEach(c -> {
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x)
{
if(x == Integer.MIN_VALUE){
return write((long)x);
}
if(ptr + 12 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x)
{
if(x == Long.MIN_VALUE){
return write("" + x);
}
if(ptr + 21 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision)
{
if(x < 0){
write('-');
x = -x;
}
x += Math.pow(10, -precision)/2;
// if(x < 0){ x = 0; }
write((long)x).write(".");
x -= (long)x;
for(int i = 0;i < precision;i++){
x *= 10;
write((char)('0'+(int)x));
x -= (int)x;
}
return this;
}
public FastWriter writeln(char c){
return write(c).writeln();
}
public FastWriter writeln(int x){
return write(x).writeln();
}
public FastWriter writeln(long x){
return write(x).writeln();
}
public FastWriter writeln(double x, int precision){
return write(x, precision).writeln();
}
public FastWriter write(int... xs)
{
boolean first = true;
for(int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs)
{
boolean first = true;
for(long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln()
{
return write((byte)'\n');
}
public FastWriter writeln(int... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(long... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(char[] line)
{
return write(line).writeln();
}
public FastWriter writeln(char[]... map)
{
for(char[] line : map)write(line).writeln();
return this;
}
public FastWriter writeln(String s)
{
return write(s).writeln();
}
private void innerflush()
{
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush()
{
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) { return write(b); }
public FastWriter print(char c) { return write(c); }
public FastWriter print(char[] s) { return write(s); }
public FastWriter print(String s) { return write(s); }
public FastWriter print(int x) { return write(x); }
public FastWriter print(long x) { return write(x); }
public FastWriter print(double x, int precision) { return write(x, precision); }
public FastWriter println(char c){ return writeln(c); }
public FastWriter println(int x){ return writeln(x); }
public FastWriter println(long x){ return writeln(x); }
public FastWriter println(double x, int precision){ return writeln(x, precision); }
public FastWriter print(int... xs) { return write(xs); }
public FastWriter print(long... xs) { return write(xs); }
public FastWriter println(int... xs) { return writeln(xs); }
public FastWriter println(long... xs) { return writeln(xs); }
public FastWriter println(char[] line) { return writeln(line); }
public FastWriter println(char[]... map) { return writeln(map); }
public FastWriter println(String s) { return writeln(s); }
public FastWriter println() { return writeln(); }
}
public void trnz(int... o)
{
for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" ");
System.out.println();
}
// print ids which are 1
public void trt(long... o)
{
Queue<Integer> stands = new ArrayDeque<>();
for(int i = 0;i < o.length;i++){
for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x));
}
System.out.println(stands);
}
public void tf(boolean... r)
{
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
public void tf(boolean[]... b)
{
for(boolean[] r : b) {
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
System.out.println();
}
public void tf(long[]... b)
{
if(INPUT.length() != 0) {
for (long[] r : b) {
for (long x : r) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
System.out.println();
}
}
public void tf(long... b)
{
if(INPUT.length() != 0) {
for (long x : b) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
BufferedReader in;
StringTokenizer st;
PrintWriter out;
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(next());
}
long nextLong() throws Exception {
return Long.parseLong(next());
}
double nextDouble() throws Exception {
return Double.parseDouble(next());
}
void solve() throws Exception {
int n = nextInt(), k = nextInt(), s = nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = -nextInt();
Arrays.sort(a);
for(int i=0;i<n;i++)
{
if (s>=k)
{
out.println(i);
return;
}
s += -a[i];
s--;
}
if (s<k)
out.println(-1);
else
out.println(n);
}
void run() {
try {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
new A().run();
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
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 A {
static final int[] dx = {0, 0, -1, 1};
static final int[] dy = {-1, 1, 0, 0};
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner("input.txt");
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
// Scanner sc = new Scanner(System.in);
// PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt(), M = sc.nextInt();
int[][] dist = new int[N][M];
Queue<Integer> q = new LinkedList<>();
int K = sc.nextInt();
while(K-->0)
{
int x = sc.nextInt() - 1, y = sc.nextInt() - 1;
q.add(x * M + y);
dist[x][y] = 1;
}
int max = 0, ansX = -1, ansY = -1;
while(!q.isEmpty())
{
int u = q.remove(), x = u / M, y = u % M;
if(dist[x][y] > max)
max = dist[ansX = x][ansY = y];
for(int k = 0; k < 4; ++k)
{
int nx = x + dx[k], ny = y + dy[k];
if(nx >= 0 && ny >= 0 && nx < N && ny < M && dist[nx][ny] == 0)
{
dist[nx][ny] = dist[x][y] + 1;
q.add(nx * M + ny);
}
}
}
out.printf("%d %d\n", ansX + 1, ansY + 1);
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
|
import java.util.*;
import java.io.*;
public class A
{
public static void main(String[] args)
{
Kattio io = new Kattio(System.in);
int n = io.getInt();
int ans = 0;
int V = n;
int A = n;
A -= n/2;
ans += n/2;
V -= A;
ans += A;
A -= n/2;
ans += n/2;
io.println(ans);
io.flush();
}
}
class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int getInt() {
return Integer.parseInt(nextToken());
}
public double getDouble() {
return Double.parseDouble(nextToken());
}
public long getLong() {
return Long.parseLong(nextToken());
}
public String getWord() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) { }
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
for (int i = 0; i < n; i++) b[i] = sc.nextInt();
int c[] = new int[2 * n];
c[0] = a[0];
for (int i = 1; i < n; i++) {
c[i * 2] = a[i];
c[i * 2 - 1] = b[i];
if (a[i] == 1 || b[i] == 1) {
System.out.print(-1);
System.exit(0);
}
}
c[2 * n - 1] = b[0];
if (a[0] == 1 || b[0] == 1) {
System.out.print(-1);
System.exit(0);
}
System.out.println(bin_search(c, m));
}
private static double bin_search(int[] c, int m) {
double start = 0;
double end = Integer.MAX_VALUE;
double mid;
while (start + 0.0000001 < end) {
mid = (start + end) / 2;
if (test(mid, m, c)) end = mid;
else start = mid;
}
return end;
}
private static boolean test(double fuel, int m, int[] c) {
for (int i = 0; i < c.length; i++) {
fuel -= (m + fuel) / c[i];
if (fuel < 0) {
return false;
}
}
return true;
}
}
|
nlogn
|
1010_A. Fly
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class F11141 {
static class Solver {
ArrayList<int[]> ranges[];
HashMap<Long, Integer> hm = new HashMap<>();
int id(long s) {
if (!hm.containsKey(s))
hm.put(s, hm.size());
return hm.get(s);
}
// max disjoint range set in ranges[r]
int[] memo;
int go(int r) {
memo[N] = 0;
int last = N;
for(int[] a : ranges[r]) {
while(a[0] < last) {
memo[last - 1] = memo[last];
last--;
}
memo[a[0]] = Math.max(memo[a[0]], Math.max(memo[a[0]], 1 + memo[a[1] + 1]));
last = a[0];
}
while(0 < last) {
memo[last - 1] = memo[last];
last--;
}
return memo[0];
}
ArrayDeque<int[]> ans = new ArrayDeque<>();
void go2(int r) {
memo[N] = 0;
int last = N;
int minAt[] = new int[N], oo = 987654321;
Arrays.fill(minAt, oo);
for(int[] a : ranges[r]) {
minAt[a[0]] = Math.min(minAt[a[0]], a[1] - a[0]);
while(a[0] < last) {
memo[last - 1] = memo[last];
last--;
}
memo[a[0]] = Math.max(memo[a[0]], Math.max(memo[a[0]], 1 + memo[a[1] + 1]));
last = a[0];
}
while(0 < last) {
memo[last - 1] = memo[last];
last--;
}
int k = 0;
for(; k < N;) {
if(minAt[k] == oo || memo[k] != 1 + memo[k + minAt[k] + 1]) k++;
else {
ans.push(new int[] {k, k + minAt[k]});
k += minAt[k] + 1;
}
}
}
@SuppressWarnings("unchecked")
Solver() {
ranges = new ArrayList[2250001];
for (int i = 0; i < ranges.length; i++)
ranges[i] = new ArrayList<>();
}
int N, LID;
long[] a;
void solve(Scanner s, PrintWriter out) {
N = s.nextInt();
a = new long[N + 1];
for (int i = 1; i <= N; i++)
a[i] = s.nextLong() + a[i - 1];
for (int i = N; i >= 1; i--)
for (int j = i; j <= N; j++) {
int x = id(a[j] - a[i - 1]);
ranges[x].add(new int[] { i - 1, j - 1 });
}
int best = 0, bid = -1;
memo = new int[N + 1];
// Arrays.sort(ranges, (a, b) -> b.size() - a.size());
for(int i = 0; i < ranges.length; i++, LID++) {
if(ranges[i].size() <= best) continue;
int ans = go(i);
if(ans > best) {
best = ans;
bid = i;
}
}
// backtrack on bid
out.println(best);
go2(bid);
while(!ans.isEmpty()) {
int[] c = ans.pop();
out.println(++c[0] + " " + ++c[1]);
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver solver = new Solver();
solver.solve(s, out);
out.close();
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.PriorityQueue;
public class D_Rnd718_Explorer
{
static int row, col;
static int INF = 1_000_000_000;
static int[] dx = {0, 0, 1, -1};
static int[] dy = {1, -1, 0, 0};
public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String[] in = scan.readLine().split(" ");
row = parse(in[0]);
col = parse(in[1]);
int k = parse(in[2]);
int[][] xMove = new int[row][col-1];
for(int i = 0; i < row; i++)
{
in = scan.readLine().split(" ");
for(int j = 0; j < col - 1; j++)
xMove[i][j] = parse(in[j]);
}
int[][] yMove = new int[row - 1][col];
for(int i = 0; i < row - 1; i++)
{
in = scan.readLine().split(" ");
for(int j = 0; j < col; j++)
yMove[i][j] = parse(in[j]);
}
int[][] output = new int[row][col];
if(k % 2 != 0)
fill(-1, output);
else
{
Point[][] grid = new Point[row][col];
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
grid[i][j] = new Point(i, j);
parseMoves(grid, xMove, yMove);
solve(grid, k, output);
}
print(output, out);
out.flush();
}
private static void solve(Point[][] grid, int k, int[][] output)
{
// try bfs (hoping it passes the time constraint)
/*int target = k / 2;
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
output[i][j] = bfs(j, i, target, grid) << 1;*/
int target = k / 2;
int[][][] dist = new int[row][col][k/2];
fill(dist, grid);
for(int steps = 1; steps < target; steps++ )
{
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col;j ++)
{
dist[i][j][steps] = getDist(i, j, steps, dist, grid);
}
}
}
for(int i = 0; i < row; i++)
for(int j = 0; j < col;j ++)
output[i][j] = (dist[i][j][target - 1] << 1);
}
private static int getDist(int y, int x, int steps, int[][][] dist, Point[][] grid)
{
for(int d = 0; d < 4; d++)
{
int i = y + dy[d];
int j = x + dx[d];
if(valid(i, j))
{
dist[y][x][steps] = Math.min(dist[y][x][steps], dist[i][j][steps - 1] + grid[y][x].weight[d]);
}
}
return dist[y][x][steps];
}
private static void fill(int[][][] dist, Point[][] grid)
{
for(int i = 0; i < row; i++)
for(int j = 0; j < col;j ++)
for(int s = 0; s < dist[0][0].length; s++)
dist[i][j][s] = INF;
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
for(int d = 0; d < 4; d++)
dist[i][j][0] = Math.min(dist[i][j][0], grid[i][j].weight[d]);
}
private static boolean valid(int y, int x)
{
return y >= 0 && x >= 0 && y < row && x < col;
}
/*private static int bfs(int xStart, int yStart, int target, Point[][] grid)
{
PriorityQueue<Step> q = new PriorityQueue<Step>();
q.add(new Step(grid[yStart][xStart], 0, 0));
Step s;
int w;
while(!q.isEmpty())
{
s = q.poll();
if(s.numSteps == target)
return s.length;
// try to go in each of the four directions
for(int d = 0; d < 4; d++)
{
w = s.current.weight[d];
if(w != -1)
q.add(new Step(grid[s.current.y + s.current.dy[d]][s.current.x + s.current.dx[d]], s.length + w, s.numSteps + 1));
}
}
return -1;
}*/
private static void parseMoves(Point[][] grid, int[][] xMove, int[][] yMove)
{
for(int i = 0; i < xMove.length; i++)
{
for(int j = 0; j < xMove[i].length; j++)
{
grid[i][j].weight[2] = xMove[i][j]; // right
grid[i][j + 1].weight[3] = xMove[i][j]; // left
}
}
for(int i = 0; i < yMove.length; i++)
{
for(int j = 0; j < yMove[i].length; j++)
{
grid[i][j].weight[0] = yMove[i][j]; // down
grid[i + 1][j].weight[1] = yMove[i][j]; // up
}
}
}
private static void fill(int val, int[][] output)
{
for(int i = 0; i < output.length; i++)
Arrays.fill(output[i], val);
}
private static void print(int[][] ray, PrintWriter out)
{
for(int i = 0; i < ray.length; i++)
{
out.print(ray[i][0]);
for(int j = 1; j < ray[i].length; j++)
out.print(" " + ray[i][j]);
out.println();
}
}
public static int parse(String num)
{
return Integer.parseInt(num);
}
static class Point
{
int[] weight = new int[4]; // down, up, right, left
int x, y;
public Point(int i, int j)
{
y = i;
x = j;
Arrays.fill(weight, INF);
}
}
static class Step implements Comparable<Step>
{
int length, numSteps;
Point current;
public Step(Point p, int weight, int s)
{
current = p;
length = weight;
numSteps = s;
}
@Override
public int compareTo(Step s)
{
if(length == s.length) return numSteps - s.numSteps;
return length - s.length;
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Subtraction {
static long c=0;
public static void main(String[] args) throws IOException {
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(reader.readLine());
while (n-->0){
String l=reader.readLine();
String[] a=l.split(" ");
long A=Long.parseLong(a[0]);
long B=Long.parseLong(a[1]);
c=0;
gcd(A,B);
System.out.println(c);
}
}
private static void gcd(long a, long b) {
if (b==0)
return ;
c=c+a/b;
gcd(b,a%b);
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class TaskB {
static BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer str;
static String SK;
static String next() throws IOException {
while ((str == null) || (!str.hasMoreTokens())) {
SK = in.readLine();
if (SK == null)
return null;
str = new StringTokenizer(SK);
}
return str.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) throws IOException {
long n = nextLong();
int k = nextInt();
if (n == 1) {
System.out.println(0);
return;
}
long sum = (((2 + (long) k)) * ((long) k - 1)) / 2 - ((long) k - 2);
if (n > sum) {
System.out.println(-1);
return;
} else if (n <= k) {
System.out.println(1);
return;
}
long cnt = 0;
long sum2 = 0;
int index = binSearch(2, k, k, n);
sum2 = (((long) (index) + k) * (long) (k - index + 1)) / 2 - (long) (k - index);
cnt = k - index + 1;
if (sum2 == n) {
System.out.println(cnt);
return;
}
if (sum2 > n)
for (int kk = index; kk <= k; kk++) {
sum2 = (((long) (kk) + k) * (long) (k - kk + 1)) / 2 - (long) (k - kk);
cnt--;
if (sum2 <= n) {
System.out.println(cnt + 1);
return;
}
}
else {
for (int kk = index - 1; kk >= 2; kk--) {
sum2 = (((long) (kk) + k) * (long) (k - kk + 1)) / 2 - (long) (k - kk);
cnt++;
if (sum2 >= n) {
System.out.println(cnt);
return;
}
}
}
System.out.println(-1);
return;
}
static int binSearch(int l, int r, int k, long n) {
while (true) {
int mid = l + (r - l) / 2;
long sum2 = (((long) (mid) + k) * (long) (k - mid + 1)) / 2 - (long) (k - mid);
if (l >= r || sum2 == n) {
return mid;
} else if (sum2 > n) {
l = mid + 1;
} else if (sum2 < n) {
r = mid;
}
}
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
//package com.krakn.CF.B1159;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int min = 1000000000, temp;
for (int i = 0; i < n; i++) {
temp = arr[i] / Math.max(i, n - 1 - i);
if (temp < min)
min = temp;
// System.out.println(i + " " + temp);
}
System.out.println(min);
}
}
|
linear
|
1159_B. Expansion coefficient of the array
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main implements Runnable {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new Main(),"Main",1<<26).start();
}
static long gcd(long a,long b){ if(b==0)return a;return gcd(b,a%b); }
static long modPow(long a,long p,long m){ if(a==1)return 1;long ans=1;while (p>0){ if(p%2==1)ans=(ans*a)%m;a=(a*a)%m;p>>=1; }return ans; }
static long modInv(long a,long m){return modPow(a,m-2,m);}
static long sol_x,sol_y,gcd_a_b;
static void extendedEuclid(long a,long b){ if(b==0){gcd_a_b=a;sol_x=1;sol_y=0; } else{ extendedEuclid(b,a%b);long temp = sol_x;sol_x=sol_y;sol_y = temp - (a/b)*sol_y; } }
static class Bhavansort{ Random random;Bhavansort(int a[]){ randomArray(a); sort(a);}Bhavansort(long a[]){ randomArray(a); sort(a);}static int[] sort(int a[]){ Arrays.sort(a);return a;}static long[] sort(long a[]){ Arrays.sort(a);return a; }void randomArray(long a[]){ int n=a.length;for(int i=0;i<n;i++){ int p=random.nextInt(n)%n;long tm=a[i];a[i]=a[p];a[p]=tm; } }void randomArray(int a[]){ int n=a.length;for(int i=0;i<n;i++){ int p=random.nextInt(n)%n;int tm=a[i];a[i]=a[p];a[p]=tm; } }}
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt();
int m=sc.nextInt();
int a[][]=new int[n][m];
for (int i = 0; i <n ; i++) {
for (int j = 0; j <m ; j++) {
a[i][j]=sc.nextInt();
}
}
int cost[][]=new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <n ; j++) {
cost[i][j]=Integer.MAX_VALUE;
for (int k = 0; k <m ; k++) {
cost[i][j]=Math.min(cost[i][j],Math.abs(a[i][k]-a[j][k]));
}
}
}
int costRight[][]=new int[n][n];
for (int i = 0; i <n ; i++) {
for (int j = 0; j <n ; j++) {
costRight[i][j]=Integer.MAX_VALUE;
for (int k = 0; k <m-1 ; k++) {
costRight[i][j]=Math.min(Math.abs(a[i][k+1]-a[j][k]),costRight[i][j]);
}
}
}
/*for (int i = 0; i <n ; i++) {
for (int j = 0; j <n ; j++) {
out.print(cost[i][j]+" ");
}
out.println();
}
out.println();
for (int i = 0; i <n ; i++) {
for (int j = 0; j <n ; j++) {
out.print(costRight[i][j]+" ");
}
out.println();
}*/
if(n==1){
int ans=Integer.MAX_VALUE;
for (int i = 0; i <m-1 ; i++) {
ans=Math.min(ans,Math.abs(a[0][i]-a[0][i+1]));
}
out.println(ans);
out.close();
return;
}
Long dp[][][]=new Long[n+1][n+1][1<<n];
long max=0;
for (int i = 0; i <n ; i++) {
// out.println(f(i,i,1<<i,dp,n,cost,costRight));
max=Math.max(max,f(i,i,1<<i,dp,n,cost,costRight));
}
out.println(max);
out.close();
}
long f(int start,int end,int mask,Long dp[][][],int n,int cost[][],int costRight[][]){
if(dp[start][end][mask]!=null)return dp[start][end][mask];
long ans=Integer.MIN_VALUE;
for (int i = 0; i <n ; i++) {
if((mask&(1<<i))==0){
int newMask=mask|(1<<i);
if((1<<n)-1!=(mask|(1<<i))){
ans = Math.max(ans, Math.min(cost[end][i], f(start, i, newMask, dp, n, cost, costRight)));
}
else{
ans=Math.max(ans,Math.min(cost[end][i],costRight[start][i]));
}
}
}
return dp[start][end][mask]=ans;
}
}
|
np
|
1102_F. Elongated Matrix
|
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.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskG solver = new TaskG();
solver.solve(1, in, out);
out.close();
}
static class TaskG {
static final long MODULO = (long) 1e9 + 7;
static final long BIG = Long.MAX_VALUE - Long.MAX_VALUE % MODULO;
static final int[] ONE = new int[]{1};
int k;
int n;
long[] globalRes;
int[] p2;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
k = in.nextInt();
globalRes = new long[k + 1];
p2 = new int[n + 1];
p2[0] = 1;
for (int i = 1; i <= n; ++i) p2[i] = (int) (2 * p2[i - 1] % MODULO);
Vertex[] vs = new Vertex[n];
for (int i = 0; i < n; ++i) vs[i] = new Vertex();
for (int i = 0; i < n - 1; ++i) {
Vertex a = vs[in.nextInt() - 1];
Vertex b = vs[in.nextInt() - 1];
a.adj.add(b);
b.adj.add(a);
}
vs[0].dfs(null);
long[][] ways = new long[k + 1][k + 1];
ways[0][0] = 1;
for (int i = 1; i <= k; ++i) {
for (int j = 1; j <= k; ++j) {
ways[i][j] = j * (ways[i - 1][j] + ways[i - 1][j - 1]) % MODULO;
}
}
long sum = 0;
for (int i = 1; i <= k; ++i) {
long s = globalRes[i];
s %= MODULO;
sum = (sum + s * ways[k][i]) % MODULO;
}
out.println(sum);
}
class Vertex {
int[] res;
int subtreeSize;
List<Vertex> adj = new ArrayList<>();
public void dfs(Vertex parent) {
subtreeSize = 1;
int[] prod = ONE;
for (Vertex child : adj)
if (child != parent) {
child.dfs(this);
subtreeSize += child.subtreeSize;
}
int mult = 2;//p2[n - subtreeSize];
for (Vertex child : adj)
if (child != parent) {
int[] c = child.res;
prod = mul(prod, c);
subFrom(globalRes, c, 1);
}
addTo(globalRes, prod, mult);
res = insertEdge(prod);
}
private int[] insertEdge(int[] a) {
int len = a.length + 1;
if (len > k) len = k + 1;
int[] b = new int[len];
b[0] = a[0] * 2;
if (b[0] >= MODULO) b[0] -= MODULO;
for (int i = 1; i < len; ++i) {
long s = a[i - 1];
if (i < a.length) s += a[i];
if (s >= MODULO) s -= MODULO;
s = s * 2;
if (s >= MODULO) s -= MODULO;
b[i] = (int) s;
}
b[1] -= 1;
if (b[1] < 0) b[1] += MODULO;
return b;
}
private void addTo(long[] a, int[] b, int mult) {
for (int i = 0; i < b.length; ++i) {
long s = a[i] + b[i] * (long) mult;
if (s < 0) s -= BIG;
a[i] = s;
}
}
private void subFrom(long[] a, int[] b, int mult) {
for (int i = 0; i < b.length; ++i) {
long s = a[i] + (MODULO - b[i]) * (long) mult;
if (s < 0) s -= BIG;
a[i] = s;
}
}
private int[] mul(int[] a, int[] b) {
int len = a.length + b.length - 1;
if (len > k) len = k + 1;
int[] c = new int[len];
for (int i = 0; i < len; ++i) {
long s = 0;
int left = Math.max(0, i - (b.length - 1));
int right = Math.min(a.length - 1, i);
for (int ia = left; ia <= right; ++ia) {
int ib = i - ia;
s += a[ia] * (long) b[ib];
if (s < 0) s -= BIG;
}
c[i] = (int) (s % MODULO);
}
return c;
}
}
}
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
|
1097_G. Vladislav and a Great Legend
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
import static java.lang.Integer.*;
import static java.lang.Double.*;
import java.lang.Math.*;
public class A {
public static void main(String[] args) throws Exception {
new A().run();
}
public void run() throws Exception {
FastIO file = new FastIO();
int n = file.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = file.nextInt();
Arrays.sort(a);
boolean[] used = new boolean[n];
int count = 0;
for (int i = 0; i < n; i++) {
if (!used[i]) {
count++;
for (int j = i; j < n; j++) {
if (a[j] % a[i] == 0) {
used[j] = true;
}
}
}
}
System.out.println(count);
}
public static class FastIO {
BufferedReader br;
StringTokenizer st;
public FastIO() {
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 long pow(long n, long p, long mod) {
if (p == 0)
return 1;
if (p == 1)
return n % mod;
if (p % 2 == 0) {
long temp = pow(n, p / 2, mod);
return (temp * temp) % mod;
} else {
long temp = pow(n, (p - 1) / 2, mod);
temp = (temp * temp) % mod;
return (temp * n) % mod;
}
}
public static long pow(long n, long p) {
if (p == 0)
return 1;
if (p == 1)
return n;
if (p % 2 == 0) {
long temp = pow(n, p / 2);
return (temp * temp);
} else {
long temp = pow(n, (p - 1) / 2);
temp = (temp * temp);
return (temp * n);
}
}
public static long gcd(long x, long y) {
if (x == 0)
return y;
else
return gcd(y % x, x);
}
public static boolean isPrime(int n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
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();
}
static int INF = (int)1e5*4*4+5;
static int maxn = (int)1e5*2+1;
static int mod=(int)1e9+7 ;
static int n,m,k,t,q,x,a,b,y;
static ArrayList<Integer> adj[];
static int[] dist,parent,back;
static boolean[] vis,vist;
static int root=0,ans=1;
void solve(PrintWriter out, Reader in) throws IOException{
n = in.nextInt();
if(n==1) {out.println(1);return;}
adj = new ArrayList[n+1];
for(int i=1;i<=n;i++)
adj[i] = new ArrayList<Integer>();
int u,v;
for(int i=0;i<n-1;i++){
u = in.nextInt();
v = in.nextInt();
adj[u].add(v);
adj[v].add(u);
}
vist = new boolean[n+1];
vis = new boolean[n+1];
vist[1] =true;
makeroot(1);
parent = new int[n+1];
dist = new int[n+1];
back = new int[n+1];
dfs(root,0);
calcdist(root);
vist = new boolean[n+1];
vis = new boolean[n+1];
vist[root] =true;
PriorityQueue<Node> pq = new PriorityQueue<Node>();
for(int i=1;i<=n;i++){
if(i!=root) pq.add(new Node(i,dist[i]));
}
Node elm;
int rt = root;
out.print(1);
makeroot(root);
removeNodes(root,rt);
ans+=dist[rt];
out.print(" "+ans);
int itr=2;
for(int i=2;i<=n;i++){
elm = pq.remove();
if(vis[elm.idx]) continue;
removeNodes(back[elm.idx],elm.idx);
ans += elm.dist+1;
out.print(" "+ans);
itr++;
}
for(int i=itr;i<n;i++)
out.print(" "+ans);
out.println();
}
//<>
static class Node implements Comparable<Node>{
int dist,idx;
Node(int idx,int dist){
this.idx = idx;
this.dist = dist;
}
public int compareTo(Node o) {
return o.dist-this.dist;
}
}
static void removeNodes(int s,int e){
vis[s]=true;
while(s!=e){
vis[s] = true;
s = parent[s];
}
vis[s]=true;
return;
}
static int calcdist(int s){
int res=0;
int tmp=0;
for(int e:adj[s]){
if(e!=parent[s]){
tmp= calcdist(e);
if(1+tmp>res){
res = 1+tmp;
back[s] = back[e];
}
}
}
if(res==0) back[s]=s;
return dist[s] = res;
}
static void dfs(int s,int p){
for(int e:adj[s]){
if(e!=p){
parent[e]=s;
dfs(e,s);
}
}
return;
}
static void makeroot(int s){
Queue<Integer> q = new LinkedList<>();
q.add(s);
int elm=0;
while(q.size()!=0){
elm = q.remove();
for(int e:adj[elm]){
if(!vist[e]){
vist[e]=true;
q.add(e);
root = e;
}
}
}
return;
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
|
nlogn
|
958_B2. Maximum Control (medium)
|
CODEFORCES
|
import javax.print.DocFlavor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;
public class p1523C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t ; i++) {
int n = sc.nextInt();
ArrayList<Stack<Integer>> ar = new ArrayList<Stack<Integer>>();
for (int j = 0; j < n + 1; j++) {
ar.add(new Stack<Integer>());
}
HashMap <Integer , Integer> hm = new HashMap<Integer, Integer>();
StringBuilder cur = new StringBuilder();
int l = 0;
for (int j = 0; j < n; j++) {
int a = sc.nextInt();
if( a == 1)
{
if(cur.length() == 0)
cur.append("1");
else
cur.append(".1");
l++;
ar.get(1).add(l);
hm.put(l , 1);
}
else
{
int newl = ar.get( a - 1).pop();
for (int k = newl + 1; k <= l ; k++) {
ar.get(hm.get(k)).pop();
hm.remove(k);
cur.delete(cur.lastIndexOf(".") + 1, cur.length());
cur.delete(cur.length() - 1 , cur.length());
}
cur.delete(cur.lastIndexOf(".") + 1, cur.length());
cur.append(a);
ar.get(a).add(newl);
hm.put(newl , a);
l = newl;
}
System.out.println(cur);
}
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.Scanner;
//http://codeforces.com/contest/909/problem/C
public class PythInd {
public static final int MOD = 1000000007;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String[] sTypes = new String[n];
for (int i = 0; i < n; i++) {
sTypes[i] = sc.nextLine();
}
sc.close();
// dp[i][j] = number of ways to have a for loop indented
// j times at the ith position.
int[][] dp = new int[n][n];
dp[0][0] = 1;
for (int i = 0; i < dp.length - 1; i++) {
if (sTypes[i].equals("s")) {
int curSum = 0;
for (int j = i + 1; j >= 0; j--) {
curSum = (dp[i][j] + curSum) % MOD;
dp[i + 1][j] += curSum;
dp[i + 1][j] %= MOD;
}
} else {
for (int j = 1; j <= i + 1; j++) {
dp[i + 1][j] += dp[i][j - 1];
dp[i + 1][j] %= MOD;
}
}
}
int ans = 0;
for (int i = 0; i < dp[0].length; i++) {
ans = (ans + dp[n - 1][i]) % MOD;
}
System.out.println(ans);
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.util.*;
public class Rules {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
double maxSpeed = in.nextInt();
double len = in.nextInt();
double delayDist = in.nextInt();
double delaySpeed = in.nextInt();
// two cases: I reach the delayPoint at a speed higher than the delaySpeed, or I don't.
double timeToDelayAtMax = travelS(a, 0.0, maxSpeed, delayDist);
double timeToDelayAtDelay = travelS(a, 0.0, delaySpeed, delayDist);
if (Math.abs(timeToDelayAtMax-timeToDelayAtDelay) < 0.00001) {
// I can reach the delayPoint without being delayed
double time = travelS(a, 0.0, maxSpeed, len);
System.out.printf("%.9f\n", time);
return;
}
// binary search to find best velocity to stop acceleration in beginning
double lowV = delaySpeed;
double highV = maxSpeed;
int loopCount = 1000;
double[] initial = null;
double[] secondary = null;
while (loopCount-->0) {
double guessV = (lowV+highV)/2.0;
initial = travelA(a, 0.0, guessV);
secondary = travelA(a, guessV, Math.min(delaySpeed, maxSpeed));
if (initial[1] + secondary[1] < delayDist) { // okay, we can go faster
lowV = guessV;
} else {
highV = guessV;
}
}
double totalTime = 0.0;
double finalSpeed = 0.0;
initial = travelA(a, 0.0, lowV);
secondary = travelA(a, lowV, delaySpeed);
totalTime = initial[0] + secondary[0];
double totalDist = initial[1] + secondary[1];
totalTime += (delayDist-totalDist)/maxSpeed;
// now we have delayDist to go, and we are at delaySpeed
totalTime += travelS(a, delaySpeed, maxSpeed, len-delayDist);
System.out.printf("%.9f\n", totalTime);
}
// [0] = time in h, [1] = dist travelled, in km
// input units are in km/h^2, km/h, km/h
public static double[] travelA(int a, double startSpeed, double endSpeed) {
if (startSpeed > endSpeed)
a = -a;
double time = (endSpeed - startSpeed) / a;
double dist = 0.5*a*time*time + startSpeed*time;
return new double[] {time, dist};
}
// returns time it takes to travel dist, with given inputs
public static double travelS(int a, double startSpeed, double maxSpeed, double dist) {
double timeToMax = (maxSpeed - startSpeed) / a;
double targetTime = (-startSpeed + Math.sqrt(startSpeed*startSpeed + 2*a*dist)) / a;
if (targetTime < timeToMax)
return targetTime;
double partialDist = 0.5*timeToMax*timeToMax*a + startSpeed*timeToMax;
double remainingDist = dist - partialDist;
targetTime = remainingDist / maxSpeed;
return targetTime + timeToMax;
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
//package round25;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class A {
private Scanner in;
private PrintWriter out;
private String INPUT = "";
public void solve()
{
int n = ni();
int[] u = new int[n];
int fe = -1, fo = -1;
int ne = -1, no = -1;
for(int i = 0;i < n;i++){
u[i] = ni();
if(u[i] % 2 == 0){
if(fe == -1){
fe = i + 1;
}else{
ne = i + 1;
}
}else{
if(fo == -1){
fo = i + 1;
}else{
no = i + 1;
}
}
}
if(ne > 0){
out.println(fo);
}else{
out.println(fe);
}
}
public void run() throws Exception
{
in = INPUT.isEmpty() ? new Scanner(System.in) : new Scanner(INPUT);
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception
{
new A().run();
}
private int ni() { return Integer.parseInt(in.next()); }
private static void tr(Object... o) { System.out.println(o.length == 1 ? o[0] : Arrays.toString(o)); }
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class E16 {
static double[][] grid;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
grid = new double[n][n];
for(int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j = 0; j < n; j++) {
grid[i][j] = Double.parseDouble(st.nextToken());
}
}
boolean[] seen = new boolean[1<<n];
double[] prob = new double[1<<n];
prob[(1<<n)-1] = 1;
LinkedList<Integer> q = new LinkedList<Integer>();
q.add((1<<n)-1);
while(!q.isEmpty()) {
int curr = q.removeFirst();
if(Integer.bitCount(curr) == 1)
continue;
for(int i = 0; i < n; i++) {
if((curr & (1 << i)) == 0)
continue;
for(int j = i+1; j < n; j++) {
if((curr & (1<<j)) == 0)
continue;
prob[curr-(1<<i)] += prob[curr] * grid[j][i];
prob[curr-(1<<j)] += prob[curr] * grid[i][j];
if(!seen[curr-(1<<i)]) {
q.addLast(curr-(1<<i));
seen[curr-(1<<i)] = true;
}
if(!seen[curr-(1<<j)]) {
q.addLast(curr-(1<<j));
seen[curr-(1<<j)] = true;
}
}
}
prob[curr] = 0;
}
double sum = 0;
for(int i = 0; i < n; i++) {
sum += prob[1<<i];
}
for(int i = 0; i < n-1; i++) {
System.out.print(prob[1<<i]/sum + " ");
}
System.out.println(prob[1<<(n-1)]/sum);
}
}
|
np
|
16_E. Fish
|
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
*/
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 {
int mod = 1000000007;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt();
int[][] dp = new int[n + 1][5002];
char[] a = new char[n];
for (int i = 0; i < n; i++) a[i] = in.readCharacter();
for (int i = 0; i < dp[n].length; i++) dp[n][i] = 1;
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j < n; j++) {
if (a[i] == 's') {
if (j > 0) dp[i][j] = dp[i][j - 1];
dp[i][j] = (int) ((dp[i][j] + (long) dp[i + 1][j]) % mod);
} else {
if (j > 0) dp[i][j] = dp[i][j - 1];
dp[i][j] = (int) ((dp[i][j] + (long) dp[i + 1][j + 1] - (long) dp[i + 1][j] + mod) % mod);
}
}
}
out.println(dp[0][0]);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
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.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.io.BufferedReader;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
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;
InputStreamReader in = new InputStreamReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputStreamReader inSt, PrintWriter out) {
InputReader in = new InputReader(inSt);
long a = in.nextLong();
long b = in.nextLong();
long result = 0;
while (b != 1) {
result += a / b;
long r = a % b;
long q = b;
long top = q % r;
long bottom = r;
result += q / r;
a = top;
b = bottom;
}
result += a;
out.println(result);
}
class InputReader {
public BufferedReader reader;
private String[] currentArray;
int curPointer;
public InputReader(InputStreamReader inputStreamReader) {
reader = new BufferedReader(inputStreamReader);
}
public String next() {
try {
currentArray = null;
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void nextChars(char[] t) {
try {
currentArray = null;
reader.read(t);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public char nextChar() {
try {
currentArray = null;
return (char) reader.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
if ((currentArray == null) || (curPointer >= currentArray.length)) {
try {
currentArray = reader.readLine().split(" ");
} catch (IOException e) {
throw new RuntimeException(e);
}
curPointer = 0;
}
return Integer.parseInt(currentArray[curPointer++]);
}
public long nextLong() {
if ((currentArray == null) || (curPointer >= currentArray.length)) {
try {
currentArray = reader.readLine().split(" ");
} catch (IOException e) {
throw new RuntimeException(e);
}
curPointer = 0;
}
return Long.parseLong(currentArray[curPointer++]);
}
}
}
|
constant
|
343_A. Rational Resistance
|
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);
G1PlaylistForPolycarpEasyVersion solver = new G1PlaylistForPolycarpEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class G1PlaylistForPolycarpEasyVersion {
public static final int GENRES_COUNT = 3;
private int songsCount;
private int totalDuration;
private Song[] songs;
private int[][][] mem;
static final int mod = 1000000007;
public void solve(int testNumber, InputReader in, PrintWriter out) {
songsCount = in.nextInt();
totalDuration = in.nextInt();
songs = new Song[songsCount];
for (int i = 0; i < songsCount; i++) {
songs[i] = new Song(in.nextInt(), in.nextInt() - 1);
}
long ret = 0;
int chosenSongs = 0;
mem = new int[GENRES_COUNT + 1][][];
for (int i = 0; i < GENRES_COUNT; i++) {
mem[i] = new int[totalDuration + 1][];
for (int j = 0; j <= totalDuration; j++) {
mem[i][j] = new int[1 << songsCount];
for (int k = 0; k < 1 << songsCount; k++) {
mem[i][j][k] = -1;
}
}
}
for (int i = 0; i < songsCount; i++) {
chosenSongs = 1 << i;
ret += search(totalDuration - songs[i].duration, songs[i].genre, chosenSongs);
}
out.println(ret % mod);
}
private long search(int timeLeft, int lastGenre, int chosen) {
if (timeLeft < 0) {
return 0;
}
if (timeLeft == 0) {
return 1;
}
if (mem[lastGenre][timeLeft][chosen] != -1) {
return mem[lastGenre][timeLeft][chosen];
}
long ret = 0;
for (int i = 0; i < songsCount; i++) {
if (((1 << i) & chosen) == 0 && songs[i].genre != lastGenre) {
ret += search(timeLeft - songs[i].duration, songs[i].genre, chosen | 1 << i);
if (ret > mod) {
ret = ret % mod;
}
}
}
mem[lastGenre][timeLeft][chosen] = (int) (ret % mod);
return mem[lastGenre][timeLeft][chosen];
}
class Song {
public int duration;
public int genre;
public Song(int duration, int genre) {
this.duration = duration;
this.genre = genre;
}
}
}
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());
}
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
public class Main {
private static FastScanner sc = new FastScanner();
private static long mod = 1000000007;
public static void main(String[] args) {
int n = sc.nextInt();
int T = sc.nextInt();
int[] t = new int[n];
int[] g = new int[n];
for(int i=0; i<n; i++) {
t[i] = sc.nextInt();
g[i] = sc.nextInt() - 1;
}
long[][][] dp = new long[T+1][3][1 << 15];
for(int i=1; i<=T; i++) {
for(int j=0; j<n; j++) {
if(i - t[j] == 0) {
dp[i][g[j]][1 << j] = (dp[i][g[j]][1 << j] + 1) % mod;
} else if(i - t[j] > 0) {
for(int k=0; k<(1 << 15); k++) {
if((k >> j & 1) == 1) {
continue;
}
dp[i][g[j]][k + (1 << j)] = (dp[i][g[j]][k + (1 << j)] + dp[i - t[j]][(g[j] + 1) % 3][k] + dp[i - t[j]][(g[j] + 2) % 3][k]) % mod;
}
}
}
}
long ans = 0;
for(int j=0; j<3; j++) {
for(int k=0; k<(1 << 15); k++) {
ans = (ans + dp[T][j][k]) % mod;
}
}
System.out.println(ans);
}
static long power(long m , long n){
if(n == 0) {
return 1;
}else if(n == 1){
return m;
}else if(n % 2 == 0){
long s = power(m, n/2);
return ( (s % mod) * (s % mod) ) % mod;
}else{
return ( (m % mod) * (power(m, n-1) % mod) ) % mod;
}
}
static class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private boolean hasNextByte() {
if(ptr < buflen) {
return true;
} else {
ptr = 0;
try {
buflen = in.read(buffer);
} catch(IOException e) {
e.printStackTrace();
}
if(buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
private void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;}
public boolean hasNext() { skipUnprintable(); return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt(){
return Integer.parseInt(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
/**
* @author derrick20
*/
import java.io.*;
import java.util.*;
public class SameSumBlocks {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
int[] pre = new int[N + 1];
for (int i = 1; i <= N; i++) {
pre[i] = pre[i - 1] + sc.nextInt();
}
var sumMap = new HashMap<Integer, ArrayList<Pair>>();
for (int i = 1; i <= N; i++) {
for (int j = i; j <= N; j++) {
int sum = pre[j] - pre[i - 1];
sumMap.computeIfAbsent(sum, val -> new ArrayList<>()).add(new Pair(i, j));
}
}
var ans = new ArrayList<Pair>();
for (var list : sumMap.values()) {
Collections.sort(list, Comparator.comparingInt(p -> p.r));
// greedily schedule the intervals
int last = 0;
var group = new ArrayList<Pair>();
for (Pair p : list) {
if (p.l > last) {
group.add(p);
last = p.r;
}
}
if (group.size() > ans.size()) {
ans = group;
}
}
out.println(ans.size());
for (Pair p : ans) {
out.println(p);
}
out.close();
}
static class Pair {
int l, r;
public Pair(int ll, int rr) {
l = ll; r = rr;
}
public String toString() {
return l + " " + r;
}
}
static class FastScanner {
private int BS = 1<<16;
private char NC = (char)0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt=1;
boolean neg = false;
if(c==NC)c=getChar();
for(;(c<'0' || c>'9'); c = getChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=getChar()) {
res = (res<<3)+(res<<1)+c-'0';
cnt*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/cnt;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=getChar();
while(c>32) {
res.append(c);
c=getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=getChar();
while(c!='\n') {
res.append(c);
c=getChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=getChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {new Main().run();}
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
void run(){
int q=in.nextInt();
for(int i=0;i<q;i++) {
work();
}
out.flush();
}
long mod=1000000007;
long gcd(long a,long b) {
return a==0?b:b>a?gcd(b%a,a):gcd(b,a);
}
void work() {
long n=in.nextLong();
long k=in.nextLong();
if(k==0) {
out.println("YES"+" "+n);
}
long a=0,b=0,c=1,d=1;
while(--n>=0&&a<=k) {
b+=c;
c*=4;
a+=d;
d=d*2+1;
long t=count(c-d,n);
if(a<=k&&b>=k-t) {
out.println("YES"+ " "+n);
return;
}
}
out.println("NO");
}
private long count(long l, long n) {
if(n==0)return 0;
n--;
long ret=l;
for(int i=1;i<=n;i++) {
long t=ret;
ret*=4;
if(ret/4!=t)return Long.MAX_VALUE;
}
return ret;
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
if(st==null || !st.hasMoreElements())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
public class ChainReaction implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
private class Beacon implements Comparable<Beacon> {
private int position, range, score;
private Beacon(int position, int range) {
this.position = position;
this.range = range;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Beacon o) {
return Integer.compare(this.position, o.position);
}
}
public void solve() {
int n = in.ni();
if (n == 1) {
out.println(0);
return;
}
beacons = new ArrayList<>();
for (int i = 0; i < n; i++) {
beacons.add(new Beacon(in.ni(), in.ni()));
}
beacons.sort(Comparator.naturalOrder());
for (int i = 1; i < n; i++) {
int left = 0, right = i - 1, position = beacons.get(i).position, range = beacons.get(i).range;
int leftmost = i;
while (left <= right) {
int mid = left + (right - left) / 2;
if (position - range <= beacons.get(mid).position) {
leftmost = Math.min(leftmost, mid);
right = mid - 1;
} else {
left = mid + 1;
}
}
beacons.get(i).setScore(i - leftmost);
}
dp = new Integer[n];
int ans = Integer.MAX_VALUE;
for (int i = n - 1; i >= 0; i--) {
ans = Math.min(n - 1 - i + recurse(i), ans);
}
out.println(ans);
}
private List<Beacon> beacons;
private Integer[] dp;
private int recurse(int idx) {
if (idx <= 0) return 0;
if (dp[idx] != null) return dp[idx];
int destroyed = beacons.get(idx).score;
int ans = destroyed + recurse(idx - destroyed - 1);
return dp[idx] = ans;
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
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 ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (ChainReaction instance = new ChainReaction()) {
instance.solve();
}
}
}
|
nlogn
|
608_C. Chain Reaction
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Scanner;
public class kosyaDetka {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
ArrayList<Integer> arr = new ArrayList<>();
for(int i = 0; i < t; i++){
arr.add( scan.nextInt());
}
int count = 0;
while (arr.size() != 0){
int min = Integer.MAX_VALUE;
for(int i = 0; i < arr.size(); i++){
int temp = arr.get(i);
if( temp < min){
min = temp;
}
}
for(int i = 0; i < arr.size(); i++){
int temp = arr.get(i);
if( temp % min == 0){
arr.remove(i);
i--;
}
}
count++;
}
System.out.println(count);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.