src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.util.*;
import java.io.*;
public class Solution
{
public static void main(String [] args) throws IOException
{
PrintWriter pw=new PrintWriter(System.out);//use pw.println() not pw.write();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(br.readLine());
/*
inputCopy
5 3
xyabd
outputCopy
29
inputCopy
7 4
problem
outputCopy
34
inputCopy
2 2
ab
outputCopy
-1
inputCopy
12 1
abaabbaaabbb
outputCopy
1
*/
int n=Integer.parseInt(st.nextToken());
int k=Integer.parseInt(st.nextToken());
st=new StringTokenizer(br.readLine());
String str=st.nextToken();
char [] arr=str.toCharArray();
Arrays.sort(arr);
int weight=arr[0]-96;
char a=arr[0];
int included=1;
for(int i=1;i<arr.length;++i)
{
if(included==k)
break;
char c=arr[i];
if(c-a<2)
continue;
weight+=arr[i]-96;
++included;
a=arr[i];
}
if(included==k)
pw.println(weight);
else
pw.println(-1);
pw.close();//Do not forget to write it after every program return statement !!
}
}
/*
→Judgement Protocol
Test: #1, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
5 3
xyabd
Output
29
Answer
29
Checker Log
ok 1 number(s): "29"
Test: #2, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
7 4
problem
Output
34
Answer
34
Checker Log
ok 1 number(s): "34"
Test: #3, time: 139 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
2 2
ab
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #4, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
12 1
abaabbaaabbb
Output
1
Answer
1
Checker Log
ok 1 number(s): "1"
Test: #5, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 13
qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa
Output
169
Answer
169
Checker Log
ok 1 number(s): "169"
Test: #6, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 14
qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #7, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
1 1
a
Output
1
Answer
1
Checker Log
ok 1 number(s): "1"
Test: #8, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 1
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Output
1
Answer
1
Checker Log
ok 1 number(s): "1"
Test: #9, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 2
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #10, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
13 13
uwgmkyqeiaocs
Output
169
Answer
169
Checker Log
ok 1 number(s): "169"
Test: #11, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
13 13
hzdxpbfvrltnj
Output
182
Answer
182
Checker Log
ok 1 number(s): "182"
Test: #12, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
1 1
n
Output
14
Answer
14
Checker Log
ok 1 number(s): "14"
Test: #13, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
10 8
smzeblyjqw
Output
113
Answer
113
Checker Log
ok 1 number(s): "113"
Test: #14, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
20 20
tzmvhskkyugkuuxpvtbh
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #15, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
30 15
wjzolzzkfulwgioksfxmcxmnnjtoav
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #16, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
40 30
xumfrflllrrgswehqtsskefixhcxjrxbjmrpsshv
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #17, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 31
ahbyyoxltryqdmvenemaqnbakglgqolxnaifnqtoclnnqiabpz
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #18, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
10 7
iuiukrxcml
Output
99
Answer
99
Checker Log
ok 1 number(s): "99"
Test: #19, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
38 2
vjzarfykmrsrvwbwfwldsulhxtykmjbnwmdufa
Output
5
Answer
5
Checker Log
ok 1 number(s): "5"
Test: #20, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
12 6
fwseyrarkwcd
Output
61
Answer
61
Checker Log
ok 1 number(s): "61"
Test: #21, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
2 2
ac
Output
4
Answer
4
Checker Log
ok 1 number(s): "4"
Test: #22, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
1 1
c
Output
3
Answer
3
Checker Log
ok 1 number(s): "3"
Test: #23, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
2 2
ad
Output
5
Answer
5
Checker Log
ok 1 number(s): "5"
Test: #24, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER
Input
2 1
ac
Output
-1
Answer
1
Checker Log
wrong answer 1st number
*/
|
linear
|
1011_A. Stages
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class con111_A {
public static void main( final String[] args ) throws IOException {
final BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
final int n = Integer.parseInt( br.readLine() );
final int[] a = new int[n];
final String[] parts = br.readLine().split( " " );
for ( int i = 0; i < n; ++i ) {
a[ i ] = Integer.parseInt( parts[ i ] );
}
System.out.println( solve( n, a ) );
}
private static int solve( final int n, final int[] a ) {
Arrays.sort( a );
int sum = 0;
for ( int i = 0; i < n; ++i ) {
sum += a[ i ];
}
int res = 0;
int ms = 0;
for ( int i = n - 1; i >= 0; --i ) {
if ( ms > sum / 2 ) {
break;
} else {
ms += a[ i ];
++res;
}
}
return res;
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
public class Mainm {
static int mod1 = (int) (1e9 + 7);
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
Scanner scan = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws IOException {
String str00 = scan.next();
return str00;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() throws IOException {
int c;
for (c = read(); c <= 32; c = read());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = read()) {
sb.append((char) c);
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
public int[] nextArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
}
static int GCD(int a, int b)
{
if (b == 0)
return a;
return GCD(b, a % b);
}
static long power(long x, long y, long p)
{
int res = 1; // Initialize result
return res;
}
static boolean primeCheck(long num0) {
boolean b1 = true;
if (num0 == 1) {
b1 = false;
} else {
int num01 = (int) (Math.sqrt(num0)) + 1;
me1:
for (int i = 2; i < num01; i++) {
if (num0 % i == 0) {
b1 = false;
break me1;
}
}
}
return b1;
}
public static int dev(long num1)
{
int count00=0;
while (num1%2==0)
{
count00++;
num1/=2;
}
HashMap<Long,Long> hashMap=new HashMap<>();
if(count00!=0)
{
hashMap.put(2L,(long)count00);
}
for (int i = 3; i <= (int)Math.sqrt(num1); i = i + 2)
{
// While i divides n, print i and divide n
if(num1%i==0) {
int count01 = 0;
while (num1 % i == 0) {
num1 /= i;
count01++;
}
hashMap.put((long)i,(long)count01);
}
}
if(num1>2)
{
hashMap.put((long)num1,1L);
}
long numOfDiv=1;
for(long num00:hashMap.keySet())
{
long cDiv0=hashMap.get(num00);
numOfDiv*=(cDiv0+1);
}
return (int)(numOfDiv);
}
public static long solve(long[] arr1, long N)
{
int n=(int)N;
HashMap<Long,Integer> hm=new HashMap<>();
for(int i=0;i<n;i++)
{
if(hm.containsKey(arr1[i]))
{
}
else
{
hm.put(arr1[i],1);
}
}
long count1=0;
for(int i=0;i<n;i++)
{
long num1=arr1[i]*arr1[i];
if(hm.containsKey(num1))
{
count1+=hm.get(num1);
if(arr1[i]==1)
{
count1--;
}
}
}
return count1;
}
public static void main(String[] args) throws IOException {
Reader r = new Reader();
//PrintWriter writer=new PrintWriter(System.out);
//Scanner r = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
//Scanner r=new Scanner(System.in);
OutputWriter770 out77 = new OutputWriter770(System.out);
int num1=r.nextInt();
int[] arr1=r.nextArray(num1);
Arrays.sort(arr1);
int res1=0;
for(int i=0;i<num1;i++)
{
if(arr1[i]!=-1)
{
res1++;
int num2=arr1[i];
arr1[i]=-1;
for(int j=i+1;j<num1;j++)
{
if(arr1[j]%num2==0)
{
arr1[j]=-1;
}
}
}
}
out77.print(res1+"");
r.close();
out77.close();
}
}
class OutputWriter770
{
BufferedWriter writer;
public OutputWriter770(OutputStream stream)
{
writer = new BufferedWriter(new OutputStreamWriter(stream));
}
public void print(int i) throws IOException
{
writer.write(i + "");
}
public void println(int i) throws IOException
{
writer.write(i + "\n");
}
public void print(String s) throws IOException
{
writer.write(s + "");
}
public void println(String s) throws IOException
{
writer.write(s + "\n");
}
public void print(char[] c) throws IOException
{
writer.write(c);
}
public void close() throws IOException
{
writer.flush();
writer.close();
}
}
class node
{
int source,dest;
long difDist;
node(int source,int dest,long tDst, long hDst)
{
this.source=source;
this.dest=dest;
this.difDist=hDst-tDst;
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.Scanner;
public class test5{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
long x=in.nextLong();
if(x>=3){
if(x%2!=0)
System.out.println(x*(x-1)*(x-2));
else if(x%3==0)
System.out.println((x-3)*(x-1)*(x-2));
else
System.out.println(x*(x-1)*(x-3));
}
else System.out.println(x);
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author @zhendeaini6001
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] input = IOUtils.readIntArray(in, n);
Arrays.sort(input);
int x = input[b-1];
int y = input[b];
out.println(y - x);
}
}
class IOUtils {
public static int[] readIntArray(Scanner in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.nextInt();
return array;
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Egor Kulikov (egor@egork.net)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int[] array = IOUtils.readIntArray(in, count);
int[] sorted = array.clone();
ArrayUtils.sort(sorted, IntComparator.DEFAULT);
int differs = 0;
for (int i = 0; i < count; i++) {
if (array[i] != sorted[i])
differs++;
}
if (differs <= 2)
out.printLine("YES");
else
out.printLine("NO");
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
class ArrayUtils {
private static int[] tempInt = new int[0];
public static int[] sort(int[] array, IntComparator comparator) {
return sort(array, 0, array.length, comparator);
}
public static int[] sort(int[] array, int from, int to, IntComparator comparator) {
ensureCapacityInt(to - from);
System.arraycopy(array, from, tempInt, 0, to - from);
sortImpl(array, from, to, tempInt, 0, to - from, comparator);
return array;
}
private static void ensureCapacityInt(int size) {
if (tempInt.length >= size)
return;
size = Math.max(size, tempInt.length << 1);
tempInt = new int[size];
}
private static void sortImpl(int[] array, int from, int to, int[] temp, int fromTemp, int toTemp, IntComparator comparator) {
if (to - from <= 1)
return;
int middle = (to - from) >> 1;
int tempMiddle = fromTemp + middle;
sortImpl(temp, fromTemp, tempMiddle, array, from, from + middle, comparator);
sortImpl(temp, tempMiddle, toTemp, array, from + middle, to, comparator);
int index = from;
int index1 = fromTemp;
int index2 = tempMiddle;
while (index1 < tempMiddle && index2 < toTemp) {
if (comparator.compare(temp[index1], temp[index2]) <= 0)
array[index++] = temp[index1++];
else
array[index++] = temp[index2++];
}
if (index1 != tempMiddle)
System.arraycopy(temp, index1, array, index, tempMiddle - index1);
if (index2 != toTemp)
System.arraycopy(temp, index2, array, index, toTemp - index2);
}
}
interface IntComparator {
public static final IntComparator DEFAULT = new IntComparator() {
public int compare(int first, int second) {
if (first < second)
return -1;
if (first > second)
return 1;
return 0;
}
};
public int compare(int first, int second);
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
while(n-->0){
long a=sc.nextLong(),b=sc.nextLong();
long ans=0,cur=0;
while(a>0 && b>0){
if(b>a)a=a+b-(b=a);
cur=(a/b);
ans+=cur;
a-=(cur*b);
}
System.out.println(ans);
}
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.awt.Point;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String dimensions = br.readLine();
String extractDim = "";
int n = 0, m;
for (int i = 0 ; i < dimensions.length() ; i++)
{
if(dimensions.charAt(i) == ' ')
{
n = Integer.parseInt(extractDim);
extractDim = "";
continue;
}
extractDim += dimensions.charAt(i);
}
m = Integer.parseInt(extractDim);
String burningTrees = br.readLine();
int k = Integer.parseInt(burningTrees);
Point[] coord = new Point[k];
String coordSet = br.readLine();
int spaceCount = 0;
String newCoord = "";
int s = 0;
for(int i = 0 ; i < coordSet.length() ; i++)
{
if(coordSet.charAt(i) == ' ')
spaceCount++;
if(spaceCount == 2)
{
String extractCoord = "";
int x = 0, y;
for (int j = 0 ; j < newCoord.length() ; j++)
{
if(newCoord.charAt(j) == ' ')
{
x = Integer.parseInt(extractCoord);
extractCoord = "";
continue;
}
extractCoord += newCoord.charAt(j);
}
y = Integer.parseInt(extractCoord);
coord[s] = new Point(x,y);
s++;
newCoord = "";
spaceCount = 0;
continue;
}
newCoord += coordSet.charAt(i);
}
String extractCoord = "";
int x = 0, y;
for (int j = 0 ; j < newCoord.length() ; j++)
{
if(newCoord.charAt(j) == ' ')
{
x = Integer.parseInt(extractCoord);
extractCoord = "";
continue;
}
extractCoord += newCoord.charAt(j);
}
y = Integer.parseInt(extractCoord);
coord[s] = new Point(x,y);
s++;
br.close();
int[][] forest = new int[n+2][m+2];
for(int i = 0 ; i < forest.length ; i++)
{
for(int j = 0 ; j < forest[i].length ; j++)
{
if(i == 0 || i == n+1 || j == 0 || j == m+1 )
forest[i][j] = 0;
else
forest[i][j] = 1;
}
}
Queue<Point> q = new LinkedList<>();
for(int i = 0 ; i < coord.length ; i++)
{
forest[coord[i].x][coord[i].y] = 0;
q.add(coord[i]);
}
Point tree = new Point();
while(!q.isEmpty())
{
Point temp = q.remove();
forest[temp.x][temp.y] = 0;
if(q.isEmpty())
tree = new Point(temp.x ,temp.y);
for(int i = -1 ; i <= 1 ; i++)
{
for(int j = -1; j <= 1; j++)
{
if(i != 0 && j != 0 || i == 0 && j == 0)
continue;
if(forest[temp.x+i][temp.y+j] == 0)
continue;
else
{
forest[temp.x+i][temp.y+j] = 0;
q.add(new Point(temp.x+i , temp.y+j));
}
}
}
}
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
bw.write(tree.x + " " + tree.y);
bw.close();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
/**
* Created by IntelliJ IDEA.
* User: shakhov
* Date: 15.06.2011
* Time: 15:22:46
* 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.*;
public class CodeForces {
public void solve() throws IOException {
String s = nextToken();
Set<String> set = new HashSet<String>();
int counter = 0;
for (int i = 0, l = s.length(); i < l; i++) {
for (int j = i + 1; j < l; j++) {
String subst = s.substring(i, j);
if (!set.contains(subst)) {
set.add(subst);
if (counts(s.toCharArray(), subst.toCharArray()) > 1) {
counter = Math.max(counter, subst.length());
}
}
}
}
writer.print(counter);
}
private int counts(char[] s, char[] r) {
int l = s.length;
int rl = r.length;
int arr[] = new int[26];
Arrays.fill(arr, rl);
for (int i = rl - 2; i > -1; i--) {
int margin = (r[i] - 'a');
if (arr[margin] == rl) {
arr[margin] = rl - i - 1;
}
}
//search
int sp = 0;
int counter = 0;
while (sp <= l - rl) {
int oldsp = sp;
for (int i = rl - 1; i > -1; i--) {
if (r[i] != s[sp + i]) {
if (i == rl - 1) {
sp += arr[s[sp + i] - 'a'];
} else {
sp++;
}
break;
}
}
if (oldsp == sp) {
counter++;
sp++;
}
}
return counter;
}
public static void main(String[] args) {
new CodeForces().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
//reader = new BufferedReader(new FileReader("LifeWithoutZeros.in"));
tokenizer = null;
writer = new PrintWriter(System.out);
//writer = new PrintWriter(new BufferedWriter(new FileWriter("LifeWithoutZeros.out")));
//long t=new Date().getTime();
solve();
//writer.println(t-new Date().getTime());
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();
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.awt.Checkbox;
import java.awt.Point;
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.Map.Entry;
import javax.print.attribute.SetOfIntegerSyntax;
import javax.swing.plaf.FontUIResource;
public class CODE2{
private static InputStream stream;
private static byte[] buf = new byte[1024];
private static int curChar,MAX;
private static int numChars;
private static SpaceCharFilter filter;
private static PrintWriter pw;
private static long count = 0,mod=1000000007;
static int BIT[];
private static boolean primer[];
// private static TreeSet<Integer> ts=new TreeSet[200000];
public final static int INF = (int) 1E9;
public static void main(String args[]) {
InputReader(System.in);
pw = new PrintWriter(System.out);
new Thread(null ,new Runnable(){
public void run(){
try{
solve();
pw.close();
} catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<26).start();
}
static StringBuilder sb;
public static void test(){
sb=new StringBuilder();
int t=nextInt();
while(t-->0){
solve();
}
pw.println(sb);
}
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/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/2);
temp=(temp*temp);
return(temp*n);
}
}
public static void Merge(long a[],int p,int r){
if(p<r){
int q = (p+r)/2;
Merge(a,p,q);
Merge(a,q+1,r);
Merge_Array(a,p,q,r);
}
}
public static void Merge_Array(long a[],int p,int q,int r){
long b[] = new long[q-p+1];
long c[] = new long[r-q];
for(int i=0;i<b.length;i++)
b[i] = a[p+i];
for(int i=0;i<c.length;i++)
c[i] = a[q+i+1];
int i = 0,j = 0;
for(int k=p;k<=r;k++){
if(i==b.length){
a[k] = c[j];
j++;
}
else if(j==c.length){
a[k] = b[i];
i++;
}
else if(b[i]<c[j]){
a[k] = b[i];
i++;
}
else{
a[k] = c[j];
j++;
}
}
}
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;
}
static LinkedList<Integer> adj[];
static boolean Visited[];
static HashSet<Integer> exc;
static long oddsum[]=new long[1000001];
static long co=0,ans=0;
static int parent[];
static int size[],color[],res[],k;
static ArrayList<Integer> al[];
static long MOD = (long)1e9 + 7;
private static void buildgraph(int n){
adj=new LinkedList[n+1];
Visited=new boolean[n+1];
levl=new int[n+1];
for(int i=0;i<=n;i++){
adj[i]=new LinkedList<Integer>();
}
}
static int[] levl;
static int[] eat;
// static int n,m;
static int price[];
//ind frog crab
static boolean check(char c)
{
if(c!='a' && c!='e' && c!='i' && c!='o' && c!='u' )
return true;
else
return false;
}
public static void solve(){
int n= nextInt();
int a[]=new int[n];
a=nextIntArray(n);
int invcount=0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]>a[j])
invcount++;
}
}
int m=nextInt();
int initial = invcount%2;
while(m--!=0)
{
int l=nextInt();
int r=nextInt();
int diff = r-l+1;
int totalpair = (diff*(diff-1))/2;
if(((totalpair%2)+initial)%2==1)
{
pw.println("odd");
initial=1;
}
else
{
pw.println("even");
initial=0;
}
}
}
static void seive2(int n)
{
primer=new boolean[n+1];
Arrays.fill(primer,true);
primer[0]=false;
primer[1]=false;
primer[2]=true;
for(int i=2;i*i<=n;i++)
{
if(primer[i])
{
for(int j=2*i;j<=n;j=j+i)
{
primer[j]=false;
}
}
}
}
/* static void BITupdate(int x,int val)
{
while(x<=n)
{
BIT[x]+=val;
x+= x & -x;
}
}*/
/* static void update(int x,long val)
{
val=val%MOD;
while(x<=n)
{
// System.out.println(x);
BIT[x]=(BIT[x]+val)%MOD;
x+=(x & -x);
}
// System.out.println("dfd");
}*/
static int BITsum(int x)
{
int sum=0;
while(x>0)
{
sum+=BIT[x];
x-= (x & -x);
}
return sum;
}
/* static long sum(int x)
{
long sum=0;
while(x>0)
{
sum=(sum+BIT[x])%MOD;
x-=x & -x;
}
return sum;
}*/
static boolean union(int x,int y)
{
int xr=find(x);
int yr=find(y);
if(xr==yr)
return false;
if(size[xr]<size[yr])
{
size[yr]+=size[xr];
parent[xr]=yr;
}
else
{
size[xr]+=size[yr];
parent[yr]=xr;
}
return true;
}
static int find(int x)
{
if(parent[x]==x)
return x;
else
{
parent[x]=find(parent[x]);
return parent[x];
}
}
public static class Edge implements Comparable<Edge>
{
int u, v,s;
public Edge(int u, int v)
{
this.u = u;
this.v = v;
//this.s = s;
}
public int hashCode()
{
return Objects.hash();
}
public int compareTo(Edge other)
{
return (Integer.compare(u, other.u) != 0 ? (Integer.compare(u, other.u)):(Integer.compare(v, other.v)));
// &((Long.compare(s, other.s) != 0 ? (Long.compare(s, other.s)):(Long.compare(u, other.v)!=0?Long.compare(u, other.v):Long.compare(v, other.u))));
//return this.u-other.u;
}
public String toString()
{
return this.u + " " + this.v;
}
}
static int col[];
public static boolean isVowel(char c){
if(c=='a' || c=='e'||c=='i' || c=='o' || c=='u')
return true;
return false;
}
static int no_vert=0;
private static void dfs(int start){
Visited[start]=true;
if(al[color[start]].size()>=k)
{
res[start]=al[color[start]].get(al[color[start]].size()-k);
}
al[color[start]].add(start);
for(int i:adj[start]){
if(!Visited[i])
{
dfs(i);
}
}
(al[color[start]]).remove(al[color[start]].size()-1);
}
public static String reverseString(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return (sb.toString());
}
/*
private static void BFS(int sou){
Queue<Integer> q=new LinkedList<Integer>();
q.add(sou);
Visited[sou]=true;
levl[sou]=0;
while(!q.isEmpty()){
int top=q.poll();
for(int i:adj[top]){
//pw.println(i+" "+top);
if(!Visited[i])
{
q.add(i);
levl[i]=levl[top]+1;
}
Visited[i]=true;
}
}
}*/
static int indeg[];
/* private static void kahn(int n){
PriorityQueue<Integer> q=new PriorityQueue<Integer>();
for(int i=1;i<=n;i++){
if(indeg[i]==0){
q.add(i);
}
}
while(!q.isEmpty()){
int top=q.poll();
st.push(top);
for(Node i:adj[top]){
indeg[i.to]--;
if(indeg[i.to]==0){
q.add(i.to);
}
}
}
}
static int state=1;
static long no_exc=0,no_vert=0;
static Stack<Integer> st;
static HashSet<Integer> inset;
/* private static void topo(int curr){
Visited[curr]=true;
inset.add(curr);
for(int x:adj[curr]){
if(adj[x].contains(curr) || inset.contains(x)){
state=0;
return;
}
if(state==0)
return;
}
st.push(curr);
inset.remove(curr);
}*/
static HashSet<Integer> hs;
static boolean prime[];
static int spf[];
public static void sieve(int n){
prime=new boolean[n+1];
spf=new int[n+1];
Arrays.fill(spf, 1);
Arrays.fill(prime, true);
prime[1]=false;
spf[2]=2;
for(int i=4;i<=n;i+=2){
spf[i]=2;
}
for(int i=3;i<=n;i+=2){
if(prime[i]){
spf[i]=i;
for(int j=2*i;j<=n;j+=i){
prime[j]=false;
if(spf[j]==1){
spf[j]=i;
}
}
}
}
}
// To Get Input
// Some Buffer Methods
public static void sort(long a[]){
Merge(a, 0, a.length-1);
}
public static void InputReader(InputStream stream1) {
stream = stream1;
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private static boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private static int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
private static int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private static String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
private static int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
private static long[][] next2dArray(int n, int m) {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = nextLong();
}
}
return arr;
}
private static char[][] nextCharArray(int n,int m){
char [][]c=new char[n][m];
for(int i=0;i<n;i++){
String s=nextLine();
for(int j=0;j<s.length();j++){
c[i][j]=s.charAt(j);
}
}
return c;
}
private static long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private static void pArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
return;
}
private static void pArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
return;
}
private static void pArray(boolean[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
return;
}
private static boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Elektronnietablici {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer in;
static PrintWriter out = new PrintWriter(System.out);
public static String nextToken() throws IOException{
while (in == null || !in.hasMoreTokens()){
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public static int nextInt() throws IOException{
return Integer.parseInt(nextToken());
}
public static double nextDouble() throws IOException{
return Double.parseDouble(nextToken());
}
public static void main(String[] args) throws IOException{
int n = nextInt();
String S;
for (int i = 0; i < n; i++) {
S = nextToken();
int f = 0;
if (S.charAt(0) == 'R' && S.charAt(1) >= '1' && S.charAt(1) <= '9'){
for (int j = 2; j < S.length(); j++) {
if (S.charAt(j) >= 'A' && S.charAt(j) <= 'Z'){
f = 1;
break;
}
}
}
if (f == 0){
String T1 = "";
String ans = "R";
int j;
for (j = 0; S.charAt(j) >= 'A' && S.charAt(j) <= 'Z'; j++) {
T1 += S.charAt(j);
}
ans += S.substring(j, S.length()) + "C";
int len = j;
j--;
int p = 1;
int z = 0;
for (; j >= 0; j--) {
z += (S.charAt(j) - 'A') * p;
p *= 26;
}
p = 1;
for (int k = 0; k < len; k++) {
z += p;
p *= 26;
}
ans += z;
out.println(ans);
}
else{
String T1 = "";
String ans = "";
int j;
for (j = 1; S.charAt(j) != 'C'; j++) {
ans += S.charAt(j);
}
T1 = S.substring(j + 1, S.length());
int z = Integer.parseInt(T1);
int p = 1;
int len = 0;
while (p <= z){
z -= p;
p *= 26;
len++;
}
p /= 26;
T1 = "";
for (int k = len - 1; k >= 0; k--) {
int l = z / p;
T1 += (char)(z / p + 'A');
z -= l * p;
p /= 26;
}
ans = T1 + ans;
out.println(ans);
}
}
//2
//R23C55
//BC23
out.close();
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class cfedu46a{
public static void main(String [] args) throws IOException{
InputReader in = new InputReader("cfedu46a.in");
int [] arr = new int[9];
int [] arr2 = new int[9];
int [] size = {4, 3, 2, 1, 1, 1, 2, 3, 4};
int n = in.nextInt();
for(int i = 0; i < n; i++){
String s = in.next();
switch(s.length()){
case 1:
if(s.charAt(0) == 'S')
arr[3]++;
if(s.charAt(0) == 'M')
arr[4]++;
if(s.charAt(0) == 'L')
arr[5]++;
break;
default:
if(s.charAt(s.length() - 1) == 'S'){
arr[3 - (s.length() - 1)]++;
}
if(s.charAt(s.length() - 1) == 'L'){
arr[5 + (s.length() - 1)]++;
}
}
}
for(int i = 0; i < n; i++){
String s = in.next();
switch(s.length()){
case 1:
if(s.charAt(0) == 'S')
arr2[3]++;
if(s.charAt(0) == 'M')
arr2[4]++;
if(s.charAt(0) == 'L')
arr2[5]++;
break;
default:
if(s.charAt(s.length() - 1) == 'S'){
arr2[3 - (s.length() - 1)]++;
}
if(s.charAt(s.length() - 1) == 'L'){
arr2[5 + (s.length() - 1)]++;
}
}
}
int cnt = 0;
for(int i = 0; i < 9; i++){
if(arr[i] == arr2[i])
continue;
else{
cnt += (arr2[i] - arr[i] > 0? arr2[i] - arr[i]: 0);
}
}
System.out.println(cnt);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(String s) {
try{
reader = new BufferedReader(new FileReader(s), 32768);
}
catch (Exception e){
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());
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.*;
import java.util.StringTokenizer;
public class Main {
BufferedReader br;
PrintWriter pw;
StringTokenizer st;
long mod = (long) (1e9 + 7);
public static void main(String[] args) {
(new Main()).run();
}
void solve() throws IOException {
int n = nextInt();
boolean p[] = new boolean[n];
for (int i = 0; i < n; i++) {
String s = nextToken();
if (s.charAt(0) == 'f') p[i] = true;
}
long d[][] = new long[n][n];
d[0][0] = 1;
for (int i = 1; i < n; i++) {
if (p[i - 1]) {
d[i][0] = 0;
for (int j = 1; j < n; j++) {
d[i][j] = d[i - 1][j - 1];
}
} else {
long sum = 0;
for (int j = n - 1; j >= 0; j--) {
sum += d[i - 1][j];
sum %= mod;
d[i][j] = sum;
}
}
}
long sum = 0;
for (int i = 0; i < n; i++) {
sum += d[n - 1][i];
sum %= mod;
}
pw.print(sum);
}
void run() {
try {
// br = new BufferedReader(new FileReader("divljak.in"));
// pw = new PrintWriter(new BufferedWriter(new FileWriter("divljak.out")));
// br = new BufferedReader(new FileReader("input.txt"));
// pw = new PrintWriter(new FileWriter("output.txt"));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
solve();
pw.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
class h {
int ans;
int last;
public h() {
last = -1;
ans = 0;
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
public class Main {
public static BufferedReader in;
public static PrintWriter out;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
boolean showLineError = true;
if (showLineError) {
solve();
out.close();
} else {
try {
solve();
} catch (Exception e) {
} finally {
out.close();
}
}
}
static void debug(Object... os) {
out.println(Arrays.deepToString(os));
}
private static void solve() throws IOException {
String[] line = nss();
int n = Integer.parseInt(line[0]);
int m = Integer.parseInt(line[1]);
boolean[][] matrix = new boolean[n][n];
for (int i = 0; i < m; i++) {
line = nss();
int u = Integer.parseInt(line[0]) - 1;
int v = Integer.parseInt(line[1]) - 1;
matrix[u][v] = matrix[v][u] = true;
}
long[][] dp = new long[1<<n][n];
for(int i=0;i<n;i++)
dp[1<<i][i]=1;
long ret=0;
for(int mask =0;mask< 1<<n;mask++){
for(int last =0;last<n;last++)
if((mask & (1<<last))!=0){
int first=-1;
for(first=0;first<n;first++)
if((mask & (1<<first))!=0)
break;
for(int add =first;add<n;add++)
if((mask & (1<<add))==0 && matrix[last][add])
dp[mask+ (1<<add)][add]+=dp[mask][last];
if(Long.bitCount(mask)>2 && matrix[first][last])
ret+=dp[mask][last];
}
}
out.println(ret/2L);
}
private static String[] nss() throws IOException {
return in.readLine().split(" ");
}
private static int ni() throws NumberFormatException, IOException {
return Integer.parseInt(in.readLine());
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.Optional;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Main main = new Main();
main.solveC();
}
private void solveA() {
Scanner sc = new Scanner(System.in);
String first = sc.next();
String last = sc.next();
String answer = first.substring(0, 1) + last.substring(0, 1);
for (int i = 2; i <= first.length(); i++) {
String current = first.substring(0, i) + last.substring(0, 1);
if (answer.compareTo(current) > 0) {
answer = current;
}
}
System.out.println(answer);
}
private void solveB() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int layer = 0;
for (int i = 1; i <= N; i++) {
int max = N - i + 1;
layer += i < max ? i : max;
}
System.out.println(layer);
}
private void solveC() {
Scanner sc = new Scanner(System.in);
final long MOD_NUM = 1000000007L;
int N = sc.nextInt();
long[] level = new long[N + 2];
level[0] = 1;
sc.nextLine();
String pre = "s";
for (int i = 0; i < N; i++) {
String line = sc.nextLine();
long[] next_level = new long[N + 2];
if (pre.equals("f")) {
for (int j = 1; j < N + 1; j++) {
next_level[j] = level[j - 1];
}
}
if (pre.equals("s")) {
for (int j = N; j >= 0; j--) {
next_level[j] = (next_level[j + 1] + level[j]) % MOD_NUM;
}
}
pre = line;
level = next_level;
}
long answer = 0L;
for (int i = 0; i < N + 1; i++) {
answer = (answer + level[i]) % MOD_NUM;
}
System.out.println(answer);
}
private void solveD() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
System.out.println(N);
}
private void solveE() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
System.out.println(N);
}
private void solveF() {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
System.out.println(N);
}
interface Graph {
void link(int from, int to, long cost);
Optional<Long> getCost(int from, int to);
int getVertexNum();
}
interface FlowResolver {
long maxFlow(int from, int to);
}
/**
* グラフの行列による実装
* 接点数の大きいグラフで使うとMLEで死にそう
*/
class ArrayGraph implements Graph {
private Long[][] costArray;
private int vertexNum;
public ArrayGraph(int n) {
costArray = new Long[n][];
for (int i = 0; i < n; i++) {
costArray[i] = new Long[n];
}
vertexNum = n;
}
@Override
public void link(int from, int to, long cost) {
costArray[from][to] = new Long(cost);
}
@Override
public Optional<Long> getCost(int from, int to) {
return Optional.ofNullable(costArray[from][to]);
}
@Override
public int getVertexNum() {
return vertexNum;
}
}
/**
* DFS(深さ優先探索)による実装
* 計算量はO(E*MaxFlow)のはず (E:辺の数, MaxFlow:最大フロー)
*/
class DfsFlowResolver implements FlowResolver {
private Graph graph;
public DfsFlowResolver(Graph graph) {
this.graph = graph;
}
/**
* 最大フロー(最小カット)を求める
* @param from 始点(source)のID
* @param to 終点(target)のID
* @return 最大フロー(最小カット)
*/
public long maxFlow(int from, int to) {
long sum = 0L;
long currentFlow;
do {
currentFlow = flow(from, to, Long.MAX_VALUE / 3, new boolean[graph.getVertexNum()]);
sum += currentFlow;
} while (currentFlow > 0);
return sum;
}
/**
* フローの実行 グラフの更新も行う
* @param from 現在いる節点のID
* @param to 終点(target)のID
* @param current_flow ここまでの流量
* @param passed 既に通った節点か否かを格納した配列
* @return 終点(target)に流した流量/戻りのグラフの流量
*/
private long flow(int from, int to, long current_flow, boolean[] passed) {
passed[from] = true;
if (from == to) {
return current_flow;
}
for (int id = 0; id < graph.getVertexNum(); id++) {
if (passed[id]) {
continue;
}
Optional<Long> cost = graph.getCost(from, id);
if (cost.orElse(0L) > 0) {
long nextFlow = current_flow < cost.get() ? current_flow : cost.get();
long returnFlow = flow(id, to, nextFlow, passed);
if (returnFlow > 0) {
graph.link(from, id, cost.get() - returnFlow);
graph.link(id, from, graph.getCost(id, from).orElse(0L) + returnFlow);
return returnFlow;
}
}
}
return 0L;
}
}
/**
* 1-indexedのBIT配列
*/
class BinaryIndexedTree {
private long[] array;
public BinaryIndexedTree(int size) {
this.array = new long[size + 1];
}
/**
* 指定した要素に値を加算する
* 計算量はO(logN)
* @param index 加算する要素の添字
* @param value 加算する量
*/
public void add(int index, long value) {
for (int i = index; i < array.length; i += (i & -i)) {
array[i] += value;
}
}
/**
* 1〜指定した要素までの和を取得する
* 計算量はO(logN)
* @param index 和の終端
* @return 1〜indexまでの和
*/
public long getSum(int index) {
long sum = 0L;
for (int i = index; i > 0; i -= (i & -i)) {
sum += array[i];
}
return sum;
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class VKRound2Div2Task1 {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
String[] strs = str.split(" ");
int n = Integer.parseInt(strs[0]);
int a = Integer.parseInt(strs[1]);
int b = Integer.parseInt(strs[2]);
str = br.readLine();
String[] hs = str.split(" ");
int[] h = new int[hs.length];
for(int i=0;i<hs.length;i++){
h[i] = Integer.parseInt(hs[i]);
}
Arrays.sort(h);
if(h[b-1]==h[b]){
System.out.println(0);
}else{
System.out.println(h[b]-h[b-1]);
}
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.util.Scanner;
public class TwentyFive {
public static void main(String[] args) {
System.out.println(25);
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
// import java.awt.Point;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
long MOD = 1_000_000_007;
int inf = Integer.MAX_VALUE;
void solve(){
int n = ni();
int r = ni();
int[] x = new int[n];
for(int i = 0; i < n; i++){
x[i] = ni();
}
double[] y = new double[n];
Arrays.fill(y,-1);
for(int i = 0; i < n; i++){
for(int j = 0; j < i; j++){
double res = 4*r*r - (x[i]-x[j])*(x[i]-x[j]);
if(res < 0) continue;
else{
double tmp = Math.sqrt(res) + y[j];
if(tmp > y[i]){
y[i] = tmp;
}
}
}
if(y[i]==-1) y[i] = r;
}
for(int i = 0; i < n; i++){
out.print(y[i]+" ");
}
}
class Permutation{
// max=10
// n=10: 160ms
// n=11: 1600-1700ms
int n;
int max;
BitSet used;
int[] p;
public Permutation(int n, int max){
this.n = n;
this.max = max;
used = new BitSet(n);
p = new int[n];
}
public boolean next(){
if(used.cardinality() == 0){
for(int i=0; i<n; i++){
p[i] = i;
}
used.set(0, n);
return true;
}
int i;
for(i=n-1; i>=0; i--){
used.clear(p[i]);
if((used.nextClearBit(p[i]+1)) < max) break;
}
if(i<0) return false;
p[i] = used.nextClearBit(p[i]+1);
used.set(p[i]);
int idx = i+1;
for(i=used.nextClearBit(0); i<max && idx<n; i=used.nextClearBit(i+1)){
p[idx++] = i;
used.set(i);
}
return true;
}
public String toString(){
StringBuilder sb = new StringBuilder();
for(int i=0; i<n; i++){
sb.append(p[i]+" ");
}
return sb.toString();
}
}
void run() throws Exception
{
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Main().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b) && b != ' ')){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Solver {
StringTokenizer st;
BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws NumberFormatException, IOException {
Solver solver = new Solver();
solver.open();
solver.solve();
solver.close();
}
public void open() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
public String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
public void solve() throws NumberFormatException, IOException {
int n = nextInt();
out.println(0+" "+0+" "+n);
}
public void close() {
out.flush();
out.close();
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class Main {
int work(int x){
if(x%2==0)return x+1;
else return x-1;
}
static int N = 200050;
class Node implements Comparable <Node>{
int x, id;
Node(int x, int id){
this.x = x; this.id = id;
}
public int compareTo(Node o){
return Integer.compare(x, o.x);
}
public String toString(){
return id + "=" + x;
}
}
class Edge{
int from, to, nex;
Edge (int from, int to, int nex){
this.from = from;
this.to = to;
this.nex = nex;
}
}
Edge[] edge = new Edge[N*10];
int[] head = new int[N];
int edgenum;
void addedge(int u, int v){
Edge E = new Edge(u, v, head[u]);
edge[edgenum] = E;
head[u] = edgenum ++;
}
int n;
int[] p = new int[N], ans = new int[N];
int a, b, max;
Map<Integer, Integer> map = new HashMap();
boolean match(int x, int y, int col){
int P = map.get(x);
if(map.containsKey(y-x) == false)
return false;
int Q = map.get(y - x);
if(ans[Q] == -1 || x * 2 == y){
ans[Q] = ans[P] = col;
}
else {
if(match(a+b-2*y+x, y, col))
ans[Q] = ans[P] = col;
else return false;
}
return true;
}
boolean solve(){
if(max >= a && max >= b)return false;
for(int i = 1; i <= n; i++)
if(ans[i] == -1)
{
if(match(p[i], a, 0)==false && match(p[i], b, 1) == false)
return false;
}
return true;
}
void init(){
n = cin.nextInt();
a = cin.nextInt(); b = cin.nextInt();
max = 0;
for(int i = 1; i <= n; i++){
ans[i] = -1;
p[i] = cin.nextInt();
map.put(p[i], i);
if(p[i] > max) max = p[i];
}
}
public void work(){
init();
if(solve()){
out.println("YES");
for(int i = 1; i <= n; i++)out.print(ans[i]+" "); out.println();
}
else
out.println("NO");
}
Main() {
cin = new Scanner(System.in);
out = new PrintWriter(System.out);
}
public static void main(String[] args) {
Main e = new Main();
e.work();
out.close();
}
public Scanner cin;
public static PrintWriter out;
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.*;
import java.util.Arrays ;
import java .lang.String.* ;
import java .lang.StringBuilder ;
public class Test{
static int pos = 0 ;
static int arr[] ;
static LinkedList l1 = new LinkedList() ;
static void find(int p ,char[]x,int put[],String s){
int c= 0 ;
for (int i = 0; i < s.length(); i++) {
if(x[p]==s.charAt(i)){
c++ ; }
}
put[p] = c ;
}
static int mode(int m ,int[]x ){
int temp = 0 ;
for (int i = x.length-1; i >=0; i--) {
if(x[i]<=m){
temp= x[i] ;
/// break ;
return m-temp ;
}
}
return m-temp ;
}
static int mode2(int m ,int[]x ){
int temp = 0 ;
for (int i = x.length-1; i >=0; i--) {
if(x[i]<=m){
temp= x[i] ;
/// break ;
return x[i] ;
}
}
return 0 ;
}
static int find(int x[],int temp){
int j = 0 ;
for (int i = x.length-1; i >=0; i--) {
if(x[i]==temp) return j+1 ;
j++ ;
}
return -1 ;
}
static String ch(long[]x,long b){
for (int i = 0; i < x.length; i++) {
if(x[i]==b)return "YES" ;
}
return "NO" ;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in) ;
PrintWriter pw = new PrintWriter(System.out);
long n = in.nextLong() ;
long count =1 ;
long temp =n/2;
temp+=count ;
System.out.println(temp);
}
}
|
constant
|
964_A. Splits
|
CODEFORCES
|
// practice with rainboy
import java.io.*;
import java.util.*;
public class CF903F {
static final int INF = 0x3f3f3f3f;
static void fill(int[][][][] aa, int a) {
for (int h0 = 0; h0 <= 4; h0++)
for (int h1 = 0; h1 <= 4; h1++)
for (int h2 = 0; h2 <= 4; h2++)
for (int h3 = 0; h3 <= 4; h3++)
aa[h0][h1][h2][h3] = a;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int a1 = Integer.parseInt(st.nextToken());
int a2 = Integer.parseInt(st.nextToken());
int a3 = Integer.parseInt(st.nextToken());
int a4 = Integer.parseInt(st.nextToken());
int[] aa = new int[10];
aa[0] = aa[1] = aa[2] = aa[3] = a1;
aa[4] = aa[5] = aa[6] = a2;
aa[7] = aa[8] = a3;
aa[9] = a4;
int[][] ww = new int[10][4];
ww[0][0] = 1;
ww[1][1] = 1;
ww[2][2] = 1;
ww[3][3] = 1;
ww[4][0] = ww[4][1] = 2;
ww[5][1] = ww[5][2] = 2;
ww[6][2] = ww[6][3] = 2;
ww[7][0] = ww[7][1] = ww[7][2] = 3;
ww[8][1] = ww[8][2] = ww[8][3] = 3;
ww[9][0] = ww[9][1] = ww[9][2] = ww[9][3] = 4;
char[][] cc = new char[4][n + 8];
for (int k = 0; k < 4; k++) {
char[] c_ = cc[k];
br.readLine().getChars(0, n, c_, 4);
c_[0] = c_[1] = c_[2] = c_[3]
= c_[n + 4] = c_[n + 5] = c_[n + 6] = c_[n + 7] = '.';
}
int[][][][] dp = new int[5][5][5][5];
int[][][][] dq = new int[5][5][5][5];
fill(dp, INF);
dp[4][4][4][4] = 0;
int[] hh = new int[4];
for (int i = 0; i < n + 4; i++) {
for (int h0 = 0; h0 <= 4; h0++)
for (int h1 = 0; h1 <= 4; h1++)
for (int h2 = 0; h2 <= 4; h2++)
for (int h3 = 0; h3 <= 4; h3++)
for (int s = 0; s < 10; s++) {
hh[0] = h0;
hh[1] = h1;
hh[2] = h2;
hh[3] = h3;
for (int k = 0; k < 4; k++) {
int h = ww[s][k];
if (hh[k] < h) {
while (h < 4 && cc[k][i + h] == '.')
h++;
hh[k] = h;
}
}
int x = dp[h0][h1][h2][h3] + aa[s];
if (dp[hh[0]][hh[1]][hh[2]][hh[3]] > x)
dp[hh[0]][hh[1]][hh[2]][hh[3]] = x;
}
fill(dq, INF);
for (int h0 = 1; h0 <= 4; h0++) {
hh[0] = h0 < 4 || cc[0][i + 4] == '*' ? h0 - 1 : 4;
for (int h1 = 1; h1 <= 4; h1++) {
hh[1] = h1 < 4 || cc[1][i + 4] == '*' ? h1 - 1 : 4;
for (int h2 = 1; h2 <= 4; h2++) {
hh[2] = h2 < 4 || cc[2][i + 4] == '*' ? h2 - 1 : 4;
for (int h3 = 1; h3 <= 4; h3++) {
hh[3] = h3 < 4 || cc[3][i + 4] == '*' ? h3 - 1 : 4;
int x = dp[h0][h1][h2][h3];
if (dq[hh[0]][hh[1]][hh[2]][hh[3]] > x)
dq[hh[0]][hh[1]][hh[2]][hh[3]] = x;
}
}
}
}
int[][][][] tmp = dp; dp = dq; dq = tmp;
}
System.out.println(dp[4][4][4][4]);
}
}
|
linear
|
903_F. Clear The Matrix
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class C72A{
static BufferedReader br;
public static void main(String args[])throws Exception{
br=new BufferedReader(new InputStreamReader(System.in));
long n=toLong();
long res=n+n/2;
System.out.println(res);
}
/****************************************************************/
public static int[] toIntArray()throws Exception{
String str[]=br.readLine().split(" ");
int k[]=new int[str.length];
for(int i=0;i<str.length;i++){
k[i]=Integer.parseInt(str[i]);
}
return k;
}
public static int toInt()throws Exception{
return Integer.parseInt(br.readLine());
}
public static long[] toLongArray()throws Exception{
String str[]=br.readLine().split(" ");
long k[]=new long[str.length];
for(int i=0;i<str.length;i++){
k[i]=Long.parseLong(str[i]);
}
return k;
}
public static long toLong()throws Exception{
return Long.parseLong(br.readLine());
}
public static double[] toDoubleArray()throws Exception{
String str[]=br.readLine().split(" ");
double k[]=new double[str.length];
for(int i=0;i<str.length;i++){
k[i]=Double.parseDouble(str[i]);
}
return k;
}
public static double toDouble()throws Exception{
return Double.parseDouble(br.readLine());
}
public static String toStr()throws Exception{
return br.readLine();
}
public static String[] toStrArray()throws Exception{
String str[]=br.readLine().split(" ");
return str;
}
/****************************************************************/
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class Main2 {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int k = input.nextInt();
int[] num = new int[n];
for(int i = 0 ; i < n ; i++){
num[i] = input.nextInt();
}
System.out.println(str(n,m,k,num));
}
static int str(int n,int m,int k,int[] num){
Arrays.sort(num);
int total = k;
int count = 0;
while(k < m){
if(count == num.length)return -1;
k += num[num.length-count-1]-1;
count++;
}
return count;
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
public class main {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static PrintWriter pw = new PrintWriter(System.out);
public static String line;
public static StringTokenizer st;
public static ArrayList<ArrayList<Integer>> adjList;
public static void main(String[] args) throws Exception{
String s = br.readLine();
pw.print(25);
pw.print("\n");
pw.close();
br.close();
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.util.Locale;
import java.util.Scanner;
public class E {
public static void main(String[] args) {
new E().solve();
}
private int c(int n) {
return n * (n - 1) / 2;
}
public void solve() {
Locale.setDefault(Locale.US);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double[][] pb = new double[n][n];
for (int i=0; i<n; ++i)
for (int j=0; j<n; ++j)
pb[i][j] = sc.nextDouble();
int m = (1<<n);
double[] dp = new double[m];
dp[0] = 1.0f;
for (int i=1; i<m; ++i)
for (int j=0; j<n; ++j) if ((i & (1<<j)) != 0)
for (int k=0; k<n; ++k) if ((i & (1<<k)) == 0)
dp[i] += pb[k][j] * dp[i & ~(1<<j)] / c(n - Integer.bitCount(i) + 1);
int w = (1<<n) - 1;
for (int i=0; i<n-1; ++i)
System.out.printf("%.6f ", dp[w & ~(1<<i)]);
System.out.printf("%.6f\n", dp[w & ~(1<<(n-1))]);
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.awt.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
public class B {
static int ourLevel;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
ourLevel = Integer.parseInt(st.nextToken());
State[] list = new State[n];
for(int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
list[i] = new State(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())/10);
}
System.out.println(solve(list, 0, k));
}
public static double solve(State[] s, int index, int left) {
if(index == s.length)
return prob(s);
double ret = 0;
for(int c = 0; c <= left && s[index].prob + c <= 10; c++) {
s[index].prob += c;
ret = Math.max(ret, solve(s, index+1, left-c));
s[index].prob -= c;
}
return ret;
}
public static double prob(State[] s) {
double win = 1;
for(int i = 0; i < (1<<s.length); i++) {
int numLose = s.length - Integer.bitCount(i);
if(2*numLose >= s.length) {
int level = 0;
double p = 1;
for(int j = 0; j < s.length; j++) {
if((i&(1<<j)) == 0) {
p *= (10-s[j].prob)/10.;
level += s[j].level;
}
else {
p *= s[j].prob/10.;
}
}
double lose = level * 1.0 / (ourLevel + level);
win -= p * lose;
}
}
return win;
}
static class State {
public int level,prob;
public State(int a, int b) {
level = a;
prob = b;
}
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A {
static double[][] a;
static int N;
static double[][] memo;
static double[] dp(int alive)
{
int count = Integer.bitCount(alive);
if(count == 1)
{
double[] ret = new double[N];
for(int i = 0; i < N; ++i)
if((alive & (1<<i)) != 0)
{
ret[i] = 1;
break;
}
return memo[alive] = ret;
}
if(memo[alive] != null)
return memo[alive];
double[] ret = new double[N];
for(int j = 0; j < N; ++j)
if((alive & (1<<j)) != 0)
{
double[] nxt = dp(alive & ~(1<<j));
for(int i = 0; i < N; ++i)
ret[i] += die[j][alive] * nxt[i];
}
return memo[alive] = ret;
}
static double[][] die;
static void f()
{
die = new double[N][1<<N];
for(int i = 0; i < N; ++i)
for(int j = 0; j < 1<<N; ++j)
{
int count = Integer.bitCount(j);
if(count <= 1)
continue;
double prop = 1.0 / (count * (count - 1) >> 1);
for(int k = 0; k < N; ++k)
if((j & (1<<k)) != 0)
die[i][j] += prop * a[k][i];
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
N = sc.nextInt();
a = new double[N][N];
for(int i = 0; i < N; ++i)
for(int j = 0; j < N; ++j)
a[i][j] = sc.nextDouble();
memo = new double[1<<N][];
f();
double[] ret = dp((1<<N) - 1);
for(int i = 0; i < N - 1; ++i)
out.printf("%.8f ",ret[i]);
out.printf("%.8f\n", ret[N-1]);
out.flush();
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready();}
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.List;
import java.awt.*;
public class Trains1_2 implements Runnable {
private BufferedReader br = null;
private PrintWriter pw = null;
private StringTokenizer stk = new StringTokenizer("");
public static void main(String[] args) {
new Thread(new Trains1_2()).run();
}
public void run() {
/*
* try { br = new BufferedReader(new FileReader("knapsackfixed.in")); pw
* = new PrintWriter("knapsackfixed.out"); } catch
* (FileNotFoundException e) { e.printStackTrace(); }
*/
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
solver();
pw.close();
}
private void nline() {
try {
if (!stk.hasMoreTokens())
stk = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException("KaVaBUnGO!!!", e);
}
}
private String nstr() {
while (!stk.hasMoreTokens())
nline();
return stk.nextToken();
}
private int ni() {
return Integer.valueOf(nstr());
}
private long nl() {
return Long.valueOf(nstr());
}
private double nd() {
return Double.valueOf(nstr());
}
boolean isNumber(char c) {
if (c <= '9' && c >= '0')
return true;
return false;
}
String to10(String s) {
long ans = 0;
for (int i = s.length() - 1; i >= 0; i--) {
ans += (s.charAt(i) - 'A' + 1) * Math.pow(26, s.length() - i - 1);
}
return String.valueOf(ans);
}
String to26(String s){
String ans="";
int a = Integer.valueOf(s);
while(a>26){
a--;
int k = a%26;
ans=ans+(char)((int)'A'+k);
a/=26;
}
ans+=(char)(a+'A'-1);
String ans1 = "";
for(int i = ans.length()-1; i>=0; i--)ans1+=ans.charAt(i);
return ans1;
}
String rev(String s) {
String ans = "";
int format = 0;
int git = 0;
String token1 = "";
String token2 = "";
String token3 = "", token4 = "";
for (int i = 0; i < s.length(); i++) {
if (!isNumber(s.charAt(i)))
token1 += s.charAt(i);
else
break;
git++;
}
for (int i = git; i < s.length(); i++) {
if (isNumber(s.charAt(i)))
token2 += s.charAt(i);
else
break;
git++;
}
if (s.length() == git)
format = 1;
else {
format = 2;
for (int i = git; i < s.length(); i++) {
if (!isNumber(s.charAt(i)))
token3 += s.charAt(i);
else
break;
git++;
}
for (int i = git; i < s.length(); i++)
if (isNumber(s.charAt(i)))
token4 += s.charAt(i);
else
break;
}
if (format == 1) {
ans += "R";
ans += token2;
ans += "C";
ans += to10(token1);
}else{
ans+=to26(token4);
ans+=token2;
}
return ans;
}
private void solver() {
int n = ni();
for (int i = 0; i < n; i++)
System.out.println(rev(nstr()));
}
void exit() {
System.exit(0);
}
}
|
linear
|
1_B. Spreadsheets
|
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.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jialin Ouyang (Jialin.Ouyang@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskG solver = new TaskG();
solver.solve(1, in, out);
out.close();
}
static class TaskG {
static int MAXL = 700 + 1;
static IntModular MOD = new IntModular();
int n;
char[] digits;
int[] pow10;
int[] ones;
int[][][] way;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
digits = new char[MAXL];
n = in.next(digits);
initPow();
int res = MOD.mul(calc(9), 9);
for (int digit = 0; digit < 9; ++digit) {
res = MOD.sub(res, calc(digit));
}
out.println(res);
}
void initPow() {
pow10 = new int[n + 1];
ones = new int[n + 1];
pow10[0] = 1;
for (int i = 1; i <= n; ++i) {
pow10[i] = MOD.mul(pow10[i - 1], 10);
ones[i] = MOD.add(MOD.mul(ones[i - 1], 10), 1);
}
}
int calc(int targetDigit) {
if (way == null) {
way = new int[2][2][n + 1];
}
int t = 0;
clearCnt(t);
way[t][0][0] = 1;
for (int i = 0; i < n; ++i) {
int digit = digits[i] - '0';
clearCnt(t ^ 1);
// not free
for (int cnt = 0; cnt <= n; ++cnt)
if (way[t][0][cnt] > 0) {
// not free
int newCnt = targetDigit < digit ? cnt + 1 : cnt;
way[t ^ 1][0][newCnt] = MOD.add(
way[t ^ 1][0][newCnt],
way[t][0][cnt]);
// free
way[t ^ 1][1][cnt] = MOD.add(
way[t ^ 1][1][cnt],
MOD.mul(
Math.min(targetDigit + 1, digit),
way[t][0][cnt]));
way[t ^ 1][1][cnt + 1] = MOD.add(
way[t ^ 1][1][cnt + 1],
MOD.mul(
Math.max(digit - targetDigit - 1, 0),
way[t][0][cnt]));
}
// free
for (int cnt = 0; cnt <= n; ++cnt)
if (way[t][1][cnt] > 0) {
way[t ^ 1][1][cnt] = MOD.add(
way[t ^ 1][1][cnt],
MOD.mul(
targetDigit + 1,
way[t][1][cnt]));
way[t ^ 1][1][cnt + 1] = MOD.add(
way[t ^ 1][1][cnt + 1],
MOD.mul(
9 - targetDigit,
way[t][1][cnt]));
}
t ^= 1;
}
int res = 0;
for (int cnt = 0; cnt <= n; ++cnt) {
res = MOD.add(
res,
MOD.mul(MOD.mul(
ones[n - cnt],
pow10[cnt]),
MOD.add(way[t][0][cnt], way[t][1][cnt])));
}
return res;
}
void clearCnt(int t) {
for (int free = 0; free < 2; ++free) {
Arrays.fill(way[t][free], 0);
}
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(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 println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class IntModular {
private static final int MOD = 1000000007;
public final int mod;
private final int[] x;
public IntModular() {
this(MOD);
}
public IntModular(int mod) {
this.mod = mod;
this.x = new int[2];
}
public int add(int a, int b) {
return fix(a + b, mod);
}
public int sub(int a, int b) {
return fix(a - b, mod);
}
public int mul(int a, int b) {
return mul(a, b, mod);
}
public static int mul(int a, int b, int mod) {
return a > 0
? (b < mod / a ? a * b : (int) ((long) a * b % mod))
: 0;
}
public static int fix(int a, int mod) {
a = slightFix(a, mod);
return 0 <= a && a < mod ? a : slightFix(a % mod, mod);
}
private static int slightFix(int a, int mod) {
return a >= mod
? a - mod
: a < 0 ? a + mod : a;
}
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPosition;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPosition = 0;
this.numberOfChars = 0;
}
public int next(char[] s) {
return next(s, 0);
}
public int next(char[] s, int startIdx) {
int b = nextNonSpaceChar();
int res = 0;
do {
s[startIdx++] = (char) b;
b = nextChar();
++res;
} while (!isSpaceChar(b));
return res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPosition >= numberOfChars) {
currentPosition = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPosition++];
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\t' || isEndOfLineChar(c);
}
public boolean isEndOfLineChar(int c) {
return c == '\n' || c == '\r' || c < 0;
}
}
}
|
quadratic
|
908_G. New Year and Original Order
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Tester
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = 1000000007;
public static void main(String[] args) {
solveQ3();
}
private static void solveQ3() {
// TODO Auto-generated method stub
FastReader sc = new FastReader();
long x = sc.nextLong();
long k = sc.nextLong();
if(x == 0) {
System.out.println(0);
return;
}
long ans = modExp(2, k);
x = (2*x)%mod;
x = (x - 1 + mod)%mod;
ans = (ans*x)%mod;
ans = (ans + 1)%mod;
System.out.println(ans);
}
private static long modExp(long a, long n) {
if(n == 0)
return 1;
if(n%2 == 0)
return modExp((a*a)%mod, n/2);
else
return (a*modExp((a*a)%mod, n/2))%mod;
}
private static void solveQ2() {
// TODO Auto-generated method stub
FastReader sc = new FastReader();
long l = sc.nextLong();
long r = sc.nextLong();
long x = sc.nextLong();
long y = sc.nextLong();
long n = x*y;
long count = 0;
for(long i=l; (i<=Math.sqrt(n)) && (n/i<=r); i++) {
if((n%i == 0) && (gcd(i, n/i)==x)) {
if(i*i != n)
count += 2;
else
count += 1;
}
}
System.out.println(count);
}
public static long gcd(long a, long b) {
if(b==0)
return a;
else
return gcd(b, a%b);
}
private static void solveQ1() {
// TODO Auto-generated method stub
FastReader sc = new FastReader();
int n = sc.nextInt();
HashSet<Integer> hs = new HashSet<Integer>();
for(int i=0; i<n; i++) {
int x = sc.nextInt();
if(x != 0) {
hs.add(x);
}
}
System.out.println(hs.size());
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
// static Scanner in;
static PrintWriter out;
static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;}
public static void main(String[] args) throws Exception {
// in = new Scanner(System.in);
out = new PrintWriter(System.out);
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
int n = next();
int t = 2*next();
int[] x = new int[n];
int[] a = new int[n];
for (int i = 0; i < n; i++) {
x[i] = 2* next() + 2000;
a[i] = next();
}
int[] srt = new int[n];
for (int i = 0; i < n; i++) srt[i] = 10000 * x[i] + a[i];
Arrays.sort(srt);
for (int i = 0; i < n; i++) {
x[i] = srt[i] / 10000;
a[i] = srt[i] % 10000;
}
int answ = 2;
for (int i = 0; i < n - 1; i++) {
if (x[i + 1] - x[i] > a[i] + a[i + 1] + t) answ++;
if (x[i + 1] - x[i] >= a[i] + a[i + 1] + t) answ++;
}
out.println(answ);
out.close();
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.util.Scanner;
public class P23A {
public P23A() {
Scanner sc = new Scanner(System.in);
String str = sc.next();
sc.close();
String maxStr = "";
for (int i = 0; i < str.length() - 1; i++){
for (int j = i + 1; j < str.length(); j++){
String pattern = str.substring(i, j);
if (str.substring(i+1).contains(pattern) && pattern.length() > maxStr.length()){
maxStr = pattern;
}
}
}
System.out.println(maxStr.length());
}
public static void main (String []args){
new P23A();
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.Point;
public class Main {
static final long MOD = 1000000007L;
//static final long MOD2 = 1000000009L;
//static final long MOD = 998244353L;
//static final long INF = 500000000000L;
static final int INF = 1000000005;
static final int NINF = -1000000005;
//static final long INF = 1000000000000000000L;
static FastScanner sc;
static PrintWriter pw;
static final int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
public static void main(String[] args) {
sc = new FastScanner();
pw = new PrintWriter(System.out);
int Q = sc.ni();
for (int q = 0; q < Q; q++) {
int N = sc.ni();
int[] nums = sc.intArray(N, 0);
pw.println(1);
ArrayDeque<Integer> ad = new ArrayDeque<Integer>();
ad.push(1);
for (int i = 1; i < N; i++) {
if (nums[i]==1) {
ad.push(1);
} else {
while (!ad.isEmpty()) {
int d = ad.pop();
if (d==nums[i]-1) {
ad.push(nums[i]);
break;
}
}
}
printAD(ad);
}
}
pw.close();
}
public static void printAD(ArrayDeque<Integer> v) {
Object[] arr = v.toArray();
for (int i = arr.length-1; i >= 0; i--) {
pw.print(arr[i]);
if (i>0) pw.print(".");
}
pw.println();
}
public static void sort(int[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
public static void sort(long[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
//Sort an array (immune to quicksort TLE)
public static void sort(int[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
return a[0]-b[0];
}
});
}
public static void sort(long[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else
return 0;
//Ascending order.
}
});
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[][] graph(int N, int[][] edges) {
int[][] graph = new int[N][];
int[] sz = new int[N];
for (int[] e: edges) {
sz[e[0]] += 1;
sz[e[1]] += 1;
}
for (int i = 0; i < N; i++) {
graph[i] = new int[sz[i]];
}
int[] cur = new int[N];
for (int[] e: edges) {
graph[e[0]][cur[e[0]]] = e[1];
graph[e[1]][cur[e[1]]] = e[0];
cur[e[0]] += 1;
cur[e[1]] += 1;
}
return graph;
}
int[] intArray(int N, int mod) {
int[] ret = new int[N];
for (int i = 0; i < N; i++)
ret[i] = ni()+mod;
return ret;
}
char[] charArray(int N) {
char[] ret = new char[N];
for (int i = 0; i < N; i++)
ret[i] = next().charAt(0);
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N, long mod) {
long[] ret = new long[N];
for (int i = 0; i < N; i++)
ret[i] = nl()+mod;
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.Scanner;
public class NickAndArray {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int array[]=new int[n];
int max=Integer.MAX_VALUE;
int index=0;
for(int i=0;i<n;i++)
{
int k=sc.nextInt();
array[i]=k;
if(array[i]>=0)
{
array[i]=-array[i]-1;
}
if(array[i]<max)
{
max=array[i];
index=i;
}
}
if(n%2!=0)
{
array[index]=-array[index]-1;
}
for(int i=0;i<n;i++)
{
System.out.print(array[i]+" " );
}
}
}
|
linear
|
1180_B. Nick and Array
|
CODEFORCES
|
import java.util.*;
public class test{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int m=s.nextInt();
int arr[]=new int[n];
int max = Integer.MIN_VALUE;
long sum = 0;
for(int i=0;i<n;i++)
{
arr[i] = s.nextInt();
sum = sum + arr[i];
max = Math.max(max,arr[i]);
}
Arrays.sort(arr);
int i = 0;
int count = 0;
int d = 0;
for(i=0; i<n; i++)
{
if(arr[i] > d)
{
count++;
d++;
}
else if(arr[i] == d && arr[i] > 0)
{
count++;
}
}
//System.out.println(count + " " + max);
if(max - d > 0)
{
count = count + max - d;
}
System.out.println(sum - count);}}
|
nlogn
|
1061_B. Views Matter
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
import static java.lang.Integer.*;
public class BDiv1 {
static int n;
static int a;
static int b;
static HashMap<Integer,Integer> graphA=new HashMap<>();
static HashMap<Integer,Integer> graphB=new HashMap<>();
static int [] array;
static int [] original;
static boolean x=true;
public static void main(String[] args) throws Exception{
BufferedReader buf =new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st =new StringTokenizer(buf.readLine());
n=parseInt(st.nextToken());
a=parseInt(st.nextToken());
b=parseInt(st.nextToken());
st =new StringTokenizer(buf.readLine());
array=new int[n];
original=new int [n];
for (int i=0;i<n;i++){
array[i]=parseInt(st.nextToken());
original[i]=array[i];
}
Arrays.sort(array);
for (int i=0;i<n;i++){
int k= Arrays.binarySearch(array,a-array[i]);
if (k>=0){
graphA.put(array[i],array[k]);
graphA.put(array[k],array[i]);
}
}
for (int i=0;i<n;i++){
int k= Arrays.binarySearch(array,b-array[i]);
if (k>=0){
graphB.put(array[i],array[k]);
graphB.put(array[k],array[i]);
}
}
for (int i=0;i<n;i++){
Integer j=graphA.get(array[i]);
if (j!=null){
if (graphB.containsKey(array[i]) && graphB.containsKey(j)){
graphA.remove(array[i]);
graphA.remove(j);
}
else if (graphB.containsKey(array[i]) && !graphB.containsKey(j)){
graphB.remove(graphB.get(array[i]));
graphB.remove(array[i]);
}
else if (!graphB.containsKey(array[i]) && graphB.containsKey(j)){
graphB.remove(graphB.get(j));
graphB.remove(j);
}
}
}
int [] res=new int [n];
for (int i=0;i<n;i++){
if (graphA.containsKey(original[i]))res[i]=0;
else if (graphB.containsKey(original[i])) res[i]=1;
else {
System.out.println("NO");
return;
}
}
System.out.println("YES");
for (int k:res)System.out.print(k+" ");
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class A {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
long n = s.nextLong();
if(n >= 0)
System.out.println(n);
else {
String str = ("" + n).substring(1);
if(str.length() == 1)
System.out.println("-" + str);
else {
long one = Long.parseLong(str.substring(0, str.length()-1));
long two = Long.parseLong(str.substring(0, str.length()-2) + str.substring(str.length()-1));
if(one > two)
System.out.println((two!=0?"-":"") + two);
else
System.out.println((one!=0?"-":"") + one);
}
}
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class A {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = new String(in.readLine());
String[] t=s.split(" ");
int n = Integer.parseInt(t[0]);
int k = Integer.parseInt(t[1]);
boolean[] prime=new boolean[n+1];
for (int i=2;i<Math.sqrt(n);i++) {
for (int j=i+i;j<=n;j=j+i) {
prime[j]=true;
}
}
int size=0;
for (int i=2;i<=n;i++) {
if (!prime[i]) {
size++;
}
}
int[] pn=new int[size];
int index=0;
for (int i=2;i<=n;i++) {
if (!prime[i]) {
pn[index]=i;
index++;
}
}
for (int i=2;i<size;i++) {
for (int j=0;j<i;j++) {
if (pn[i]==pn[j]+pn[j+1]+1) {
// System.out.println(pn[i]+"="+pn[j]+"+"+pn[j+1]+"+1");
k--;
}
}
}
if (k<=0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
void solve() throws IOException {
int n=ni();//have bult yet
int t=ni();//new house
int[] center=new int[n];
int[] width=new int[n];
for(int i=0;i<n;i++){
center[i]=ni();
width[i]=ni();
}
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(center[i]>center[j]){
int cent=center[i];
int wid=width[i];
center[i]=center[j];
width[i]=width[j];
center[j]=cent;
width[j]=wid;
}
}
}
int count=2;
for(int i=0;i<n-1;i++){
//min way
double ideal=(double)width[i]/2+(double)width[i+1]/2+t;
//real way
double real=center[i+1]-center[i];
//out.println(ideal);
//out.println(real);
if(ideal==real)count++;
else{
if(ideal<real)count=count+2;
}
}
out.println(count);
}
public Main() throws IOException {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
String ns() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int ni() throws IOException {
return Integer.valueOf(ns());
}
long nl() throws IOException {
return Long.valueOf(ns());
}
double nd() throws IOException {
return Double.valueOf(ns());
}
public static void main(String[] args) throws IOException {
new Main();
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
//package fourninetysixDiv3;
import java.util.HashMap;
import java.util.Scanner;
public class Median_Segments_general {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
System.out.println(func(n, m, arr)-func(n, m+1, arr));
}
public static long func(int n,int m,int[] arr) {
HashMap<Long, Integer> map = new HashMap<>();
map.put((long) 0, 1);
long sum = 0;
long res = 0;
long add=0;
for(int i=0;i<n;i++) {
if(arr[i]<m) {
sum--;
if(map.containsKey(sum)) {
add-=map.get(sum);
}
}
else {
if(map.containsKey(sum)) {
add+=map.get(sum);
}
sum++;
}
res+=add;
if(map.containsKey(sum)) {
map.put(sum, map.get(sum)+1);
}
else {
map.put(sum,1);
}
}
return res;
}
}
|
nlogn
|
1005_E1. Median on Segments (Permutations Edition)
|
CODEFORCES
|
//package round159;
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 A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni(), K = ni();
int[] a = na(n);
a = radixSort(a);
if(K >= m){
out.println(0);
return;
}
int p = 1;
for(int i = n-1;i >= 0;i--){
K += a[i]-1;
if(K >= m){
out.println(p);
return;
}
p++;
}
out.println(-1);
}
public static int[] radixSort(int[] f)
{
int[] to = new int[f.length];
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
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 A().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
nlogn
|
257_A. Sockets
|
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);
TaskG solver = new TaskG();
solver.solve(1, in, out);
out.close();
}
static class TaskG {
static int[][] g;
static int n;
static int[] a;
static int[][] edges;
static long[] dp;
static long[] dpPathToRootWithDetours;
static int time = 0;
static int[] appearance;
static int[] firstAppearance;
static int[] depth;
public static void dfs(int i, int parE) {
firstAppearance[i] = time;
appearance[time++] = i;
dp[i] = a[i];
for (int eIndex : g[i]) {
if (eIndex == parE) continue;
int child = i ^ edges[eIndex][0] ^ edges[eIndex][1];
dfs(child, eIndex);
appearance[time++] = i;
dp[i] += Math.max(dp[child] - edges[eIndex][2] * 2, 0);
}
}
public static void dfs2(int i, int parE) {
if (i == 0) {
dpPathToRootWithDetours[i] = dp[i];
} else {
int par = i ^ edges[parE][0] ^ edges[parE][1];
depth[i] = depth[par] + 1;
dpPathToRootWithDetours[i] = dpPathToRootWithDetours[par] - Math.max(0, dp[i] - edges[parE][2] * 2);
dpPathToRootWithDetours[i] -= edges[parE][2];
dpPathToRootWithDetours[i] += dp[i];
long myPathWeight = Math.max(dp[i] - edges[parE][2] * 2, 0);
long change = dp[par] - myPathWeight - edges[parE][2] * 2;
change = Math.max(change, 0);
dp[i] += change;
}
for (int eIndex : g[i]) {
if (eIndex == parE) continue;
dfs2(i ^ edges[eIndex][0] ^ edges[eIndex][1], eIndex);
}
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.NextInt();
int q = in.NextInt();
a = in.NextIntArray(n);
edges = new int[n - 1][3];
{
long[] count = new long[n];
for (int i = 0; i < n - 1; i++) {
int u = in.NextInt() - 1;
int v = in.NextInt() - 1;
int w = in.NextInt();
edges[i][0] = u;
edges[i][1] = v;
edges[i][2] = w;
count[u]++;
count[v]++;
}
g = new int[n][];
for (int i = 0; i < n; i++) {
g[i] = new int[(int) count[i]];
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < 2; j++) {
g[edges[i][j]][(int) --count[edges[i][j]]] = i;
}
}
}
dp = new long[n];
dpPathToRootWithDetours = new long[n];
depth = new int[n];
firstAppearance = new int[n];
appearance = new int[(n - 1) * 2 + 1];
dfs(0, -1);
dfs2(0, -1);
GraphLowestCommonAncestor.LCA lca = GraphLowestCommonAncestor.createLCA(appearance, firstAppearance, depth);
firstAppearance = null;
depth = null;
appearance = null;
edges = null;
g = null;
for (int i = 0; i < q; i++) {
int u = in.NextInt() - 1;
int v = in.NextInt() - 1;
int lcaI = lca.getLCA(u, v);
long res = dpPathToRootWithDetours[u] + dpPathToRootWithDetours[v] - 2 * dpPathToRootWithDetours[lcaI] + dp[lcaI];
out.println(res);
}
}
}
static class MinRangeSparseTable implements ISearchInRange {
private final int[][] sparseTables;
private final long[] array;
private final boolean reverseOrdered;
public MinRangeSparseTable(long[] array, boolean reverseOrdered) {
this.reverseOrdered = reverseOrdered;
this.array = array;
int LCALength = IntegerExtension.getNumberOfBits(array.length);
sparseTables = new int[LCALength][];
sparseTables[0] = new int[array.length];
for (int i = 0; i < array.length; i++) {
sparseTables[0][i] = i;
}
for (int i = 1; i < LCALength; i++) {
int size = 1 << i;
int jumpSize = 1 << (i - 1);
sparseTables[i] = new int[sparseTables[0].length - size + 1];
for (int j = 0; j < sparseTables[i].length; j++) {
sparseTables[i][j] = min(sparseTables[i - 1][j], sparseTables[i - 1][j + jumpSize]);
}
}
}
private int min(int a, int b) {
return ((array[a] < array[b]) ^ reverseOrdered) ? a : b;
}
public Pair<Long, Long> queryIndexValueInRange(long l, long r) {
int size = (int) (r - l + 1);
int LCAIndex = IntegerExtension.getNumberOfBits(size) - 1;
int sizeNeeded = 1 << LCAIndex;
int res = min(sparseTables[LCAIndex][(int) l], sparseTables[LCAIndex][(int) (r - sizeNeeded + 1)]);
return new Pair<>((long) res, array[res]);
}
public MinRangeSparseTable(long[] array) {
this(array, false);
}
}
static class GraphLowestCommonAncestor {
public static GraphLowestCommonAncestor.LCA createLCA(int[] appearances, final int[] firstAppearance, final int[] depth) {
return new GraphLowestCommonAncestor.LCA_MinRangeSparseTable(appearances, firstAppearance, depth);
}
public interface LCA {
int getLCA(int a, int b);
}
private static class LCA_MinRangeSparseTable implements GraphLowestCommonAncestor.LCA {
private final MinRangeSparseTable minRangeSparseTable;
private final int[] firstAppearance;
private final int[] indexToNode;
public LCA_MinRangeSparseTable(int[] appearances, final int[] firstAppearance, final int[] depth) {
this.firstAppearance = firstAppearance;
this.indexToNode = appearances;
long[] depthOrder = new long[appearances.length];
for (int i = 0; i < depthOrder.length; i++) {
depthOrder[i] = depth[appearances[i]];
}
minRangeSparseTable = new MinRangeSparseTable(depthOrder);
}
public int getLCA(int a, int b) {
a = firstAppearance[a];
b = firstAppearance[b];
int l = Math.min(a, b), r = Math.max(a, b);
return indexToNode[(int) (long) minRangeSparseTable.queryIndexValueInRange(l, r).first];
}
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine(), " \t\n\r\f,");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int NextInt() {
return Integer.parseInt(next());
}
public int[] NextIntArray(int n) {
return NextIntArray(n, 0);
}
public int[] NextIntArray(int n, int offset) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = NextInt() + offset;
}
return a;
}
}
static interface ISearchInRange {
}
static class Pair<T1, T2> {
public T1 first;
public T2 second;
public Pair(T1 f, T2 s) {
first = f;
second = s;
}
}
static class IntegerExtension {
public static int getNumberOfBits(long i) {
return 64 - Long.numberOfLeadingZeros(i);
}
}
}
|
nlogn
|
1000_G. Two-Paths
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class B {
static Scanner in; static int next() throws Exception {return in.nextInt();};
// static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;}
// static BufferedReader in;
static PrintWriter out;
public static long count(long k, long x, long y, long n) {
long sum = 2*k*(k+1)+1;
if (k >= x-1) {
sum -= (k-x+1)*(k-x+1);
}
if (k >= y-1) {
sum -= (k-y+1)*(k-y+1);
}
if (k + x >= n) {
sum -= (k+x-n)*(k+x-n);
}
if (k + y >= n) {
sum -= (k+y-n)*(k+y-n);
}
if (k > x+y-1) {
sum += ((k+1-x-y)*(k+1-x-y+1))/2;
}
if (k > n-x+y) {
sum += ((k+x-n-y)*(k+x-n-y+1))/2;
}
if (k > n-y+x) {
sum += ((k+y-n-x)*(k+y-n-x+1))/2;
}
if (k > 2*n-x-y+1) {
sum += ((k-2*n+x+y-1)*(k-2*n+x+y))/2;
}
return sum;
}
public static void main(String[] args) throws Exception {
in = new Scanner(System.in);
// in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
// in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
long n = in.nextLong(), x = in.nextLong(), y = in.nextLong(), c = in.nextLong();
long res = 0;
while (count(res, x, y, n) < c) res++;
out.println(res);
out.println();
out.close();
}
}
|
logn
|
256_B. Mr. Bender and Square
|
CODEFORCES
|
//package que_a;
import java.io.*;
import java.util.*;
import java.math.*;
public class utkarsh {
InputStream is;
PrintWriter out;
long mod = (long) (1e9 + 7);
boolean SHOW_TIME;
void solve() {
//Enter code here utkarsh
//SHOW_TIME = true;
long X = nl();
BigInteger x = BigInteger.valueOf(X);
long K = nl();
BigInteger k = BigInteger.valueOf(K);
BigInteger MOD = BigInteger.valueOf(mod);
if(X == 0) {
out.println(0); return;
}
if(k.compareTo(BigInteger.ZERO) == 0) {
out.println((x.add(x)).mod(MOD)); return;
}
BigInteger p = BigInteger.valueOf(modpow(2, K, mod));
BigInteger ans = x.multiply(p);
ans = ans.add(ans);
ans = ans.subtract(p).add(BigInteger.ONE);
ans = ans.add(MOD);
out.println(ans.mod(MOD));
}
long modpow(long b, long e, long mod) {
b %= mod;
long r = 1;
while(e > 0) {
if((e & 1) == 1) {
r *= b; r %= mod;
}
b *= b; b %= mod;
e >>= 1;
}
return r;
}
//---------- I/O Template ----------
public static void main(String[] args) { new utkarsh().run(); }
void run() {
is = System.in;
out = new PrintWriter(System.out);
long start = System.currentTimeMillis();
solve();
long end = System.currentTimeMillis();
if(SHOW_TIME) out.println("\n" + (end - start) + " ms");
out.flush();
}
byte input[] = new byte[1024];
int len = 0, ptr = 0;
int readByte() {
if(ptr >= len) { ptr = 0;
try { len = is.read(input); }
catch(IOException e) { throw new InputMismatchException(); }
if(len <= 0) { return -1; }
} return input[ptr++];
}
boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); }
int skip() {
int b = readByte();
while(b != -1 && isSpaceChar(b)) { b = readByte(); }
return b;
}
char nc() { return (char)skip(); }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
String nLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
int ni() {
int n = 0, b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
if(b == -1) { return -1; } //no input
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
long nl() {
long n = 0L; int b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
double nd() { return Double.parseDouble(ns()); }
float nf() { return Float.parseFloat(ns()); }
int[] na(int n) {
int a[] = new int[n];
for(int i = 0; i < n; i++) { a[i] = ni(); }
return a;
}
char[] ns(int n) {
char c[] = new char[n];
int i, b = skip();
for(i = 0; i < n; i++) {
if(isSpaceChar(b)) { break; }
c[i] = (char)b; b = readByte();
} return i == n ? c : Arrays.copyOf(c,i);
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main2 {
static long mod = 998244353;
static FastScanner scanner;
static Set<Long> second = new HashSet<>();
static boolean applied = false;
public static void main(String[] args) {
scanner = new FastScanner();
int n = scanner.nextInt();
int[] a = scanner.nextIntArray(n);
int[] colors = new int[n];
ADUtils.sort(a);
int color = 0;
for (int i = 0; i < n; i++) {
if (colors[i] != 0) continue;
color++;
for (int j = i; j < n; j++) {
if (a[j] % a[i] == 0) colors[j] = color;
}
}
System.out.println(color);
}
static class WithIdx implements Comparable<WithIdx>{
int val, idx;
public WithIdx(int val, int idx) {
this.val = val;
this.idx = idx;
}
@Override
public int compareTo(WithIdx o) {
return Integer.compare(val, o.val);
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
int[] nextIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
long[] nextLongArray(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) res[i] = nextLong();
return res;
}
String[] nextStringArray(int n) {
String[] res = new String[n];
for (int i = 0; i < n; i++) res[i] = nextToken();
return res;
}
}
static class PrefixSums {
long[] sums;
public PrefixSums(long[] sums) {
this.sums = sums;
}
public long sum(int fromInclusive, int toExclusive) {
if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value");
return sums[toExclusive] - sums[fromInclusive];
}
public static PrefixSums of(int[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
public static PrefixSums of(long[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
}
static class ADUtils {
static void sort(int[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
static void reverse(int[] arr) {
int last = arr.length / 2;
for (int i = 0; i < last; i++) {
int tmp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = tmp;
}
}
static void sort(long[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
long a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
}
static class MathUtils {
static long[] FIRST_PRIMES = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89 , 97 , 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051};
static long[] primes(int to) {
long[] all = new long[to + 1];
long[] primes = new long[to + 1];
all[1] = 1;
int primesLength = 0;
for (int i = 2; i <= to; i ++) {
if (all[i] == 0) {
primes[primesLength++] = i;
all[i] = i;
}
for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j]; j++) {
all[(int) (i * primes[j])] = primes[j];
}
}
return Arrays.copyOf(primes, primesLength);
}
static long modpow(long b, long e, long m) {
long result = 1;
while (e > 0) {
if ((e & 1) == 1) {
/* multiply in this bit's contribution while using modulus to keep
* result small */
result = (result * b) % m;
}
b = (b * b) % m;
e >>= 1;
}
return result;
}
static long submod(long x, long y, long m) {
return (x - y + m) % m;
}
}
}
/*
5 6
1 4
2 3
3 4
4 5
5 2
3 5
5 8
1 2
2 3
1 3
4 3
3 4
4 1
4 5
5 1
*/
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
// practice with rainboy
import java.io.*;
import java.util.*;
public class CF338A extends PrintWriter {
CF338A() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF338A o = new CF338A(); o.main(); o.flush();
}
static final int MD = 1000000009;
long power(int a, int k) {
if (k == 0)
return 1;
long p = power(a, k / 2);
p = p * p % MD;
if (k % 2 == 1)
p = p * a % MD;
return p;
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int z = n - m;
if (z >= (n + k - 1) / k) {
println(m);
return;
}
int d = (n - z * k) / k;
println(((power(2, d + 1) - 2 + MD) * k + m - d * k) % MD);
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class B {
static int n,t[],g[],MOD=(int)1e9+7;
static int [][][]memo1,memo2[],memo3[];
static int dp1(int idx,int remCnt,int remSum) {
if(remCnt==0)
return remSum==0?1:0;
if(remSum==0 || idx==n)
return 0;
if(memo1[idx][remCnt][remSum]!=-1)
return memo1[idx][remCnt][remSum];
int ans=dp1(idx+1,remCnt,remSum);
if(g[idx]==0 && t[idx]<=remSum)
{
ans+=dp1(idx+1,remCnt-1,remSum-t[idx]);
if(ans>=MOD)
ans-=MOD;
}
return memo1[idx][remCnt][remSum]=ans;
}
static int dp2(int idx,int remCnt1,int remCnt2,int remSum) {
int all=remCnt1+remCnt2;
if(all==0)
return remSum==0?1:0;
if(idx==n || remSum==0)
return 0;
if(memo2[idx][remCnt1][remCnt2][remSum]!=-1)
return memo2[idx][remCnt1][remCnt2][remSum];
int ans=dp2(idx+1,remCnt1,remCnt2,remSum);
if(t[idx]<=remSum) {
if(g[idx]==1 && remCnt1>0)
ans+=dp2(idx+1,remCnt1-1,remCnt2,remSum-t[idx]);
else if(g[idx]==2 && remCnt2>0)
ans+=dp2(idx+1,remCnt1,remCnt2-1,remSum-t[idx]);
}
return memo2[idx][remCnt1][remCnt2][remSum]=ans;
}
private static int dp3(int cnt0, int cnt1, int cnt2,int last) {
if(cnt0+cnt1+cnt2==0)
return 1;
if(memo3[last][cnt0][cnt1][cnt2]!=-1)
return memo3[last][cnt0][cnt1][cnt2];
long ans=0;
if(cnt0>0 && last!=0)
ans+=dp3(cnt0-1,cnt1,cnt2,0);
if(cnt1>0 && last!=1)
ans+=dp3(cnt0,cnt1-1,cnt2,1);
if(cnt2>0 && last!=2)
ans+=dp3(cnt0,cnt1,cnt2-1,2);
return memo3[last][cnt0][cnt1][cnt2]=(int) (ans%MOD);
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
n=sc.nextInt();
int []fac=new int [n+1];
t=new int [n];
g=new int [n];
int []cnt=new int [3];
fac[0]=1;
for(int i=1;i<=n;i++)
fac[i]=(int) (i*1L*fac[i-1]%MOD);
int T=sc.nextInt();
for(int i=0;i<n;i++) {
t[i]=sc.nextInt();
g[i]=sc.nextInt()-1;
cnt[g[i]]++;
}
memo1=new int [n][cnt[0]+1][T+1];
memo2=new int [n][cnt[1]+1][cnt[2]+1][T+1];
memo3=new int [4][cnt[0]+1][cnt[1]+1][cnt[2]+1];
for(int i=0;i<n;i++) {
for(int j=0;j<=cnt[0];j++)
Arrays.fill(memo1[i][j], -1);
for(int j=0;j<=cnt[1];j++)
for(int k=0;k<=cnt[2];k++)
Arrays.fill(memo2[i][j][k], -1);
}
for(int i=0;i<4;i++)
for(int j=0;j<=cnt[0];j++)
for(int k=0;k<=cnt[1];k++)
Arrays.fill(memo3[i][j][k], -1);
int ans=0;
for(int cnt0=0;cnt0<=cnt[0];cnt0++)
for(int sum0=0;sum0<=T;sum0++)
for(int cnt1=0;cnt1<=cnt[1];cnt1++)
for(int cnt2=0;cnt2<=cnt[2];cnt2++) {
long ways= dp1(0,cnt0,sum0)*1L*dp2(0,cnt1,cnt2,T-sum0)%MOD;
ways=ways*dp3(cnt0,cnt1,cnt2,3)%MOD;
ways*=fac[cnt0];
ways%=MOD;
ways*=fac[cnt1];
ways%=MOD;
ways*=fac[cnt2];
ways%=MOD;
ans+=ways;
if(ans>=MOD)
ans-=MOD;
}
out.println(ans);
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
}
|
cubic
|
1185_G2. Playlist for Polycarp (hard version)
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.stream.IntStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author mikit
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
LightScanner in = new LightScanner(inputStream);
LightWriter out = new LightWriter(outputStream);
APaintTheNumbers solver = new APaintTheNumbers();
solver.solve(1, in, out);
out.close();
}
static class APaintTheNumbers {
public void solve(int testNumber, LightScanner in, LightWriter out) {
// out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP);
int n = in.ints();
int[] a = in.ints(n);
IntroSort.sort(a);
boolean[] done = new boolean[n];
int ans = 0;
for (int i = 0; i < n; i++) {
if (done[i]) continue;
int d = a[i];
ans++;
for (int j = 0; j < n; j++) {
if (a[j] % d == 0) {
done[j] = true;
}
}
}
out.ans(ans).ln();
}
}
static class IntroSort {
private static int INSERTIONSORT_THRESHOLD = 16;
private IntroSort() {
}
static void sort(int[] a, int low, int high, int maxDepth) {
while (high - low > INSERTIONSORT_THRESHOLD) {
if (maxDepth-- == 0) {
HeapSort.sort(a, low, high);
return;
}
int cut = QuickSort.step(a, low, high);
sort(a, cut, high, maxDepth);
high = cut;
}
InsertionSort.sort(a, low, high);
}
public static void sort(int[] a) {
if (a.length <= INSERTIONSORT_THRESHOLD) {
InsertionSort.sort(a, 0, a.length);
} else {
sort(a, 0, a.length, 2 * BitMath.msb(a.length));
}
}
}
static final class ArrayUtil {
private ArrayUtil() {
}
public static void swap(int[] a, int x, int y) {
int t = a[x];
a[x] = a[y];
a[y] = t;
}
}
static class LightScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public LightScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public String string() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return tokenizer.nextToken();
}
public int ints() {
return Integer.parseInt(string());
}
public int[] ints(int length) {
return IntStream.range(0, length).map(x -> ints()).toArray();
}
}
static final class BitMath {
private BitMath() {
}
public static int count(int v) {
v = (v & 0x55555555) + ((v >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
v = (v & 0x0f0f0f0f) + ((v >> 4) & 0x0f0f0f0f);
v = (v & 0x00ff00ff) + ((v >> 8) & 0x00ff00ff);
v = (v & 0x0000ffff) + ((v >> 16) & 0x0000ffff);
return v;
}
public static int msb(int v) {
if (v == 0) {
throw new IllegalArgumentException("Bit not found");
}
v |= (v >> 1);
v |= (v >> 2);
v |= (v >> 4);
v |= (v >> 8);
v |= (v >> 16);
return count(v) - 1;
}
}
static class HeapSort {
private HeapSort() {
}
private static void heapfy(int[] a, int low, int high, int i, int val) {
int child = 2 * i - low + 1;
while (child < high) {
if (child + 1 < high && a[child] < a[child + 1]) {
child++;
}
if (val >= a[child]) {
break;
}
a[i] = a[child];
i = child;
child = 2 * i - low + 1;
}
a[i] = val;
}
static void sort(int[] a, int low, int high) {
for (int p = (high + low) / 2 - 1; p >= low; p--) {
heapfy(a, low, high, p, a[p]);
}
while (high > low) {
high--;
int pval = a[high];
a[high] = a[low];
heapfy(a, low, high, low, pval);
}
}
}
static class LightWriter implements AutoCloseable {
private final Writer out;
private boolean autoflush = false;
private boolean breaked = true;
public LightWriter(Writer out) {
this.out = out;
}
public LightWriter(OutputStream out) {
this(new BufferedWriter(new OutputStreamWriter(out, Charset.defaultCharset())));
}
public LightWriter print(char c) {
try {
out.write(c);
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter print(String s) {
try {
out.write(s, 0, s.length());
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter ans(String s) {
if (!breaked) {
print(' ');
}
return print(s);
}
public LightWriter ans(int i) {
return ans(Integer.toString(i));
}
public LightWriter ln() {
print(System.lineSeparator());
breaked = true;
if (autoflush) {
try {
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
return this;
}
public void close() {
try {
out.close();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
static class QuickSort {
private QuickSort() {
}
private static void med(int[] a, int low, int x, int y, int z) {
if (a[z] < a[x]) {
ArrayUtil.swap(a, low, x);
} else if (a[y] < a[z]) {
ArrayUtil.swap(a, low, y);
} else {
ArrayUtil.swap(a, low, z);
}
}
static int step(int[] a, int low, int high) {
int x = low + 1, y = low + (high - low) / 2, z = high - 1;
if (a[x] < a[y]) {
med(a, low, x, y, z);
} else {
med(a, low, y, x, z);
}
int lb = low + 1, ub = high;
while (true) {
while (a[lb] < a[low]) {
lb++;
}
ub--;
while (a[low] < a[ub]) {
ub--;
}
if (lb >= ub) {
return lb;
}
ArrayUtil.swap(a, lb, ub);
lb++;
}
}
}
static class InsertionSort {
private InsertionSort() {
}
static void sort(int[] a, int low, int high) {
for (int i = low; i < high; i++) {
for (int j = i; j > low && a[j - 1] > a[j]; j--) {
ArrayUtil.swap(a, j - 1, j);
}
}
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.*;
public class ehab4 {
public static void main( String[] args ) {
Scanner in = new Scanner( System.in );
int a = 0, b = 0;
System.out.println( "? 0 0 " );
System.out.flush();
int c = in.nextInt();
for ( int i = 29; i >= 0; i-- ) {
System.out.println( "? " + ( a + ( 1 << i ) ) + " " + b );
System.out.flush();
int q1 = in.nextInt();
System.out.println( "? " + a + " " + ( b + ( 1 << i ) ) );
System.out.flush();
int q2 = in.nextInt();
if ( q1 == q2 ) {
if ( c == 1 )
a += ( 1 << i );
else if ( c == -1 )
b += ( 1 << i );
c = q1;
}
else if ( q1 == -1 ) {
a += ( 1 << i );
b += ( 1 << i );
}
else if ( q1 == -2 )
return;
}
System.out.println( "! " + a + " " + b );
System.out.flush();
}
}
|
logn
|
1088_D. Ehab and another another xor problem
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class C {
/**
* @param args
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer= new StringTokenizer(br.readLine());
BigInteger left = new BigInteger(tokenizer.nextToken());
BigInteger right= new BigInteger(tokenizer.nextToken());
BigInteger val= (right.subtract(left)).add(new BigInteger(""+1));
if(val.intValue()<3){
System.out.println(-1);
return;
}
BigInteger a, b, c;
BigInteger i=left;
while(i.intValue()<=right.intValue()){
BigInteger temp1=i; //a
BigInteger temp2= i.add(new BigInteger(""+1));//b
BigInteger j=temp2.add(new BigInteger(""+1));
while(j.intValue()<=right.intValue()){
BigInteger b1= temp2;
BigInteger b2 =j;
BigInteger b3 = temp1;
BigInteger gcd= b1.gcd(b2);
if(gcd.intValue()==1){
BigInteger gcd2 =b2.gcd(b3);
if(gcd2.intValue() !=1){
a=b3;
b= b1;
c= b2;
System.out.print(a+" "+b+" "+c+" ");
System.out.println();
return ;
}
}
j=j.add(new BigInteger(""+1));
}
i=i.add(new BigInteger(""+1));
}
System.out.println(-1);
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
private static StringTokenizer st;
private static BufferedReader br;
public static long MOD = 1000000007;
public static void print(Object x) {
System.out.println(x + "");
}
public static String join(Collection<?> x, String space) {
if (x.size() == 0) return "";
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object elt : x) {
if (first) first = false;
else sb.append(space);
sb.append(elt);
}
return sb.toString();
}
public static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
st = new StringTokenizer(line.trim());
}
return st.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
// Finds smallest rectangle containing something along 1 dimension.
public static long[] search(long[] none, long[] some) throws IOException {
long[] med = new long[4];
for (int i = 0; i < 4; i++) {
if (Math.abs(none[i] - some[i]) == 1) {
return some;
}
med[i] = (none[i] + some[i]) / 2;
}
int ans = query(med);
if (ans > 0) return search(none, med);
else return search(med, some);
}
public static int query(long[] query) throws IOException {
print("? " + arr(query));
System.out.flush();
int ans = nextInt();
if (contains(query)) ans -= 1;
return ans;
}
public static boolean contains(long[] search) {
if (rect1 == null) return false;
if (search[0] > rect1[0]) return false;
if (search[1] > rect1[1]) return false;
if (search[2] < rect1[2]) return false;
if (search[3] < rect1[3]) return false;
return true;
}
public static String arr(long[] x) {
return x[0] + " " + x[1] + " " + x[2] + " " + x[3];
}
public static long[] find() throws IOException {
long[] d0 = {1, 1, 1, 1};
long[] some = {1, 1, n, n};
if (query(d0) > 0) {
return d0;
}
// print(" " + arr(some));
long[] none = {1, 1, n, 1};
if (query(none) > 0) some = none;
else some = search(none, some);
// print(" " + arr(some));
none = new long[] {1, 1, 1, some[3]};
if (query(none) > 0) some = none;
else some = search(none, some);
// print(" " + arr(some));
none = new long[] {1, some[3], some[2], some[3]};
if (query(none) > 0) some = none;
else some = search(none, some);
// print(" " + arr(some));
none = new long[] {some[2], some[1], some[2], some[3]};
if (query(none) > 0) some = none;
else some = search(none, some);
return some;
}
public static long[] rect1 = null;
public static long[] rect2 = null;
public static long n;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
n = nextLong();
rect1 = find();
rect2 = find();
print("! " + arr(rect1) + " "
+ arr(rect2));
System.out.flush();
}
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class B implements Runnable {
// leave empty to read from stdin/stdout
private static final String TASK_NAME_FOR_IO = "";
// file names
private static final String FILE_IN = TASK_NAME_FOR_IO + ".in";
private static final String FILE_OUT = TASK_NAME_FOR_IO + ".out";
BufferedReader in;
PrintWriter out;
StringTokenizer tokenizer = new StringTokenizer("");
public static void main(String[] args) {
new Thread(new B()).start();
}
private void solve() throws IOException {
long n = nextLong();
long k = nextLong();
n--;
k--;
long answer = 0;
while (n > 0 && k >= 1) {
if (k > 2000) {
long step1000 = (k + (k - 999)) * 500;
if (n - step1000 >= 0) {
n -= step1000;
answer += 1000;
k -= 1000;
continue;
}
}
if (n - k >= 0) {
n -= k;
answer++;
}
k--;
k = Math.min(n, k);
}
if (n == 0) {
out.println(answer);
} else {
out.println(-1);
}
}
public void run() {
long timeStart = System.currentTimeMillis();
boolean fileIO = TASK_NAME_FOR_IO.length() > 0;
try {
if (fileIO) {
in = new BufferedReader(new FileReader(FILE_IN));
out = new PrintWriter(new FileWriter(FILE_OUT));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
}
solve();
in.close();
out.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
long timeEnd = System.currentTimeMillis();
if (fileIO) {
System.out.println("Time spent: " + (timeEnd - timeStart) + " ms");
}
}
private String nextToken() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private BigInteger nextBigInt() throws IOException {
return new BigInteger(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Proj implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer str;
public void solve() throws IOException {
long l = nextLong();
long r = nextLong();
int g = 0;
long x = l ^ r;
long i = 1;
while (x >= i) {
i = i * 2;
}
if (x >= i) {
out.println(x);
} else
out.println(i - 1);
}
public String nextToken() throws IOException {
while (str == null || !str.hasMoreTokens()) {
str = new StringTokenizer(in.readLine());
}
return str.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (IOException e) {
}
}
public static void main(String[] args) {
new Thread(new Proj()).start();
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class A {
ArrayList<Integer> list = new ArrayList<Integer>();
boolean valid(int n) {
Queue<Integer> q = new LinkedList<Integer>();
q.add(4);
q.add(7);
int crnt;
while(!q.isEmpty()) {
crnt = q.poll();
if(n%crnt == 0) return true;
if ( crnt*10 + 4 <= 1000 ) q.add(crnt*10 + 4);
if ( crnt*10 + 7 <= 1000 ) q.add(crnt*10 + 7);
}
return false;
}
void dfs(int n){
if(n>1000)return;
if(n!=0)list.add(n);
n = n*10;
dfs(n+4);
dfs(n+7);
}
void run() {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
if (valid(n)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
public static void main(String[] args) {
new A().run();
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
/*static long power(long a,long b,long m)
{
if(b==0)
return 1;
if((b&1)==0)
return power((a*a)%m,b/2,m);
else
return (a*power((a*a)%m,b/2,m))%m;
}*/
/*
static int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
*/
public static void main (String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
PrintWriter p=new PrintWriter(System.out);
while(t-->0)
{
//StringTokenizer st=new StringTokenizer(br.readLine());
int n=Integer.parseInt(br.readLine());
String a[]=new String[n];
for(int i=0;i<n;i++)
{
a[i]=br.readLine();
}
String pre="1";
for(int i=1;i<n;i++)
{
if(a[i].equals("1"))
{
a[i]=pre+".1";
pre=a[i];
continue;
}
int li=pre.lastIndexOf('.');
while(li!=-1 && Integer.parseInt(pre.substring(li+1))+1!=Integer.parseInt(a[i]))
{
pre=pre.substring(0,li);
li=pre.lastIndexOf('.');
}
//li=pre.lastIndexOf('.');
if(li!=-1)
a[i]=pre.substring(0,li+1)+a[i];
pre=a[i];
}
for(int i=0;i<n;i++)
{
p.println(a[i]);
}
p.flush();
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class probC {
static int r;
static ArrayList<Circ> curr = new ArrayList<Circ>();
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
r = sc.nextInt();
int[] xC = new int[n];
for(int i = 0; i < n; i++)
xC[i] = sc.nextInt();
double ans[] = new double[n];
ans[0] = r;
curr.add(new Circ(xC[0], r));
for(int i = 1; i < n; i++) {
double max = r;
for(int k = 0; k < curr.size(); k++) {
double cur = curr.get(k).y+ Math.sqrt(4 * r*r - (xC[i]-curr.get(k).x)*(xC[i]-curr.get(k).x));
//System.out.println(cur + " " + max);
if(4 * r*r - (xC[i]-curr.get(k).x)*(xC[i]-curr.get(k).x) >= 0)
max = Math.max(cur, max);
}
ans[i] = max;
curr.add(new Circ(xC[i], max));
//System.out.println();
}
for(int i = 0; i < n; i++)
System.out.print(ans[i] + " ");
sc.close();
}
static class Circ {
double x, y;
public Circ(double a, double b) {
x=a;
y=b;
}
public boolean isNT(Circ b) {
double dist = Math.sqrt((x-b.x)*(x-b.x)+(y-b.y)*(y-b.y));
return dist > 2*r;
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Div2_489C {
static final long MOD = 1_000_000_007;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer inputData = new StringTokenizer(reader.readLine());
long st = Long.parseLong(inputData.nextToken());
if(st == 0) {
printer.println(0);
printer.close();
return;
}
st %= MOD;
long years = Long.parseLong(inputData.nextToken());
long[][] res = exp(years);
long ans = (res[0][0] * st % MOD * 2 % MOD + res[0][1] * (-1 + MOD) % MOD) % MOD;
printer.println(ans);
printer.close();
}
static long[][] exp(long pow) {
long[][] cBase = base;
long[][] res = { { 1, 0 }, { 0, 1 } };
while (pow != 0) {
if ((pow & 1) != 0) {
res = mult(res, cBase);
}
cBase = mult(cBase, cBase);
pow >>= 1;
}
return res;
}
static long[][] base = { { 2, 1 }, { 0, 1 } };
static long[][] mult(long[][] a, long[][] b) {
long[][] res = new long[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
res[i][j] = (a[i][0] * b[0][j] % MOD + a[i][1] * b[1][j] % MOD) % MOD;
}
}
return res;
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class first
{
int max(int a1,int a2,int a3)
{
int max=a1;
if(a2>=max)
max=a2;
if(a3>=max)
max = a3;
return max;
}
public static void main(String[] args)
{
int num=0;
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
int num2 = num/10;
int num3 = num%10;
int num4 = (num2/10)*10+num3;
first fs = new first();
int result = fs.max(num,num2,num4);
System.out.println(result);
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigInteger;
public class stacks {
public static void main(String[] args) throws Exception {
FastIO sc = new FastIO(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
long remove = 0;
int[] heights = new int[n+1];
for(int i = 0; i < n; i++) {
heights[i] = sc.nextInt();
remove += heights[i];
}
Arrays.sort(heights);
//System.out.println(Arrays.toString(heights));
long keep = 0;
for(int i = n; i> 0; i--) {
if(heights[i-1] >= heights[i]) {
heights[i-1] = heights[i]-1;
}
keep += heights[i] - heights[i-1];
}
//System.out.println(Arrays.toString(heights));
pw.println(remove - keep);
pw.close();
}
static class FastIO {
//Is your Fast I/O being bad?
InputStream dis;
byte[] buffer = new byte[1 << 17];
int pointer = 0;
public FastIO(String fileName) throws Exception {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws Exception {
dis = is;
}
int nextInt() throws Exception {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
long nextLong() throws Exception {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
byte nextByte() throws Exception {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
String next() throws Exception {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
}
}
|
nlogn
|
1061_B. Views Matter
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
static final int MAX_N = 1000010;
static final int INF = 0x3f3f3f3f;
static final int mod = 1000000007;
public static void main(String[] args) throws IOException {
initReader(System.in);
// int T = nextInt();
// for (int i = 1; i <= T; i++)
solve();
pw.flush();
}
/*******************************************************************************************************************************/
public static void solve() throws IOException {
while (hasNext()) {
long n = nextLong() - 1;
long k = 1, x = 9;
while (n - k * x >= 0) {
n -= k * x;
k += 1;
x *= 10;
}
if (n == 0)
pw.println(1);
else {
long num = x / 9 + n / k;
String s = String.valueOf(num);
pw.println(s.charAt((int) (n % k)));
}
}
}
/*******************************************************************************************************************************/
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter pw;
public static void initReader(InputStream input) throws IOException {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
// reader = new BufferedReader(new FileReader("ate.in"));
// tokenizer = new StringTokenizer("");
// printWriter = new PrintWriter(new BufferedWriter(new FileWriter("ate.out")));
}
public static boolean hasNext() {
try {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
}
return true;
}
public static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
return null;
}
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static char nextChar() throws IOException {
return next().charAt(0);
}
static class Pair {
char first;
boolean second;
public Pair(char first, boolean second) {
// TODO Auto-generated constructor stub
this.first = first;
this.second = second;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "(" + this.first + ", " + this.second + ")";
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.util.Set;
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 prakharjain
*/
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();
}
static class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int d = in.nextInt();
int[] a = new int[n];
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int ans = 2;
for (int i = 1; i < n; i++) {
if (a[i] - a[i - 1] == 2 * d) {
ans++;
} else if (a[i] - a[i - 1] > 2 * d) {
ans += 2;
}
}
out.println(ans);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void 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 static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
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 interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
int n;
int sepX;
int sepY;
int x1;
int y1;
int x2;
int y2;
FastScanner in;
PrintWriter out;
public void solve(int testNumber, FastScanner in, PrintWriter out) {
this.in = in;
this.out = out;
n = in.nextInt();
int x11, x12, y11, y12;
int x21, x22, y21, y22;
findSeparatingX();
findSeparatingY();
if (sepX >= 0) {
locate(0, 0, sepX, n);
x11 = x1;
y11 = y1;
x12 = x2;
y12 = y2;
locate(sepX, 0, n, n);
x21 = x1;
y21 = y1;
x22 = x2;
y22 = y2;
} else {
locate(0, 0, n, sepY);
x11 = x1;
y11 = y1;
x12 = x2;
y12 = y2;
locate(0, sepY, n, n);
x21 = x1;
y21 = y1;
x22 = x2;
y22 = y2;
}
++x11;
++x21;
++y11;
++y21;
out.println("! " + x11 + " " + y11 + " " + x12 + " " + y12 + " " + +x21 + " " + y21 + " " + x22 + " " + y22);
out.flush();
}
void locate(int x1, int y1, int x2, int y2) {
for (int step = 15; step >= 0; step--) {
int h = 1 << step;
if (query(x1 + h, y1, x2, y2) > 0) {
x1 += h;
}
if (query(x1, y1, x2 - h, y2) > 0) {
x2 -= h;
}
if (query(x1, y1 + h, x2, y2) > 0) {
y1 += h;
}
if (query(x1, y1, x2, y2 - h) > 0) {
y2 -= h;
}
}
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
private void findSeparatingX() {
int l = 0;
int r = n;
while (r - l > 1) {
int m = (l + r) / 2;
if (query(0, 0, m, n) == 0) {
l = m;
} else {
r = m;
}
}
sepX = -1;
if (query(0, 0, r, n) == 1 && query(r, 0, n, n) == 1) {
sepX = r;
}
}
private void findSeparatingY() {
int l = 0;
int r = n;
while (r - l > 1) {
int m = (l + r) / 2;
if (query(0, 0, n, m) == 0) {
l = m;
} else {
r = m;
}
}
sepY = -1;
if (query(0, 0, n, r) == 1 && query(0, r, n, n) == 1) {
sepY = r;
}
}
int query(int x1, int y1, int x2, int y2) {
if (x1 >= x2 || y1 >= y2) {
return 0;
}
++x1;
++y1;
out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
out.flush();
return in.nextInt();
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class A {
public static void main(String[] args) {
Scanner input = new Scanner();
StringBuilder output = new StringBuilder();
int n = input.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = input.nextInt();
}
Arrays.sort(a);
boolean[] colored = new boolean[n];
int colors = 0;
for (int i = 0; i < n; i++) {
if (!colored[i]) {
colors ++;
colored[i] = true;
for (int j = i+1; j < n; j++) {
if (a[j] % a[i] == 0) {
colored[j] = true;
}
}
}
}
System.out.println(colors);
}
private static class Scanner {
BufferedReader br; StringTokenizer st;
public Scanner(Reader in) { br = new BufferedReader(in); }
public Scanner() { this(new InputStreamReader(System.in)); }
String next() {
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine());
} catch (IOException e) { e.printStackTrace(); } }
return st.nextToken(); }
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String readNextLine() {
String str = "";
try { str = br.readLine();
} catch (IOException e) { e.printStackTrace(); }
return str; }
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); }
return a; }
long[] readLongArray(int n) {
long[] a = new long[n];
for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); }
return a; }
} // end Scanner
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
//Template with FastScanner
// jzzhao
import java.util.*;
import java.io.*;
public class Solution {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
//int tc = sc.ni();
int tc = 1;
for (int rep = 0; rep < tc; rep++) {
solve(sc,pw);
//pw.println(solve(sc,pw));
}
pw.close();
}
/*
FS Methods:
- next(): next element in string
- nextLine(): nextline in string
- ni(): next Integer
- nd(): next Double
- nl(): next Long
- intArray(n):
- longArray(n):
- to2di(m,n):
- to2dl(m,n):
*/
public static void solve(FastScanner sc, PrintWriter pw) {
int n = sc.ni();
int m = sc.ni();
int k = sc.ni();
int[][] arr = sc.to2di(n,m-1);
int[][] arr2 = sc.to2di(n-1,m);
if(k%2==1){
String s ="";
for(int j = 0;j<m;j++){
s+="-1";
if(j!=m-1){
s+=" ";
}
}
for(int i = 0;i<n;i++){
pw.println(s);
}
return;
}
Integer[][][] dp = new Integer[n][m][k+1];
// edge info
// for(int i= 0;i<n;i++){
// for(int j = 0;j<m-1;j++){
// int l = i*1000+j;
// int r = i*1000+j+1;
// String cur = l+" "+r;
// String cur2 = r+" "+l;
// map.put(cur,arr[i][j]);
// map.put(cur2,arr[i][j]);
// }
// }
// for(int i= 0;i<n-1;i++){
// for(int j = 0;j<m;j++){
// int l = i*1000+j;
// int r = (i+1)*1000+j;
// String cur = l+" "+r;
// String cur2 = r+" "+l;
// map.put(cur,arr2[i][j]);
// map.put(cur2,arr2[i][j]);
// }
// }
//dp fill
for(int i= 0;i<n;i++){
for(int j = 0;j<m;j++){
fill(dp,i,j,k,n,m,arr,arr2);
}
}
for(int i= 0;i<n;i++){
String s = "";
for(int j = 0;j<m;j++){
s+=dp[i][j][k];
if(j!=m-1){
s+=" ";
}
}
pw.println(s);
}
}
public static int fill(Integer[][][] dp, int x, int y, int k, int n,int m,int[][] arr, int[][] arr2){
if(dp[x][y][k]!=null){
return dp[x][y][k];
}
if(k==0){
dp[x][y][k]= 0;
return 0;
}
int min = Integer.MAX_VALUE;
if(x>0){
int curVal = 2*arr2[x-1][y]+fill(dp,x-1,y,k-2,n,m,arr,arr2);
min = Math.min(min,curVal);
}
if(y>0){
int curVal = 2*arr[x][y-1]+fill(dp,x,y-1,k-2,n,m,arr,arr2);
min = Math.min(min,curVal);
}
if(x<n-1){
int curVal = 2*arr2[x][y]+fill(dp,x+1,y,k-2,n,m,arr,arr2);
min = Math.min(min,curVal);
}
if(y<m-1){
int curVal = 2*arr[x][y]+fill(dp,x,y+1,k-2,n,m,arr,arr2);
min = Math.min(min,curVal);
}
dp[x][y][k]=min;
return min;
}
/*
- The following are helping method so pls do not do anything to them.
*/
// public static int[][] to2d(Scanner scanner, int m, int n){
// int[][] ans = new int[m][n];
// for(int i = 0;i<m;i++){
// String[] r = scanner.nextLine().split("[ ]");
// for(int j = 0;j<n;j++){
// ans[i][j] = stoi(r[j]);
// }
// }
// return ans;
// }
// public static int[] toArray(Scanner scanner, int m){
// int[] ans = new int[m];
// String[] r = scanner.nextLine().split("[ ]");
// for(int i = 0;i<m;i++){
// ans[i] = stoi(r[i]);
// }
// return ans;
// }
public static void printArr(PrintWriter pw,int[] a){
for(int i = 0;i<a.length;i++){
pw.print(a[i]);
if(i!=a.length-1){
pw.print(" ");
}
}
pw.println();
}
public static void print2d(PrintWriter pw,int[][] a){
for(int j=0;j<a.length;j++){
for(int i = 0;i<a[j].length;i++){
pw.print(a[j][i]);
if(i!=a[j].length-1){
pw.print(" ");
}
}
pw.println(" ");
}
pw.println();
}
public static int stoi(String s){
return Integer.parseInt(s);
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[] intArray(int N) {
int[] ret = new int[N];
for (int i = 0; i < N; i++)
ret[i] = ni();
return ret;
}
int[][] to2di(int m, int n){
int[][] ans = new int[m][n];
for(int i = 0;i<m;i++){
String[] r = nextLine().split("[ ]");
for(int j = 0;j<n;j++){
ans[i][j] = Integer.parseInt(r[j]);
}
}
return ans;
}
long[][] to2dl(int m, int n){
long[][] ans = new long[m][n];
for(int i = 0;i<m;i++){
String[] r = nextLine().split("[ ]");
for(int j = 0;j<n;j++){
ans[i][j] = Long.parseLong(r[j]);
}
}
return ans;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N) {
long[] ret = new long[N];
for (int i = 0; i < N; i++)
ret[i] = nl();
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.util.Scanner;
public class R489C {
static long MOD=(long)1e9+7;
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
long n=scan.nextLong(), k=scan.nextLong();
if(n==0) {
System.out.println(0);
return;
}
long x=2*n-1;
long e=exp(2,k);
System.out.println((x%MOD*e%MOD+1)%MOD);
}
public static long exp(long x, long e) {
long res=1;
while (e>0) {
if(e%2==1) res=(res*x)%MOD;
e/=2;
x=(x*x)%MOD;
}
return res;
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class mainA {
public static PrintWriter out = new PrintWriter(System.out);
public static FastScanner enter = new FastScanner(System.in);
public static void main(String[] args) throws IOException {
solve();
out.close();
}
public static boolean[] was;
private static void solve() throws IOException{
int n=enter.nextInt();
int[] arr=new int[n];
was=new boolean[n];
for (int i = 0; i <n ; i++) {
arr[i]=enter.nextInt();
}
Arrays.sort(arr);
int ans=0;
for (int i = 0; i <n ; i++) {
if(was[i]) continue;
find(i, arr);
ans++;
}
out.println(ans);
}
public static void find (int num, int[] arr){
for (int i = num+1; i <arr.length ; i++) {
if(arr[i]%arr[num]==0) was[i]=true;
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer stok;
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return null;
}
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
char nextChar() throws IOException {
return (char) (br.read());
}
String nextLine() throws IOException {
return br.readLine();
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.*;
import java.io.*;
// Solution
public class Main
{
public static void main (String[] argv)
{
new Main();
}
boolean test = false;
final int MOD = 998244353;
public Main() {
FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
//FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in")));
final int N = 50; //big enough
long[] f = new long[N];
int maxN = 50;
f[0] = 0;
for (int i = 1; i < N; i++) {
if (Long.MAX_VALUE / 4 <= f[i-1]) {
maxN = i - 1;
break;
}
f[i] = f[i-1] * 4 + 1;
}
long[] a = new long[N];
long[] b = new long[N];
int nt = in.nextInt();
for (int ii = 1; ii <= nt; ii++) {
int n = in.nextInt();
long k = in.nextLong();
if (k == 0) {
System.out.println("YES " + n);
continue;
}
if (n - 1> maxN || k <= 1 + f[n-1]) {
System.out.println("YES " + (n - 1));
continue;
}
if (n - 1 == maxN) {
System.out.println("YES " + (n - 2));
continue;
}
// now: n <= maxN
if (k > f[n]) {
System.out.println("NO");
continue;
}
if (n == 2) {
if (k==3) System.out.println("NO");
else System.out.println("YES 0");
continue;
}
a[1] = 1;
b[1] = f[n-1];
int ret = 0;
for (int i = 2; i <= n; i++) {
a[i] = a[i-1] + (1L << i) - 1;
b[i] = b[i-1] + (2 * (1L << i) - 3) * f[n-i];
if (a[i] + b[i] >= k) {
ret = n - i;
break;
}
}
System.out.println("YES " + ret);
}
}
private int dist(int x, int y, int xx, int yy) {
return abs(x - xx) + abs(y - yy);
}
private boolean less(int x, int y, int xx, int yy) {
return x < xx || y > yy;
}
private int mul(int x, int y) {
return (int)(1L * x * y % MOD);
}
private int add(int x, int y) {
return (x + y) % MOD;
}
private int nBit1(int v) {
int v0 = v;
int c = 0;
while (v != 0) {
++c;
v = v & (v - 1);
}
return c;
}
private long abs(long v) {
return v > 0 ? v : -v;
}
private int abs(int v) {
return v > 0 ? v : -v;
}
private int common(int v) {
int c = 0;
while (v != 1) {
v = (v >>> 1);
++c;
}
return c;
}
private void reverse(char[] a, int i, int j) {
while (i < j) {
swap(a, i++, j--);
}
}
private void swap(char[] a, int i, int j) {
char t = a[i];
a[i] = a[j];
a[j] = t;
}
private int gcd(int x, int y) {
if (y == 0) return x;
return gcd(y, x % y);
}
private long gcd(long x, long y) {
if (y == 0) return x;
return gcd(y, x % y);
}
private int max(int a, int b) {
return a > b ? a : b;
}
private long max(long a, long b) {
return a > b ? a : b;
}
private int min(int a, int b) {
return a > b ? b : a;
}
private long min(long a, long b) {
return a > b ? b : a;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader(BufferedReader in)
{
br = in;
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
String line = br.readLine();
if (line == null || line.length() == 0) return "";
st = new StringTokenizer(line);
}
catch (IOException e)
{
return "";
//e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
return "";
//e.printStackTrace();
}
return str;
}
}
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
public static void main(String[] args)throws Throwable {
MyScanner sc=new MyScanner();
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
int d=sc.nextInt();
int [] a=new int [n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
int ans=2;
for(int i=0;i<n-1;i++){
if(a[i+1]-a[i]<2*d)
continue;
if(a[i+1]-a[i]==2*d)
ans++;
else
ans+=2;
}
pw.println(ans);
pw.flush();
pw.close();
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {e.printStackTrace();}}
return st.nextToken();}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
String nextLine(){String str = "";
try {str = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return str;}
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.util.Scanner;
public class HelloWorld
{
public static void main (String args [])
{
Scanner read = new Scanner(System.in);
int n = read.nextInt();
int n1 = n; boolean q = true;
while (n1 > 0)
{
if (n % n1 == 0)
{
if (check(n1))
{
System.out.print("YES");
q = false;
break;
}
}
n1--;
}
if (q) System.out.print("NO");
}
public static boolean check (int n)
{
int n1 = n;
while (n1 != 0)
{
if (n1 % 10 != 4 && n1 % 10 != 7) return false;
n1 /= 10;
}
return true;
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.StringTokenizer;
public class Main{
public long power(long x, long y, long p)
{
long res = 1;
while (y > 0)
{
if((y & 1)==1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
Main mm=new Main();
long x=sc.nextLong();
long k=sc.nextLong();
if(x==0) {
System.out.println(0);
}
else {
long temp=mm.power(2, k, 1000000007);
long temp1=(2*x-1)%(1000000007);
long temp3=(temp1*temp)%(1000000007);
System.out.println((temp3+1)%1000000007);
}
}
}
class trienode{
trienode[] next=new trienode[26];
int count;
char value;
boolean last;
trienode() {
this.value='0';
this.count=0;
}
trienode(char x) {
this.value=x;
this.count=1;
}
}
class trie{
trienode root=new trienode();
public void insert(String s) {
trienode temp=root;
int length=s.length();
for(int i=0;i<length;i++) {
char c=s.charAt(i);
int index=c-'a';
if(temp.next[index]==null) {
temp.next[index]=new trienode(c);
}
else {
temp.next[index].count++;
}
if(i==length-1) {
temp.next[index].last=true;
}
temp=temp.next[index];
}
}
public String find(String s) {
trienode temp=root;
String ans="";
int pos=0;
char c=s.charAt(pos);
int index=c-'a';
while(temp.next[index]!=null) {
temp=temp.next[index];
ans+=temp.value;
if(pos==s.length()-1) {
break;
}
c=s.charAt(++pos);
index=c-'a';
}
while(temp.last!=true) {
int position=-1;
for(int i=0;i<26;i++) {
if(temp.next[i]!=null) {
ans+=temp.next[i].value;
position=i+0;
break;
}
}
temp=temp.next[position];
}
return ans;
}
}
class node{
int index;
int a;
int b;
node(int index,int a,int b){
this.a=a;
this.b=b;this.index=index;
}
}
class comp implements Comparator<node>{
public int compare(node n1,node n2) {
if(n1.b>n2.b) {
return 1;
}
else if(n1.b<n2.b) {
return -1;
}
else {
return 0;
}
}
}
class cc implements Comparator<node>{
public int compare(node n1,node n2) {
if(n1.index>n2.index) {
return 1;
}
else if(n1.index<n2.index) {
return -1;
}
else {
return 0;
}
}
}
/** Class for buffered reading int and double values */
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.Scanner;
public class pillar {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[200005];
for (int i=1;i<=n;i++)
a[i]=sc.nextInt();
for (int i=2;i<n;i++)
if (a[i-1]>a[i]&&a[i]<a[i+1]) {
System.out.println("NO");
return;
}
System.out.println("YES");
}
}
|
linear
|
1197_B. Pillars
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
public class palin {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(System.out);
Scanner scan = new Scanner(System.in);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
if (n >= 0) {
out.print(n);
return;
}
if (n / 10 >= (n / 100) * 10 + n % 10) {
out.print(n / 10);
return;
}
out.print((n / 100) * 10 + n % 10);
}
}
class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class E implements Runnable {
public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();}
int n, m;
char[] str;
int[][] occs, cost;
int[] dp;
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
//where's my 420??? :(
n = fs.nextInt(); m = fs.nextInt();
byte[] str = fs.next().getBytes();
int[] occs = new int[1<<m];
for(int i = 0; i < n-1; i++) {
int l1 = str[i] - 'a';
int l2 = str[i+1] - 'a';
occs[(1<<l1) | (1<<l2)]++;
occs[(1<<l2) | (1<<l1)]++;
}
//cost[mask][v] = numPairs with v for some all bits on in mask
int all = (1<<m)-1;
cost = new int[m][1<<m];
for(int i = 0; i < m; i++) {
for(int mask = 1; mask < all; mask++) {
if(((1<<i)&mask) > 0) continue;
int lb = mask & (-mask);
int trail = Integer.numberOfTrailingZeros(lb);
int nmask = mask ^ lb;
cost[i][mask] = cost[i][nmask]+occs[1<<i | 1<<trail];
}
}
dp = new int[1<<m];
for(int mask = dp.length-2; mask >= 0; mask--) {
int addOn = 0;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
addOn += cost[nxt][mask];
}
int res = oo;
for(int nxt = 0; nxt < m; nxt++) {
if(((1<<nxt)&mask) > 0) continue;
int ret = addOn+dp[mask | (1<<nxt)];
res = min(res, ret);
}
dp[mask] = res;
}
System.out.println(dp[0]>>1);
out.close();
}
int oo = (int)1e9;
int min(int a, int b) {
if(a < b) return a;
return b;
}
class FastScanner {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public 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);
}
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
}
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
//package contests.CF1019;
import java.io.*;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int half = n/2;
pw.println("? 1");
pw.flush();
int a = sc.nextInt();
pw.println("? " + (1+half));
pw.flush();
int b = sc.nextInt();
if(a - b == 0){
pw.println("! 1");
}
else
if((a - b)%2 != 0)
{
pw.println("! -1");
}else{
boolean greater = a > b;
int lo = 1;
int hi = half;
boolean ans = false;
while(lo <= hi){
int mid = (lo + hi) /2;
pw.println("? " + mid);
pw.flush();
a = sc.nextInt();
pw.println("? " + (mid+half));
pw.flush();
b = sc.nextInt();
if(a == b){
pw.println("! " + mid);
ans = true;
break;
}
if(a > b != greater){
hi = mid-1;
}else{
lo = mid+1;
greater = a>b;
}
}
if(!ans){
pw.println("! -1");
}
}
pw.flush();
pw.close();
}
static int[][] packD(int n, int[] from, int[] to) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int f : from) if(f != -1) p[f]++;
for (int i = 0; i < n; i++) g[i] = new int[p[i]];
for (int i = 0; i < from.length; i++) if(from[i] != -1) {g[from[i]][--p[from[i]]] = to[i];}
return g;
}
static void shuffle(int[] a)
{
int n = a.length;
for(int i = 0; i < n; i++)
{
int r = i + (int)(Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
static class Scanner
{
StringTokenizer st; BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s)));}
public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready();}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
// upsolve with rainboy
import java.io.*;
import java.util.*;
public class CF1187G extends PrintWriter {
CF1187G() { super(System.out); }
static class Scanner {
Scanner(InputStream in) { this.in = in; } InputStream in;
int k, l; byte[] bb = new byte[1 << 15];
byte getc() {
if (k >= l) {
k = 0;
try { l = in.read(bb); } catch (IOException e) { l = 0; }
if (l <= 0) return -1;
}
return bb[k++];
}
int nextInt() {
byte c = 0; while (c <= 32) c = getc();
int a = 0;
while (c > 32) { a = a * 10 + c - '0'; c = getc(); }
return a;
}
}
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1187G o = new CF1187G(); o.main(); o.flush();
}
static final int INF = 0x3f3f3f3f;
ArrayList[] aa_;
int n_, m_;
int[] pi, kk, bb;
int[] uu, vv, uv, cost, cost_;
int[] cc;
void init() {
aa_ = new ArrayList[n_];
for (int u = 0; u < n_; u++)
aa_[u] = new ArrayList<Integer>();
pi = new int[n_];
kk = new int[n_];
bb = new int[n_];
uu = new int[m_];
vv = new int[m_];
uv = new int[m_];
cost = new int[m_];
cost_ = new int[m_];
cc = new int[m_ * 2];
m_ = 0;
}
void link(int u, int v, int cap, int cos) {
int h = m_++;
uu[h] = u;
vv[h] = v;
uv[h] = u ^ v;
cost[h] = cos;
cc[h << 1 ^ 0] = cap;
aa_[u].add(h << 1 ^ 0);
aa_[v].add(h << 1 ^ 1);
}
boolean dijkstra(int s, int t) {
Arrays.fill(pi, INF);
pi[s] = 0;
TreeSet<Integer> pq = new TreeSet<>((u, v) -> pi[u] != pi[v] ? pi[u] - pi[v] : kk[u] != kk[v] ? kk[u] - kk[v] : u - v);
pq.add(s);
Integer first;
while ((first = pq.pollFirst()) != null) {
int u = first;
int k = kk[u] + 1;
ArrayList<Integer> adj = aa_[u];
for (int h_ : adj)
if (cc[h_] > 0) {
int h = h_ >> 1;
int p = pi[u] + ((h_ & 1) == 0 ? cost_[h] : -cost_[h]);
int v = u ^ uv[h];
if (pi[v] > p || pi[v] == p && kk[v] > k) {
if (pi[v] != INF)
pq.remove(v);
pi[v] = p;
kk[v] = k;
bb[v] = h_;
pq.add(v);
}
}
}
return pi[t] != INF;
}
void push(int s, int t) {
int c = INF;
for (int u = t, h_, h; u != s; u ^= uv[h]) {
h = (h_ = bb[u]) >> 1;
c = Math.min(c, cc[h_]);
}
for (int u = t, h_, h; u != s; u ^= uv[h]) {
h = (h_ = bb[u]) >> 1;
cc[h_] -= c; cc[h_ ^ 1] += c;
}
}
void push1(int s, int t) {
for (int u = t, h_, h; u != s; u ^= uv[h]) {
h = (h_ = bb[u]) >> 1;
cc[h_]--; cc[h_ ^ 1]++;
}
}
int edmonds_karp(int s, int t) {
System.arraycopy(cost, 0, cost_, 0, m_);
while (dijkstra(s, t)) {
push1(s, t);
for (int h = 0; h < m_; h++) {
int u = uu[h], v = vv[h];
if (pi[u] != INF && pi[v] != INF)
cost_[h] += pi[u] - pi[v];
}
}
int c = 0;
for (int h = 0; h < m_; h++)
c += cost[h] * cc[h << 1 ^ 1];
return c;
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int[] ii = new int[k];
for (int h = 0; h < k; h++)
ii[h] = sc.nextInt() - 1;
ArrayList[] aa = new ArrayList[n];
for (int i = 0; i < n; i++)
aa[i] = new ArrayList<Integer>();
for (int h = 0; h < m; h++) {
int i = sc.nextInt() - 1;
int j = sc.nextInt() - 1;
aa[i].add(j);
aa[j].add(i);
}
int t = n + k + 1;
n_ = n * t + 1;
m_ = k + (m * 2 * k + n) * (t - 1);
init();
for (int i = 0; i < n; i++) {
ArrayList<Integer> adj = aa[i];
for (int s = 0; s < t - 1; s++) {
int u = i * t + s;
for (int j : adj) {
int v = j * t + s + 1;
for (int x = 1; x <= k; x++)
link(u, v, 1, c + (x * 2 - 1) * d);
}
}
}
for (int i = 0; i < n; i++)
for (int s = 0; s < t - 1; s++) {
int u = i * t + s, v = u + 1;
link(u, v, k, i == 0 ? 0 : c);
}
for (int h = 0; h < k; h++)
link(n_ - 1, ii[h] * t + 0, 1, 0);
println(edmonds_karp(n_ - 1, 0 * t + t - 1));
}
}
|
cubic
|
1187_G. Gang Up
|
CODEFORCES
|
//package goodbye2017;
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 G {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
char[] s = ns().toCharArray();
int mod = 1000000007;
int m = 702;
long[] bases = new long[m+1];
bases[0] = 1;
for(int i = 1;i <= m;i++)bases[i] = bases[i-1] * 10 % mod;
// 10*700^3*10
long ans = 0;
for(int d = 9;d >= 1;d--){
int n = s.length;
long[] sum = new long[m]; // base
long[] num = new long[m]; // base
long esum = 0;
int ebase = 0;
for(int i = 0;i < n;i++){
long[] nsum = new long[m]; // base
long[] nnum = new long[m]; // base
for(int j = 0;j < m;j++){
for(int k = 0;k <= 9;k++){
if(k > d && j+1 < m){
nsum[j+1] += sum[j] * 10;
nsum[j+1] %= mod;
nnum[j+1] += num[j];
if(nnum[j+1] >= mod)nnum[j+1] -= mod;
}
if(k == d){
nsum[j] += sum[j] * 10 + num[j] * bases[j];
nsum[j] %= mod;
nnum[j] += num[j];
if(nnum[j] >= mod)nnum[j] -= mod;
}
if(k < d){
nsum[j] += sum[j];
if(nsum[j] >= mod)nsum[j] -= mod;
nnum[j] += num[j];
if(nnum[j] >= mod)nnum[j] -= mod;
}
}
}
for(int k = 0;k < s[i]-'0';k++){
if(k > d){
nsum[ebase+1] += esum * 10;
nsum[ebase+1] %= mod;
nnum[ebase+1] += 1;
if(nnum[ebase+1] >= mod)nnum[ebase+1] -= mod;
}
if(k == d){
nsum[ebase] += esum * 10 + bases[ebase];
nsum[ebase] %= mod;
nnum[ebase] += 1;
if(nnum[ebase] >= mod)nnum[ebase] -= mod;
}
if(k < d){
nsum[ebase] += esum;
if(nsum[ebase] >= mod)nsum[ebase] -= mod;
nnum[ebase] += 1;
if(nnum[ebase] >= mod)nnum[ebase] -= mod;
}
}
if(s[i]-'0' > d){
esum = esum * 10;
esum %= mod;
ebase++;
}else if(s[i]-'0' == d){
esum = esum * 10 + bases[ebase];
esum %= mod;
}
sum = nsum;
num = nnum;
}
long all = esum;
for(int j = 0;j < m;j++){
all += sum[j];
}
ans += all % mod * d;
}
out.println(ans%mod);
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new G().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
quadratic
|
908_G. New Year and Original Order
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Double.parseDouble;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.in;
import static java.lang.System.out;
public class SolutionD extends Thread {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return parseInt(next());
}
long nextLong() {
return parseLong(next());
}
double nextDouble() {
return parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
private static final FastReader scanner = new FastReader();
private static final PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
solve();
out.close();
}
private static void solve() {
int n = scanner.nextInt();
int m = scanner.nextInt();
int k = scanner.nextInt();
int[][] hori = new int[n][m-1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m-1; j++) {
int xij = scanner.nextInt();
hori[i][j] = xij;
}
}
int[][] vert = new int[n-1][m];
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < m; j++) {
int xij = scanner.nextInt();
vert[i][j] = xij;
}
}
if (k % 2 != 0) {
for (int i = 0; i < n; i++) {
StringBuilder s = new StringBuilder();
for (int j = 0; j < m; j++) {
s.append("-1 ");
}
out.println(s);
}
return;
}
k /= 2;
long[][][] dp = new long[n][m][k+1];
for (int kTmp = 1; kTmp <= k; kTmp++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
dp[i][j][kTmp] = Integer.MAX_VALUE;
if (i > 0) {
dp[i][j][kTmp] = Math.min(dp[i][j][kTmp], dp[i-1][j][kTmp-1] + 2L * vert[i - 1][j]);
}
if (j > 0) {
dp[i][j][kTmp] = Math.min(dp[i][j][kTmp], dp[i][j-1][kTmp-1] + 2L * hori[i][j - 1]);
}
if (i + 1 < n) {
dp[i][j][kTmp] = Math.min(dp[i][j][kTmp], dp[i+1][j][kTmp-1] + 2L * vert[i][j]);
}
if (j + 1 < m) {
dp[i][j][kTmp] = Math.min(dp[i][j][kTmp], dp[i][j+1][kTmp-1] + 2L * hori[i][j]);
}
}
}
}
for (int i = 0; i < n; i++) {
StringBuilder s = new StringBuilder();
for (int j = 0; j < m; j++) {
s.append(dp[i][j][k]).append(" ");
}
out.println(s);
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
/**
*
*/
/**
* @author burdakovd
*
*/
public class A {
static class House {
int x, a;
}
/**
* @param args
*/
public static void main(final String[] args) {
final Scanner in = new Scanner(System.in);
final PrintWriter out = new PrintWriter(System.out);
try {
final int n = in.nextInt();
final int t = in.nextInt();
final House[] h = new House[n];
for (int i = 0; i < h.length; ++i) {
h[i] = new House();
h[i].x = in.nextInt();
h[i].a = in.nextInt();
}
Arrays.sort(h, new Comparator<House>() {
@Override
public int compare(final House o1, final House o2) {
return Integer.valueOf(o1.x).compareTo(o2.x);
}
});
int ans = 2;
for (int i = 1; i < n; ++i) {
final int dspace = 2 * h[i].x - h[i].a
- (2 * h[i - 1].x + h[i - 1].a);
if (dspace == 2 * t) {
++ans;
} else if (dspace > 2 * t) {
ans += 2;
}
}
out.println(ans);
} finally {
in.close();
out.close();
}
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.Queue;
public class A {
static int[] dx = {-1, 0, 1, 0};
static int[] dy = {0, 1, 0, -1};
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner("input.txt");
PrintWriter out = new PrintWriter("output.txt");
int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt();
int[][] dist = new int[n][m];
for(int[] a : dist) Arrays.fill(a, -1);
Queue<Point> q = new LinkedList<>();
for(int i = 0; i < k; i++)
{
int x = sc.nextInt() - 1, y = sc.nextInt() - 1;
dist[x][y] = 0;
q.add(new Point(x, y));
}
int ansX = -1, ansY = -1;
while(!q.isEmpty())
{
Point cur = q.remove();
ansX = cur.x; ansY = cur.y;
for(int i = 0; i < 4; i++)
{
int x = cur.x + dx[i], y = cur.y + dy[i];
if(x != -1 && y != -1 && x != n && y != m && dist[x][y] == -1)
{
q.add(new Point(x, y));
dist[x][y] = dist[cur.x][cur.y] + 1;
}
}
}
out.println((ansX + 1) + " " + (ansY + 1));
out.flush();
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));}
public Scanner(String file) throws Exception {br = new BufferedReader(new FileReader(file));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine()throws IOException{return br.readLine();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public char nextChar()throws IOException{return next().charAt(0);}
public Long nextLong()throws IOException{return Long.parseLong(next());}
public boolean ready() throws IOException{return br.ready();}
public void waitForInput() throws InterruptedException {Thread.sleep(4000);}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class B {
public static void main(String[] args) throws IOException {
/**/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
/*/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/b.in"))));
/**/
int n = sc.nextInt();
int l1 = 1;
int r1 = n;
int b1 = 1;
int t1 = n;
int min = b1;
int max = t1;
while (min != max) {
int mid = (min+max)/2;
System.out.println("? "+l1+" "+b1+" "+r1+" "+mid);
System.out.flush();
if (sc.nextInt() >= 1)
max = mid;
else
min = mid+1;
}
t1 = min;
min = l1;
max = r1;
while (min != max) {
int mid = (min+max)/2;
System.out.println("? "+l1+" "+b1+" "+mid+" "+t1);
System.out.flush();
if (sc.nextInt() >= 1)
max = mid;
else
min = mid+1;
}
r1 = min;
min = b1;
max = t1;
while (min != max) {
int mid = (min+max+1)/2;
System.out.println("? "+l1+" "+mid+" "+r1+" "+t1);
System.out.flush();
if (sc.nextInt() >= 1)
min = mid;
else
max = mid-1;
}
b1 = min;
min = l1;
max = r1;
while (min != max) {
int mid = (min+max+1)/2;
System.out.println("? "+mid+" "+b1+" "+r1+" "+t1);
System.out.flush();
if (sc.nextInt() >= 1)
min = mid;
else
max = mid-1;
}
l1 = min;
int l2 = 1;
int r2 = n;
int b2 = 1;
int t2 = n;
min = b2;
max = t2;
while (min != max) {
int mid = (min+max+1)/2;
System.out.println("? "+l2+" "+mid+" "+r2+" "+t2);
System.out.flush();
if (sc.nextInt() >= 1)
min = mid;
else
max = mid-1;
}
b2 = min;
min = l2;
max = r2;
while (min != max) {
int mid = (min+max+1)/2;
System.out.println("? "+mid+" "+b2+" "+r2+" "+t2);
System.out.flush();
if (sc.nextInt() >= 1)
min = mid;
else
max = mid-1;
}
l2 = min;
min = b2;
max = t2;
while (min != max) {
int mid = (min+max)/2;
System.out.println("? "+l2+" "+b2+" "+r2+" "+mid);
System.out.flush();
if (sc.nextInt() >= 1)
max = mid;
else
min = mid+1;
}
t2 = min;
min = l2;
max = r2;
while (min != max) {
int mid = (min+max)/2;
System.out.println("? "+l2+" "+b2+" "+mid+" "+t2);
System.out.flush();
if (sc.nextInt() >= 1)
max = mid;
else
min = mid+1;
}
r2 = min;
System.out.println("! "+l1+" "+b1+" "+r1+" "+t1+" "+l2+" "+b2+" "+r2+" "+t2);
System.out.flush();
}
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int r = sc.nextInt();
double ans[] = new double[n];
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
ans[i] = r;
for (int j = 0; j < i; j++) {
int d = Math.abs(x[i] - x[j]);
if(d <= 2 * r) {
ans[i] = Math.max(ans[i], ans[j] + Math.sqrt(4 * r * r - d * d));
}
}
out.print(ans[i] + " ");
}
out.println();
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws FileNotFoundException {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public 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();
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Created by Jarek on 2017-12-30.
*/
public class PhytonIndenter {
private static Scanner scanner = new Scanner(System.in);
private static int lineCount;
private static String[] commands;
public static void main(String args[]) {
lineCount = scanner.nextInt();
scanner.nextLine();
commands = new String[lineCount];
for (int i = 0; i < lineCount; i++) {
commands[i] = scanner.nextLine();
}
resolveWithDP();
}
private static void resolveWithDP() {
long dp[][] = new long[lineCount][5002];
long mod = 1000000007;
dp[0][0] = 1;
for (int i = 1; i < lineCount; i++) {
if ("f".equalsIgnoreCase(commands[i - 1])) {
dp[i][0] = 0;
for (int j = 1; j <= i; j++) {
dp[i][j] = dp[i - 1][j - 1];
}
} else {
long sum = 0;
for (int j = i - 1; j >= 0; j--) {
sum += dp[i - 1][j] % mod;
dp[i][j] = sum;
}
}
}
long result = 0;
for (int i = 0; i < lineCount; i++) {
result += dp[lineCount-1][i]%mod;
result %= mod;
}
System.out.println(result%mod);
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import javax.annotation.processing.SupportedSourceVersion;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(new FileReader("input.txt")); // new InputReader(inputStream);
PrintWriter out = new PrintWriter("output.txt"); //new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(in, out);
out.close();
}
private static class TaskB {
static final long max = 1000000000000000000L;
static final double eps = 0.0000001;
static final long mod = 1000000007;
static int N, M, K;
static long X, Y;
static boolean F[][][];
static int D[][];
void solve(InputReader in, PrintWriter out) throws IOException {
N = in.nextInt();
M = in.nextInt();
K = in.nextInt();
F = new boolean[K][N][M];
D = new int[N][M];
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
D[i][j] = Integer.MAX_VALUE;
List<Pair> list = new ArrayList<>();
for (int i = 0; i < K; i++) {
list.add(new Pair(in.nextInt() - 1, in.nextInt() - 1));
}
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
for (int k = 0; k < K; k++)
D[i][j] = Math.min(D[i][j], Math.abs(list.get(k).X - i) + Math.abs(list.get(k).Y - j));
int res = Integer.MIN_VALUE;
for (int j = 0; j < N; j++)
for (int k = 0; k < M; k++)
if (D[j][k] > res) {
X = j + 1;
Y = k + 1;
res = D[j][k];
}
out.println(X + " " + Y);
}
class Pair {
int X, Y;
Pair(int X, int Y) {
this.X = X;
this.Y = Y;
}
}
long gcd(long A, long B) {
if (B == 0) return A;
return gcd(B, A % B);
}
boolean isPrime(long n) {
if (n <= 1 || n > 3 && (n % 2 == 0 || n % 3 == 0))
return false;
for (long i = 5, j = 2; i * i <= n; i += j, j = 6 - j)
if (n % i == 0)
return false;
return true;
}
boolean isEqual(double A, double B) {
return Math.abs(A - B) < eps;
}
double dist(double X1, double Y1, double X2, double Y2) {
return Math.sqrt((X1 - X2) * (X1 - X2) + (Y1 - Y2) * (Y1 - Y2));
}
boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
long pow(long A, long B, long MOD) {
if (B == 0) {
return 1;
}
if (B == 1) {
return A;
}
long val = pow(A, B / 2, MOD);
if (B % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * A % MOD) % MOD;
}
}
}
private static class InputReader {
StringTokenizer st;
BufferedReader br;
public InputReader(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public InputReader(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() {
while (st == null || !st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
public boolean ready() {
try {
return br.ready();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.Scanner;
public class three {
static boolean check;
public static void main(String[] args) {
check = true;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = n + "";
recurse(n, s.length(), "4");
if (!check)
System.out.println("YES");
else {
recurse(n, s.length(), "7");
if (!check)
System.out.println("YES");
else
System.out.println("NO");
}
}
private static void recurse(int n, int length, String string) {
int k = Integer.parseInt(string);
if (n % k == 0) {
check = false;
} else if (string.length() <= length && check) {
recurse(n, length, string + "4");
recurse(n, length, string + "7");
}
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Stream;
public class Main implements Runnable {
static final double time = 1e9;
static final int MOD = (int) 1e9 + 7;
static final long mh = Long.MAX_VALUE;
static final Reader in = new Reader();
static final PrintWriter out = new PrintWriter(System.out);
StringBuilder answer = new StringBuilder();
long start = System.nanoTime();
public static void main(String[] args) {
new Thread(null, new Main(), "persefone", 1 << 28).start();
}
@Override
public void run() {
solve();
printf();
long elapsed = System.nanoTime() - start;
// out.println("stamp : " + elapsed / time);
// out.println("stamp : " + TimeUnit.SECONDS.convert(elapsed, TimeUnit.NANOSECONDS));
close();
// out.flush();
}
void solve() {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int invertions = 0;
for (int i = 1; i < n; i++) {
for (int j = i - 1; j > -1; j--) {
if (a[j] > a[i])
invertions++;
}
}
invertions %= 2;
for (int q = in.nextInt(); q > 0; q--) {
int l = in.nextInt();
int r = in.nextInt();
int k = r - l + 1;
k = (k * (k - 1) >> 1) % 2;
if (invertions == k) {
invertions = 0;
add("even", '\n');
} else {
invertions = 1;
add("odd", '\n');
}
}
}
void printf() {
out.print(answer);
}
void close() {
out.close();
}
void printf(Stream<?> str) {
str.forEach(o -> add(o, " "));
add("\n");
}
void printf(Object... obj) {
printf(false, obj);
}
void printfWithDescription(Object... obj) {
printf(true, obj);
}
private void printf(boolean b, Object... obj) {
if (obj.length > 1) {
for (int i = 0; i < obj.length; i++) {
if (b) add(obj[i].getClass().getSimpleName(), " - ");
if (obj[i] instanceof Collection<?>) {
printf((Collection<?>) obj[i]);
} else if (obj[i] instanceof int[][]) {
printf((int[][])obj[i]);
} else if (obj[i] instanceof long[][]) {
printf((long[][])obj[i]);
} else if (obj[i] instanceof double[][]) {
printf((double[][])obj[i]);
} else printf(obj[i]);
}
return;
}
if (b) add(obj[0].getClass().getSimpleName(), " - ");
printf(obj[0]);
}
void printf(Object o) {
if (o instanceof int[])
printf(Arrays.stream((int[]) o).boxed());
else if (o instanceof char[])
printf(new String((char[]) o));
else if (o instanceof long[])
printf(Arrays.stream((long[]) o).boxed());
else if (o instanceof double[])
printf(Arrays.stream((double[]) o).boxed());
else if (o instanceof boolean[]) {
for (boolean b : (boolean[]) o) add(b, " ");
add("\n");
}
else
add(o, "\n");
}
void printf(int[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(long[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(double[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(boolean[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(Collection<?> col) {
printf(col.stream());
}
<T, K> void add(T t, K k) {
if (t instanceof Collection<?>) {
((Collection<?>) t).forEach(i -> add(i, " "));
} else if (t instanceof Object[]) {
Arrays.stream((Object[]) t).forEach(i -> add(i, " "));
} else
add(t);
add(k);
}
<T> void add(T t) {
answer.append(t);
}
@SuppressWarnings("unchecked")
<T extends Comparable<? super T>> T min(T... t) {
if (t.length == 0)
return null;
T m = t[0];
for (int i = 1; i < t.length; i++)
if (t[i].compareTo(m) < 0)
m = t[i];
return m;
}
@SuppressWarnings("unchecked")
<T extends Comparable<? super T>> T max(T... t) {
if (t.length == 0)
return null;
T m = t[0];
for (int i = 1; i < t.length; i++)
if (t[i].compareTo(m) > 0)
m = t[i];
return m;
}
int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a % b);
}
long gcd(long a, long b) {
return (b == 0) ? a : gcd(b, a % b);
}
// c = gcd(a, b) -> extends gcd method: ax + by = c <----> (b % a)p + q = c;
int[] ext_gcd(int a, int b) {
if (b == 0) return new int[] {a, 1, 0 };
int[] vals = ext_gcd(b, a % b);
int d = vals[0]; // gcd
int p = vals[2]; //
int q = vals[1] - (a / b) * vals[2];
return new int[] { d, p, q };
}
// find any solution of the equation: ax + by = c using extends gcd
boolean find_any_solution(int a, int b, int c, int[] root) {
int[] vals = ext_gcd(Math.abs(a), Math.abs(b));
if (c % vals[0] != 0) return false;
printf(vals);
root[0] = c * vals[1] / vals[0];
root[1] = c * vals[2] / vals[0];
if (a < 0) root[0] *= -1;
if (b < 0) root[1] *= -1;
return true;
}
int mod(int x) { return x % MOD; }
int mod(int x, int y) { return mod(mod(x) + mod(y)); }
long mod(long x) { return x % MOD; }
long mod (long x, long y) { return mod(mod(x) + mod(y)); }
int lw(long[] f, int l, int r, long k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (f[m] >= k) r = m - 1; else l = m + 1;
}
return l;
}
int up(long[] f, int l, int r, long k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (f[m] > k) r = m - 1; else l = m + 1;
}
return l;
}
int lw(int[] f, int l, int r, int k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (f[m] >= k) r = m - 1; else l = m + 1;
}
return l;
}
int up(int[] f, int l, int r, int k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (f[m] > k) r = m - 1; else l = m + 1;
}
return l;
}
<K extends Comparable<K>> int lw(List<K> li, int l, int r, K k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (li.get(m).compareTo(k) >= 0)
r = m - 1;
else
l = m + 1;
}
return l;
}
<K extends Comparable<K>> int up(List<K> li, int l, int r, K k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (li.get(m).compareTo(k) > 0)
r = m - 1;
else
l = m + 1;
}
return l;
}
<K extends Comparable<K>> int bs(List<K> li, int l, int r, K k) {
while (l <= r) {
int m = l + r >> 1;
if (li.get(m) == k) return m;
else if (li.get(m).compareTo(k) < 0)
l = m + 1;
else
r = m - 1;
}
return -1;
}
long calc(int base, int exponent) {
if (exponent == 0) return 1;
if (exponent == 1) return base % MOD;
long m = calc(base, exponent / 2);
if (exponent % 2 == 0) return (m * m) % MOD;
return (base * ((m * m) % MOD)) % MOD;
}
long calc(int base, long exponent) {
if (exponent == 0) return 1;
if (exponent == 1) return base % MOD;
long m = calc(base, exponent / 2);
if (exponent % 2 == 0) return (m * m) % MOD;
return (base * ((m * m) % MOD)) % MOD;
}
long calc(long base, long exponent) {
if (exponent == 0) return 1;
if (exponent == 1) return base % MOD;
long m = calc(base, exponent / 2);
if (exponent % 2 == 0) return (m * m) % MOD;
return (base * (m * m % MOD)) % MOD;
}
long power(int base, int exponent) {
if (exponent == 0) return 1;
long m = power(base, exponent / 2);
if (exponent % 2 == 0) return m * m;
return base * m * m;
}
void swap(int[] a, int i, int j) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
void swap(long[] a, int i, int j) {
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>>
implements Comparable<Pair<K, V>> {
private K k;
private V v;
Pair() {}
Pair(K k, V v) {
this.k = k;
this.v = v;
}
K getK() { return k; }
V getV() { return v; }
void setK(K k) { this.k = k; }
void setV(V v) { this.v = v; }
void setKV(K k, V v) {
this.k = k;
this.v = v;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof Pair)) return false;
Pair<K, V> p = (Pair<K, V>) o;
return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0;
}
@Override
public int hashCode() {
int hash = 31;
hash = hash * 89 + k.hashCode();
hash = hash * 89 + v.hashCode();
return hash;
}
@Override
public int compareTo(Pair<K, V> pair) {
return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k);
}
@Override
public Pair<K, V> clone() {
return new Pair<K, V>(this.k, this.v);
}
@Override
public String toString() {
return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n");
}
}
static class Reader {
private BufferedReader br;
private StringTokenizer st;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.*;
import java.math.*;
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
Scanner c=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
long N=c.nextLong()-1;
long K=c.nextLong()-1;
long tot=(K*(K+1))/2;
//System.out.println(tot);
if(N>tot)
{
System.out.println(-1);
return;
}
long lo=1;
long hi=K;
while(hi-lo>=10)
{
long mid=(hi+lo)/2;
//maximum outlets using mid pipes
long sum=(mid*(mid-1))/2;
long left=mid*K-sum;
if(left>=N)
hi=mid+1;
else
lo=mid-1;
}
for(int num=(int)lo-1000;num<lo+1000;num++)
{
if(num>=0)
{
long sum=((long)num*(num-1))/2;
long left=(long)num*K-sum;
if(left>=N)
{
System.out.println(num);
return;
}
}
}
out.close();
}
}
class InputReader
{
private InputStream stream;
private byte[] buf=new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream=stream;
}
public int read()
{
if(numChars==-1)
throw new InputMismatchException();
if(curChar>=numChars)
{
curChar=0;
try
{
numChars=stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars<=0)
return -1;
}
return buf[curChar++];
}
public int readInt()
{
int c=read();
while (isSpaceChar(c))
c=read();
int sgn=1;
if(c=='-')
{
sgn=-1;
c=read();
}
int res=0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res*=10;
res+=c-'0';
c=read();
} while (!isSpaceChar(c));
return res*sgn;
}
public boolean isSpaceChar(int c)
{
if(filter!=null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c)
{
return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
}
public char readCharacter()
{
int c=read();
while (isSpaceChar(c))
c=read();
return (char) c;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.lang.reflect.Array;
public class C {
FastScanner in;
PrintWriter out;
boolean systemIO = true;
public static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public void solve() {
int n = in.nextInt();
int r = 2 * in.nextInt();
int[] x = new int[n];
for (int i = 0; i < x.length; i++) {
x[i] = in.nextInt();
}
double[] y = new double[n];
for (int i = 0; i < y.length; i++) {
y[i] = r / 2;
}
for (int i = 0; i < y.length; i++) {
for (int j = 0; j < i; j++) {
if (Math.abs(x[i] - x[j]) == r) {
y[i] = Math.max(y[i], y[j]);
} else if (Math.abs(x[i] - x[j]) < r) {
y[i] = Math.max(y[i], y[j] + Math.sqrt(r * r - (x[j] - x[i]) * (x[j] - x[i])));
}
}
}
for (int i = 0; i < y.length; i++) {
out.print(y[i] + " ");
}
}
public void run() {
try {
if (systemIO) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new FastScanner(new File("segments.in"));
out = new PrintWriter(new File("segments.out"));
}
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
public static void main(String[] arg) {
new C().run();
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
/*
2
3 5
2
6 5
1 11
-10 12
3
3 6 2
1 8 5 3
-7 9 5 3
-7 4 14 3
1 8 5 3
1 3 13 3
-2 4 13 3
3
1 3 6
3 3 6
5 12
-7 19
3 5 7 11 13
-2 8
5 9
5 9
3 6 7
-3 9 7
6 3 7
*/
public class c {
static int n;
static int[] fs;
static int[] cfs;
static long[][] choose = chooseTable(1001);
static long[] fact;
static final long MOD = (long) (1e9 + 7);
static long[][] memo;
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
n = in.nextInt();
fact = new long[301];
fact[0] = 1;
for (int i = 1; i < fact.length; i++) {
fact[i] = fact[i - 1] * i;
fact[i] %= MOD;
}
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
fs = new int[n];
for (int i = 0; i < n; i++) {
long v = in.nextLong();
long r = 1;
for (int d = 2; d * d <= v; d++) {
int cnt = 0;
while (v % d == 0) {
v /= d;
cnt ^= 1;
}
if (cnt == 1) {
r *= d;
}
}
r *= v;
if (!map.containsKey(r)) {
map.put(r, map.size());
}
fs[map.get(r)]++;
}
cfs = new int[n];
for (int i = 1; i < n; i++) {
cfs[i] = cfs[i - 1] + fs[i - 1];
}
memo = new long[n+1][n+1];
for(long[] arr : memo)
Arrays.fill(arr, -1);
System.out.println(go(0, 0));
}
static long go(int color, int priorities) {
if (color == n)
return priorities == 0 ? 1 : 0;
// System.out.println(color + " "+ priorities);
if(memo[color][priorities] != -1)
return memo[color][priorities];
int nonpriorities = cfs[color] - priorities + 1;
long ans = 0;
for (int cntPrio = 0; cntPrio <= priorities && cntPrio <= fs[color]; cntPrio++) {
for (int cntNonPrio = 0; cntNonPrio <= nonpriorities && cntNonPrio + cntPrio <= fs[color]; cntNonPrio++) {
if(cntPrio + cntNonPrio == 0 && fs[color] != 0) continue;
int cntExtra = fs[color] - cntPrio - cntNonPrio;
long tmp = choose(priorities, cntPrio);
tmp *= choose(nonpriorities, cntNonPrio);
tmp %= MOD;
tmp *= multichoose(cntPrio + cntNonPrio, cntExtra);
tmp %= MOD;
tmp *= go(color + 1, priorities - cntPrio + cntExtra);
tmp %= MOD;
tmp *= fact[fs[color]];
tmp %= MOD;
ans += tmp;
ans %= MOD;
}
}
return memo[color][priorities] = ans;
}
static long[][] chooseTable(int n) {
long[][] table = new long[n][];
for (int x = 0; x < n; x++) {
table[x] = new long[x + 1];
table[x][0] = table[x][x] = 1;
for (int y = 1; y < x; y++) {
table[x][y] = table[x - 1][y - 1] + table[x - 1][y];
table[x][y] %= MOD;
}
}
return table;
}
static long choose(int n, int k) {
if (k == 0)
return 1;
if (k >= choose[n].length) {
return 0;
}
return choose[n][k];
}
static long multichoose(int n, int k) {
return choose(n + k - 1, k);
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
}
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 double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
|
cubic
|
840_C. On the Bench
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
int t = Integer.parseInt(br.readLine());
// get primes up to 10000
/*
boolean[] prime = new boolean[10001];
for (int i = 0; i <= 10000; i++) {
prime[i] = true;
}
for (int p = 2; p * p <= 10000; p++) {
if (prime[p]) {
for (int i = p * p; i <= 10000; i += p) {
prime[i] = false;
}
}
}
ArrayList<Integer> primes = new ArrayList<>();
for (int i = 2; i < 10001; i++) {
if (prime[i]) {
primes.add(i);
}
}
*/
int A = 10000000;
int[] convert = new int[A+1];
for (int a = 1; a <= A; a++) {
convert[a] = a;
}
for (int a = 2; a <= A/a; a++) {
int sq = a*a;
for (int b = sq; b <= A; b += sq) {
while (convert[b] % sq == 0) {
convert[b] /= sq;
}
}
}
int[] prevIndex = new int[A+1];
for (int i = 0; i <= A; i++) {
prevIndex[i] = -1;
}
for (int c = 0; c < t; c++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] a = new int[n];
int maxA = 0;
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
/*
int raw = Integer.parseInt(st.nextToken());
for (int p : primes) {
if (p*p > raw) {
break;
}
while (raw % (p*p) == 0) {
raw /= p*p;
}
}
a[i] = raw;
*/
a[i] = convert[Integer.parseInt(st.nextToken())];
maxA = Math.max(maxA, a[i]);
}
// hard version has extra here
// better version O(nk)
int[] partitions = new int[k+1];
int[] partIndex = new int[k+1];
for (int i = 0; i < n; i++) {
int cur = a[i];
for (int j = k; j >= 0; j--) {
if (prevIndex[cur] >= partIndex[j]) {
partitions[j]++;
partIndex[j] = i;
}
if (j > 0 && (partitions[j-1] < partitions[j] || partitions[j-1] == partitions[j] && partIndex[j-1] > partIndex[j])) {
partitions[j] = partitions[j-1];
partIndex[j] = partIndex[j-1];
}
}
prevIndex[cur] = i;
}
System.out.println(partitions[k]+1);
for (int i = 0; i < n; i++) {
int cur = a[i];
prevIndex[cur] = -1;
}
/* this should work (O(n*k^2))
int[][] minLeftIndex = new int[n][k+1];
for (int j = 0; j <= k; j++) {
HashMap<Integer, Integer> interval = new HashMap<>();
int leftIndex = 0; // the right index is i in this case
int removed = 0;
for (int i = 0; i < n; i++) {
if (!interval.containsKey(a[i])) {
interval.put(a[i], 0);
}
interval.put(a[i], interval.get(a[i])+1);
if (interval.get(a[i]) > 1) {
removed++;
}
while (removed > j) {
interval.put(a[leftIndex], interval.get(a[leftIndex])-1);
if (interval.get(a[leftIndex]) > 0) {
removed--;
}
leftIndex++;
}
minLeftIndex[i][j] = leftIndex;
//System.out.println(i + " " + j + " " + leftIndex);
}
}
int[][] dp = new int[n][k+1];
// dp at all i = 0 = 0
for (int i = 0; i < n; i++) {
for (int j = 0; j <= k; j++) {
int min = Integer.MAX_VALUE;
for (int l = 0; l <= j; l++) {
if (minLeftIndex[i][l] > 0) {
min = Math.min(min, dp[minLeftIndex[i][l]-1][j-l] + 1); //
} else {
min = 0;
}
}
if (min != Integer.MAX_VALUE) {
dp[i][j] = min;
}
}
}
System.out.println(dp[n-1][k]+1);
*/
// easy solution
/*
HashSet<Integer> hs = new HashSet<>();
int segments = 1;
for (int i = 0; i < n; i++) {
if (hs.contains(a[i])) {
segments++;
hs.clear();
}
hs.add(a[i]);
}
System.out.println(segments);
*/
}
}
}
|
cubic
|
1497E2
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int[] a = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
sum += a[i];
}
for (int i = 0; i < n; i++)
a[i] *= -1;
Arrays.sort(a);
for (int i = 0; i < n; i++)
a[i] *= -1;
int ans = 0;
int sum1 = 0;
for (int i = 0; i < n; i++) {
sum1 += a[i];
sum -= a[i];
ans++;
if (sum1 > sum)
break;
}
pw.print(ans);
pw.close();
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String s = in.nextLine();
int ans = 0;
outer: for (int i = s.length() - 1; i >= 1; i--)
for (int j = 0; j < s.length() - i; j++) {
String sub = s.substring(j, j + i);
String str = s.substring(j + 1);
if (str.contains(sub)) {
ans = i;
break outer;
}
}
out.print(ans);
out.close();
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class G{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.flush();out.close();
}
static class TaskE {
class MinCostMaxFlow{
ArrayList<Edge> al[];
Edge ja[][];
int d[]; // shortest distances
int N , S , T , maxFlow ; int minCost;
final int gmax = Integer.MAX_VALUE / 100;
int edges = 0;
class Edge{
int u , flow, rid, cost;
Edge(int a, int b, int c, int d){u = a; flow = b; cost = c; rid = d;}
}
void addEdge(int u , int v , int flow , int cost){
int lu = al[u].size(), lv = al[v].size();
al[u].add(new Edge(v, flow, cost, lv));
al[v].add(new Edge(u, 0, -cost, lu));
}
void convertToArray(){
ja = new Edge[N][];
for(int i = 0; i < N; i++){
int sz = al[i].size();
ja[i] = new Edge[sz];
for(int j = 0; j < sz; j++){
ja[i][j] = al[i].get(j);
}
al[i].clear();
}
}
MinCostMaxFlow(int n , int source , int sink){
N = n; S = source; T = sink; maxFlow = 0; minCost = 0;
al = new ArrayList[N];
d = new int[N];
for(int i = 0; i < N; i++){
al[i] = new ArrayList<>();
}
}
boolean BellmanFord(boolean check){
d[0] = 0;
for(int i = 0; i < N - 1; i++){
for(int j = 0; j < N; j++){
for(Edge e : ja[j]){
if(e.flow == 0)continue; // not to consider reverse edges
d[e.u] = Math.min(d[e.u] , d[j] + e.cost);
}
}
}
if(check){// check for negative cycles
for(int j = 0; j < N; j++){
for(Edge e : ja[j]){
if(e.flow == 0)continue;
if(d[j] + e.cost < d[e.u]) return false;
}
}
}return true;
}
int node[]; // present node
int visit[]; // 0 -> not added 1 -> not removed 2 -> removed
int prv[], prve[]; // previous node for augmentation
int dist[]; // min dist
boolean simple(){
node = new int[N];
visit = new int[N];
prv = new int[N];
prve = new int[N];
dist = new int[N]; Arrays.fill(dist , gmax);
node[0] = S; dist[0] = 0;
int front = 1, back = 0;
while(front != back){
int u = node[back++]; int distu = dist[u];
if(back == N)back = 0;
visit[u] = 2;
for(int i = 0; i < ja[u].length; i++){
Edge e = ja[u][i];
if(e.flow == 0)continue;
int cdist = distu + e.cost; // no need of reduced cost
if(cdist < dist[e.u]){
if(visit[e.u] == 0){
node[front] = e.u;
if(++front == N)front = 0;
}else if(visit[e.u] == 2){
if(--back == -1)back += N;
node[back] = e.u;
}
visit[e.u] = 1;
prve[e.u] = i; prv[e.u] = u; dist[e.u] = cdist;
}
}
}
return visit[T] != 0;
}
class pair{
int F; int S;
pair(int a, int b){F = a; S = b;}
}
boolean dijkstra(){
visit = new int[N];
prv = new int[N];
prve = new int[N];
dist = new int[N]; Arrays.fill(dist, gmax);
PriorityQueue<pair> pq = new PriorityQueue<>((A, B) -> Double.compare(A.S , B.S));
pq.add(new pair(S , 0)); dist[0] = 0;
o : while(!pq.isEmpty()){
pair p = pq.poll();
while(dist[p.F] < p.S){
if(pq.isEmpty()) break o; // had a better val
p = pq.poll();
}
visit[p.F] = 2;
for(int i = 0; i < ja[p.F].length; i++){
Edge e = ja[p.F][i];
if(e.flow == 0)continue; // important
int cdist = p.S + (e.cost + d[p.F] - d[e.u]); // reduced cost
if(cdist < dist[e.u]){
if(visit[e.u] == 2) return false;
pq.add(new pair(e.u , cdist));
dist[e.u] = cdist; prv[e.u] = p.F; prve[e.u] = i;
visit[e.u] = 1;
}
}
}
return visit[T] != 0;
}
int augment(){
int p = T; int min = gmax;
while(p != 0){
int pp = prv[p], pe = prve[p];
int val = ja[pp][pe].flow;
min = Math.min(min , val);
p = pp;
}
p = T;
while(p != 0){
int pp = prv[p], pe = prve[p];
ja[pp][pe].flow -= min;
ja[p][ja[pp][pe].rid].flow += min;
p = pp;
}
maxFlow += min;
return min;
}
// if(dist[T] >= 0)return true; // non contributing flow
boolean calSimple(){
// uncomment to check for negative cycles
/* boolean possible = BellmanFord(true);
if(!possible) return false; */
while(simple()){
/*if(dist[T] >= 0)return true;*/
minCost += dist[T] * augment();
}
return true;
}
void updPotential(){
for(int i = 0; i < N; i++){
if(visit[i] != 0){
d[i] += dist[i] - dist[S];
}
}
}
boolean calWithPotential(){
// set true to check for negative cycles
// boolean possible = BellmanFord(false);
// if(!possible) return false;
while(dijkstra()){
int min = dist[T] + d[T] - d[S]; // getting back the original cost
/*if(dist[T] >= 0)return true;*/
minCost += min * augment();
updPotential();
}
return true;
}
}
int n , m, k, c, d, a[], f[];
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt(); m = in.nextInt(); k = in.nextInt(); c = in.nextInt(); d= in.nextInt();
// S + n
int maxl = n + k, T = n * maxl + 1;
MinCostMaxFlow ans = new MinCostMaxFlow(T + 1, 0, T);
a = new int[k + 1]; f = new int[n + 1];
for(int i = 1; i <= k; i++){
a[i] = in.nextInt();
f[a[i]]++;
}
for(int i = 1; i <= n; i++){
if(f[i] == 0)continue;
ans.addEdge(0 , i , f[i], 0);
}
for(int i = 2; i <= n; i++){
for(int l = 0; l < maxl - 1; l++){
ans.addEdge(l * n + i , (l + 1) * n + i, k, c);
}
}
for(int i = 1; i <= m; i++){
int a = in.nextInt(), b = in.nextInt();
for(int l = 0; l < maxl - 1; l++){
for(int p = 1; p <= k; p++){
if(a != 1)
ans.addEdge(n * l + a, n * (l + 1) + b, 1, d * (2 * p - 1) + c);
if(b != 1)
ans.addEdge(n * l + b, n * (l + 1) + a, 1, d * (2 * p - 1) + c);
}
}
}
for(int l = 1; l < maxl; l++){
ans.addEdge(l * n + 1, T, k, 0);
}
ans.convertToArray();
// ans.calWithPotential();
ans.calSimple();
if(ans.maxFlow != k){
out.println("BUG");
}else{
out.println((int)ans.minCost);
}
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
st = null;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
cubic
|
1187_G. Gang Up
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author c0der
*/
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 m = in.nextInt();
int k = in.nextInt();
int[] a = new int[ n ];
for (int i=0; i<n; i++) a[i] = in.nextInt();
if ( m <= k ) out.println( 0 );
else
{
m -= k - 1;
Arrays.sort( a );
int ans = 0;
for (int i=n-1; i>=0; i--)
{
ans++;
//out.println(m+" "+a[i]);
m -= a[ i ];
if ( m <= 0 ) break;
m++;
}
if ( m > 0 ) out.println( -1 );
else out.println( ans );
}
}
}
class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream in)
{
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String next()
{
while (st==null || !st.hasMoreTokens())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.util.*;
import java.math.*;
import java.io.*;
public class B implements Runnable {
public static void main(String[] args) {
new Thread(new B()).start();
}
StringTokenizer st;
PrintWriter out;
BufferedReader br;
boolean eof = false, in_out = false, std = false;
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return "0";
}
}
return st.nextToken();
}
String nextLine() {
String ret = "";
try {
ret = br.readLine();
} catch (Exception e) {
ret = "";
}
if (ret == null) {
eof = true;
return "$";
}
return ret;
}
String nextString() {
return nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
BigInteger nextBigInteger() {
return new BigInteger(nextToken());
}
public void run() {
// long time = System.currentTimeMillis();
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.flush();
} catch (Exception e) {
e.printStackTrace();
System.exit(111);
}
// System.err.println(System.currentTimeMillis() - time);
}
void solve() {
int n = nextInt();
for (int i = 0; i < n; i++) {
solve2();
}
}
void solve2() {
String s = nextToken();
boolean wasNum = false, isFirst = false;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
wasNum = true;
} else if (wasNum) {
isFirst = true;
break;
}
}
if (isFirst) {
StringTokenizer e = new StringTokenizer(s, "RC");
int y = Integer.parseInt(e.nextToken());
int x = Integer.parseInt(e.nextToken()) - 1;
go1(x, y);
} else {
go2(s);
}
}
void go1(int x, int y) {
long cur = 26;
int len = 1;
while (x >= cur) {
x -= cur;
cur *= 26;
len++;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
sb.append((char) ('A' + x % 26));
x /= 26;
}
out.println(sb.reverse().toString() + y);
}
void go2(String s) {
int id = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) <= '9' && s.charAt(i) >= '0') {
id = i;
break;
}
}
String s1 = s.substring(0, id);
String s2 = s.substring(id);
int x = 0;
int cur = 26;
for (int i = 1; i < s1.length(); i++) {
x += cur;
cur *= 26;
}
int d = 0;
for (int i = 0; i < s1.length(); i++) {
d *= 26;
d += s1.charAt(i) - 'A';
}
x += d;
out.println("R" + s2 + "C" + (x + 1));
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class A implements Runnable {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer st;
static Random rnd;
final long MODULO = 1000000009;
private void solve() throws IOException {
int moves = nextInt(), rightMoves = nextInt(), sequence = nextInt();
long answer = solveSmart(moves, rightMoves, sequence);
out.println(answer);
// for (int moves = 2; moves <= 50; moves++) {
// for (int rightMoves = 2; rightMoves <= moves; rightMoves++) {
// for (int sequence = 2; sequence <= moves; sequence++) {
// if (solveDumb(moves, rightMoves, sequence) != solveSmart(
// moves, rightMoves, sequence)) {
// out.println(moves + " " + rightMoves + " " + sequence);
// out.flush();
// }
// }
// }
// }
}
// private long solveDumb(int moves, int rightMoves, int sequence) {
// long[][][] d = new long[moves + 1][rightMoves + 1][sequence];
// long inf = Integer.MAX_VALUE;
// for (int i = 0; i <= moves; i++)
// for (int j = 0; j <= rightMoves; j++)
// Arrays.fill(d[i][j], inf);
// d[0][0][0] = 0;
//
// for (int i = 0; i < moves; i++) {
// for (int j = 0; j <= rightMoves; j++) {
// for (int k = 0; k < sequence; k++) {
// // right move
// if (j < rightMoves) {
// // last move
// if (k + 1 == sequence) {
// d[i + 1][j + 1][0] = Math.min(d[i + 1][j + 1][0],
// (d[i][j][k] + 1) * 2);
// } else {
// d[i + 1][j + 1][k + 1] = Math.min(
// d[i + 1][j + 1][k + 1], d[i][j][k] + 1);
// }
// }
//
// // bad move
// d[i + 1][j][0] = Math.min(d[i + 1][j][0], d[i][j][k]);
// }
//
// }
// }
//
// long result = inf;
// for (int i = 0; i < sequence; i++)
// result = Math.min(result, d[moves][rightMoves][i]);
// return result;
// }
private long solveSmart(long moves, long rightMoves, long sequence) {
long fullSequences = moves / sequence;
long canReset = Math.min(fullSequences, moves - rightMoves);
long remainSequences = fullSequences - canReset;
long answer = (rightMoves - remainSequences * sequence)
+ getAnswerSequences(remainSequences, sequence);
answer %= MODULO;
return answer;
}
private long getAnswerSequences(long count, long length) {
long first = (getPow(2, count + 1) - 2) % MODULO;
long result = first * length;
result %= MODULO;
result += MODULO;
result %= MODULO;
return result;
}
private int getPow(int n, long p) {
return BigInteger.valueOf(2)
.modPow(BigInteger.valueOf(p), BigInteger.valueOf(MODULO))
.intValue();
}
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
rnd = new Random();
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a,b;
if (n%2==0) {
a = 4;
}else{
a = 9;
}
b = n - a;
System.out.println(a + " " + b);
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
/**
* Date: 14 Sep, 2019
* Link:
*
* @author Prasad-Chaudhari
* @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/
* @git: https://github.com/Prasad-Chaudhari
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
public class newProgram5 {
public static void main(String[] args) throws IOException {
// TODO code application logic here
FastIO in = new FastIO();
int n = in.ni();
int a[] = in.gia(n);
int freq[] = new int[100 + 1];
for (int i = 0; i < n; i++) {
freq[a[i]]++;
}
int k = 0;
for (int i = 1; i <= 100; i++) {
if (freq[i] > 0) {
for (int j = i; j <= 100; j += i) {
freq[j] = 0;
}
k++;
// System.out.println(i);
}
}
System.out.println(k);
in.bw.flush();
}
static class FastIO {
private final BufferedReader br;
private final BufferedWriter bw;
private String s[];
private int index;
private final StringBuilder sb;
public FastIO() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8"));
s = br.readLine().split(" ");
sb = new StringBuilder();
index = 0;
}
public int ni() throws IOException {
return Integer.parseInt(nextToken());
}
public double nd() throws IOException {
return Double.parseDouble(nextToken());
}
public long nl() throws IOException {
return Long.parseLong(nextToken());
}
public String next() throws IOException {
return nextToken();
}
public String nli() throws IOException {
try {
return br.readLine();
} catch (IOException ex) {
}
return null;
}
public int[] gia(int n) throws IOException {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public int[] gia(int n, int start, int end) throws IOException {
validate(n, start, end);
int a[] = new int[n];
for (int i = start; i < end; i++) {
a[i] = ni();
}
return a;
}
public double[] gda(int n) throws IOException {
double a[] = new double[n];
for (int i = 0; i < n; i++) {
a[i] = nd();
}
return a;
}
public double[] gda(int n, int start, int end) throws IOException {
validate(n, start, end);
double a[] = new double[n];
for (int i = start; i < end; i++) {
a[i] = nd();
}
return a;
}
public long[] gla(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nl();
}
return a;
}
public long[] gla(int n, int start, int end) throws IOException {
validate(n, start, end);
long a[] = new long[n];
for (int i = start; i < end; i++) {
a[i] = nl();
}
return a;
}
public int[][][] gwtree(int n) throws IOException {
int m = n - 1;
int adja[][] = new int[n + 1][];
int weight[][] = new int[n + 1][];
int from[] = new int[m];
int to[] = new int[m];
int count[] = new int[n + 1];
int cost[] = new int[n + 1];
for (int i = 0; i < m; i++) {
from[i] = i + 1;
to[i] = ni();
cost[i] = ni();
count[from[i]]++;
count[to[i]]++;
}
for (int i = 0; i <= n; i++) {
adja[i] = new int[count[i]];
weight[i] = new int[count[i]];
}
for (int i = 0; i < m; i++) {
adja[from[i]][count[from[i]] - 1] = to[i];
adja[to[i]][count[to[i]] - 1] = from[i];
weight[from[i]][count[from[i]] - 1] = cost[i];
weight[to[i]][count[to[i]] - 1] = cost[i];
count[from[i]]--;
count[to[i]]--;
}
return new int[][][] { adja, weight };
}
public int[][][] gwg(int n, int m) throws IOException {
int adja[][] = new int[n + 1][];
int weight[][] = new int[n + 1][];
int from[] = new int[m];
int to[] = new int[m];
int count[] = new int[n + 1];
int cost[] = new int[n + 1];
for (int i = 0; i < m; i++) {
from[i] = ni();
to[i] = ni();
cost[i] = ni();
count[from[i]]++;
count[to[i]]++;
}
for (int i = 0; i <= n; i++) {
adja[i] = new int[count[i]];
weight[i] = new int[count[i]];
}
for (int i = 0; i < m; i++) {
adja[from[i]][count[from[i]] - 1] = to[i];
adja[to[i]][count[to[i]] - 1] = from[i];
weight[from[i]][count[from[i]] - 1] = cost[i];
weight[to[i]][count[to[i]] - 1] = cost[i];
count[from[i]]--;
count[to[i]]--;
}
return new int[][][] { adja, weight };
}
public int[][] gtree(int n) throws IOException {
int adja[][] = new int[n + 1][];
int from[] = new int[n - 1];
int to[] = new int[n - 1];
int count[] = new int[n + 1];
for (int i = 0; i < n - 1; i++) {
from[i] = i + 1;
to[i] = ni();
count[from[i]]++;
count[to[i]]++;
}
for (int i = 0; i <= n; i++) {
adja[i] = new int[count[i]];
}
for (int i = 0; i < n - 1; i++) {
adja[from[i]][--count[from[i]]] = to[i];
adja[to[i]][--count[to[i]]] = from[i];
}
return adja;
}
public int[][] gg(int n, int m) throws IOException {
int adja[][] = new int[n + 1][];
int from[] = new int[m];
int to[] = new int[m];
int count[] = new int[n + 1];
for (int i = 0; i < m; i++) {
from[i] = ni();
to[i] = ni();
count[from[i]]++;
count[to[i]]++;
}
for (int i = 0; i <= n; i++) {
adja[i] = new int[count[i]];
}
for (int i = 0; i < m; i++) {
adja[from[i]][--count[from[i]]] = to[i];
adja[to[i]][--count[to[i]]] = from[i];
}
return adja;
}
public void print(String s) throws IOException {
bw.write(s);
}
public void println(String s) throws IOException {
bw.write(s);
bw.newLine();
}
public void print(int s) throws IOException {
bw.write(s + "");
}
public void println(int s) throws IOException {
bw.write(s + "");
bw.newLine();
}
public void print(long s) throws IOException {
bw.write(s + "");
}
public void println(long s) throws IOException {
bw.write(s + "");
bw.newLine();
}
public void print(double s) throws IOException {
bw.write(s + "");
}
public void println(double s) throws IOException {
bw.write(s + "");
bw.newLine();
}
private String nextToken() throws IndexOutOfBoundsException, IOException {
if (index == s.length) {
s = br.readLine().split(" ");
index = 0;
}
return s[index++];
}
private void validate(int n, int start, int end) {
if (start < 0 || end >= n) {
throw new IllegalArgumentException();
}
}
}
static class Data implements Comparable<Data> {
int a, b;
public Data(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Data o) {
if (a == o.a) {
return Integer.compare(b, o.b);
}
return Integer.compare(a, o.a);
}
public static void sort(int a[]) {
Data d[] = new Data[a.length];
for (int i = 0; i < a.length; i++) {
d[i] = new Data(a[i], 0);
}
Arrays.sort(d);
for (int i = 0; i < a.length; i++) {
a[i] = d[i].a;
}
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num =0;
num = input.nextLong();
while (num<0 || num>Math.pow(10,9))
{
System.out.println("Invalid");
num = input.nextLong();
}
System.out.println("0 0 "+num);
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.awt.Point;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
public class R227_2_D {
static ArrayList<Integer>[] graph;
static int[] right, left;
static boolean vis[];
public static boolean dfs(int node) {
if (vis[node])
return false;
vis[node] = true;
for (int i = 0; i < graph[node].size(); i++) {
int tmp = graph[node].get(i);
if (right[tmp] == -1) {
left[node] = tmp;
right[tmp] = node;
return true;
}
}
for (int i = 0; i < graph[node].size(); i++) {
int tmp = graph[node].get(i);
if (dfs(right[tmp])) {
left[node] = tmp;
right[tmp] = node;
return true;
}
}
return false;
}
public static int getMaxMatch() {
Arrays.fill(left, -1);
Arrays.fill(right, -1);
boolean done = false;
while (!done) {
done = true;
Arrays.fill(vis, false);
for (int i = 0; i < graph.length; i++) {
if (left[i] == -1 && dfs(i)) {
done = false;
}
}
}
int res = 0;
for (int i = 0; i < left.length; i++) {
res += (left[i] != -1 ? 1 : 0);
}
return res;
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int V = in.readInt();
int E = in.readInt();
Point[] edges = new Point[E];
for (int i = 0; i < edges.length; i++) {
edges[i] = new Point(in.readInt() - 1, in.readInt() - 1);
}
int best = Integer.MAX_VALUE;
for (int k = 0; k < V; k++) {
int n = V - 1;
graph = new ArrayList[n];
left = new int[n];
vis = new boolean[n];
right = new int[n];
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<Integer>();
}
int center = 0;
for (int i = 0; i < E; i++) {
if (edges[i].x == k || edges[i].y == k) {
center++;
continue;
}
int src = edges[i].x > k ? edges[i].x - 1 : edges[i].x;
int dst = edges[i].y > k ? edges[i].y - 1 : edges[i].y;
graph[src].add(dst);
}
int matching = getMaxMatch();
int addToCenterEdges = 2 * V - 1 - center;
int removed = E - center - matching;
int added = n - matching;
best = Math.min(best, added + removed + addToCenterEdges);
}
System.out.println(best);
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1000];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
}
}
|
cubic
|
387_D. George and Interesting Graph
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.