src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.io.*;
import java.util.*;
import java.math.*;
public class C implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
Random rnd;
short[] qx, qy;
boolean[][] used;
final int[] dx = {1, -1, 0, 0};
final int[] dy = {0, 0, 1, -1};
void solve() throws IOException {
int n = nextInt(), m = nextInt();
qx = new short[n * m];
qy = new short[n * m];
used = new boolean[n][m];
int k = nextInt(), qs = 0, qt = 0;
for(int i = 0; i < k; i++) {
int x = nextInt() - 1, y = nextInt() - 1;
used[x][y] = true;
qx[qt] = (short) x;
qy[qt] = (short) y;
++qt;
}
int rx = 0, ry = 0;
while(qs < qt) {
int cx = qx[qs], cy = qy[qs];
++qs;
rx = cx;
ry = cy;
for(int z = 0; z < 4; z++) {
int nx = cx + dx[z], ny = cy + dy[z];
if(nx >= 0 && ny >= 0 && nx < n && ny < m && !used[nx][ny]) {
used[nx][ny] = true;
qx[qt] = (short) nx;
qy[qt] = (short) ny;
++qt;
}
}
}
out.println((rx + 1) + " " + (ry + 1));
}
public static void main(String[] args) {
final boolean oldChecker = false;
if(oldChecker) {
new Thread(null, new C(), "yarrr", 1 << 24).start();
} else {
new C().run();
}
}
public void run() {
try {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
} catch (FileNotFoundException e) {
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(42);
}
}
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();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Code implements Runnable {
public static void main(String[] args) throws IOException {
new Thread(new Code()).start();
}
private void solve() throws IOException {
int n = nextInt(), m = nextInt();
if(n > m) {
n ^= m;
m ^= n;
n ^= m;
}
int[][][] dp = new int[41][64][64];
for(int i = 0; i < 41; ++i)
for(int j = 0; j < 64; ++j)
for(int k = 0; k < 64; ++k) dp[i][j][k] = Integer.MAX_VALUE / 2;
for(int i = 0; i < 64; ++i) dp[0][0][i] = countBit(i);
for(int i = 1; i <= m; ++i) {
for(int cur = 0; cur < 64; ++cur) {
for(int next = 0; next < 64; ++next) {
for(int prev = 0; prev < 64; ++prev) {
if(!isBad(prev, cur, next, n)) {
dp[i][cur][next] = min(dp[i][cur][next], dp[i - 1][prev][cur] + countBit(next));
}
}
}
}
}
int ans = Integer.MAX_VALUE;
for(int i = 0; i < 64; ++i) ans = min(ans, dp[m][i][0]);
writer.println(n * m - ans);
}
private boolean isBit(int bits, int pos) {
return pos < 0 ? false : ((bits & (1 << pos)) != 0);
}
private boolean isBad(int prev, int cur, int next, int count) {
for(int i = 0; i < count; ++i)
if(!(isBit(cur, i - 1) || isBit(cur, i) || isBit(cur, i + 1) || isBit(prev, i) || isBit(next, i))) return true;
return false;
}
private int countBit(int bits) {
int ans = 0;
for(int i = 0; i < 6; ++i) ans += (bits & (1 << i)) > 0 ? 1 : 0;
return ans;
}
private class Pair<E extends Comparable, V extends Comparable> implements Comparable<Pair<E, V>> {
public Pair(E first, V second) {
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair<E, V> obj) {
if(first == obj.first) return second.compareTo(obj.second);
return first.compareTo(obj.first);
}
@Override
public boolean equals(Object obj) {
Pair other = (Pair)obj;
return first.equals(other.first) && second.equals(other.second);
}
public E first;
public V second;
}
@Override
public void run() {
try {
if(in.equals("")) reader = new BufferedReader(new InputStreamReader(System.in));
else reader = new BufferedReader(new FileReader(in));
if(out.equals("")) writer = new PrintWriter(new OutputStreamWriter(System.out));
else writer = new PrintWriter(new FileWriter(out));
solve();
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
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());
}
private float nextFloat() throws IOException {
return Float.parseFloat(nextToken());
}
private String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(reader.readLine());
return st.nextToken();
}
private String in = "", out = "";
private BufferedReader reader;
private PrintWriter writer;
private StringTokenizer st;
}
|
np
|
112_E. Petya and Spiders
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class E584 {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int t = sc.nextInt();
while (t > 0) {
int n = sc.nextInt(); int m = sc.nextInt();
int [][] a = new int[m][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[j][i] = sc.nextInt();
}
}
int [][] dp = new int[m + 1][(1 << n)];
for (int i = 1; i <= m; i++) {
for (int j = 0; j < (1 << n); j++) {
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]);
int [] b = a[i - 1];
for (int start = 0; start < n; start++) {
int [] c = new int[n];
for (int p = 0; p < n; p++) c[p] = b[(start + p) % n];
for (int k = 0; k < (1 << n); k++) {
if ((k | j) == j) {
int sum = 0;
for (int p = 0; p < n; p++) {
if (((k >> p) & 1) == 0 && ((j >> p) & 1) == 1) sum += c[p];
}
dp[i][j] = Math.max(dp[i][j], dp[i - 1][k] + sum);
}
}
}
}
}
out.println(dp[m][(1 << n) - 1]);
t--;
}
out.close();
}
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.util.Scanner;
public class C344C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long a = sc.nextLong();
long b = sc.nextLong();
long count = a / b, c;
a = a % b;
while(true){
if (a <= 1 || b <= 1) break;
c = b - a;
b = a;
a = c;
count++;
if (a > b) count += a / b;
a = a % b;
}
if (b > 1) count += b;
System.out.println(count);
sc.close();
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static Scanner scan = new Scanner(System.in);
public static boolean bg = true;
public static void main(String[] args) throws Exception {
long n1 = Integer.parseInt(scan.next());
if (n1==1){
System.out.println(1);
System.exit(0);
}
if (n1==2){
System.out.println(2);
System.exit(0);
}
if (n1==3){
System.out.println(6);
System.exit(0);
}
if (n1%2==0){
if (n1%3==0){
n1-=1;
n1 = n1*(n1-1)*(n1-2);
System.out.println(n1);
}
else {
n1 = n1*(n1-1)*(n1-3);
System.out.println(n1);
}
}
else {
n1 = n1*(n1-1)*(n1-2);
System.out.println(n1);
}
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
//package Round584;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class typeA {
public static void main(String[] args) {
FastReader s = new FastReader();
int n = s.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++) {
arr[i]=s.nextInt();
}
boolean[] arr2 = new boolean[n];
Arrays.sort(arr);
for(int i=0;i<arr2.length;i++) {
arr2[i]=true;
}
//arr2[0]=true;
for(int i=0;i<n-1;i++) {
for(int j=i+1;j<n;j++) {
if(arr[j]%arr[i]==0) {
arr2[j]=false;
}
}
}
int count=0;
for(int i=0;i<n;i++) {
if(arr2[i]==true) {
count++;
}
}
System.out.println(count);
}
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;
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.*;
public class PC1229 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int r = sc.nextInt();
int[] x = new int[n];
for(int i = 0; i < n; i++){
x[i] = sc.nextInt();
}
double[] ans = new double[n];
for(int i = 0; i < n; i++){
double maxY = r;
for(int j = 0; j < i; j++){
if(x[j] <= x[i] + 2*r && x[j] >= x[i] - 2*r){
maxY = Math.max(maxY, ans[j] + Math.sqrt(4 * r * r - (Math.abs(x[i] - x[j])) * (Math.abs(x[i] - x[j]))));
}
}
ans[i] = maxY;
}
for(int i = 0; i < n; i++){
System.out.println(ans[i]);
}
sc.close();
}
}
|
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.io.Reader;
import java.util.StringTokenizer;
public class MotherOfDragons {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
PrintWriter out = new PrintWriter(System.out, false);
int n = scanner.nextInt();
double k = scanner.nextInt();
long[] graph = new long[n];
for(Integer i = 0; i < n; i++) {
for(Integer j =0; j < n; j++) {
Integer val = scanner.nextInt();
if (val.equals(1) || i.equals(j)) {
graph[i] |= 1L << j;
}
}
}
int szLeft = n/2;
int szRight = n - szLeft;
int[] dp = new int[1 << szLeft];
int maxMask = 1 << szLeft;
for(int mask = 1; mask <maxMask; mask++) {
int curMask = mask;
for(int j = 0; j < szLeft; j++) {
if (((1 << j) & mask) > 0) {
curMask &= graph[j + szRight] >> szRight;
dp[mask] = Math.max(dp[mask], dp[mask ^ (1 << j)]);
}
}
if (mask == curMask) {
dp[mask] = Math.max(dp[mask],Integer.bitCount(mask));
}
}
int ans = 0;
int rmaxMask = 1 << szRight;
for(int mask = 0; mask < rmaxMask; mask++) {
int curMask = mask;
int oMask = maxMask -1;
for(int j = 0; j < szRight; j++) {
if (((1 << j) & mask) > 0) {
curMask &= (graph[j] & (rmaxMask-1));
oMask &= graph[j] >> szRight;
}
}
if (curMask != mask) continue;
ans = Math.max(ans, Integer.bitCount(mask) + dp[oMask]);
}
k/=ans;
out.println(k * k * (ans * (ans-1))/2);
out.flush();
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
np
|
839_E. Mother of Dragons
|
CODEFORCES
|
//package round17;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class A {
static StreamTokenizer in =
new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static int nextInt() throws IOException{
in.nextToken();
return (int)in.nval;
}
static PrintWriter out = new PrintWriter(System.out);
static boolean prime(int n){
int j = 2;
while (j*j <= n)
if (n%j == 0) return false;
else j++;
return true;
}
public static void main(String[] args) throws IOException{
int n = nextInt(),
k = nextInt(),
a[] = new int[n];
int s = 0;
for (int i=2; i<=n; i++)
if (prime(i))
a[s++] = i;
int m = 0;
for (int i=2; i<s; i++)
for (int j=i-1; j>0; j--)
if (a[i] == a[j]+a[j-1]+1){
m++;
break;
}
if (m >= k) out.println("YES");
else out.println("NO");
out.flush();
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.util.*;
public class A {
Scanner in = new Scanner(System.in);
public class Houses implements Comparable<Houses>{
double x;
double a;
public Houses(double xVal, double aVal){
x = xVal-aVal/2;
a = aVal;
}
@Override
public int compareTo(Houses o) {
return (int) (x - o.x);
}
}
public void solve2(ArrayList<Houses> list,int t){
Collections.sort(list);
int count = 2; //beginning and end
for(int f = 0; f < list.size()-1; f++){
if(list.get(f+1).x-list.get(f).x-list.get(f).a > t){
count+=2;
}
else if(list.get(f+1).x-list.get(f).x-list.get(f).a == t){
count++;
}
}
System.out.println(count);
}
public void solve(){
ArrayList<Houses> list = new ArrayList<Houses>();
int n = in.nextInt();
int t = in.nextInt();
for(int i = 0; i < n; i++){
list.add(new Houses(in.nextDouble(),in.nextDouble()));
}
solve2(list,t);
}
public static void main(String[] args){
A p = new A();
p.solve();
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
public class Main {
public static void deal(int n,int m,int k,int[][] d1,int[][] d2) {
if(k % 2 == 1) {
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
System.out.print("-1 ");
}
System.out.println();
}
return;
}
int[][][] dp = new int[k/2+1][n][m];
for(int i=0;i<k/2;i++) {
for(int j=0;j<n;j++) {
for(int l=0;l<m;l++) {
int min = Integer.MAX_VALUE;
if(j>0) min = Math.min(min,d2[j-1][l]+dp[i][j-1][l]);
if(j<n-1) min = Math.min(min,d2[j][l]+dp[i][j+1][l]);
if(l>0) min = Math.min(min,d1[j][l-1]+dp[i][j][l-1]);
if(l<m-1) min = Math.min(min,d1[j][l]+dp[i][j][l+1]);
dp[i+1][j][l] = min;
}
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
System.out.print(dp[k/2][i][j]*2);
System.out.print(" ");
}
System.out.println();
}
}
public static void main(String[] args) {
MyScanner scanner = new MyScanner();
int n = scanner.nextInt();
int m = scanner.nextInt();
int k = scanner.nextInt();
int[][] d1 = new int[n][m-1];
int[][] d2 = new int[n-1][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m-1;j++) {
d1[i][j] = scanner.nextInt();
}
}
for(int i=0;i<n-1;i++) {
for(int j=0;j<m;j++) {
d2[i][j] = scanner.nextInt();
}
}
deal(n,m,k,d1,d2);
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A{
public static BufferedReader k;
public static BufferedWriter z;
public static void main(String [] args)throws IOException{
k = new BufferedReader(new InputStreamReader(System.in));
z = new BufferedWriter(new OutputStreamWriter(System.out));
String[] dat = k.readLine().split(" ");
long l = Long.parseLong(dat[0]);
long r = Long.parseLong(dat[1]);
if(r-l<=1){
z.write(-1+"\n");
}
else if(r-l == 2){
if((l&1)!=0){
z.write(-1+"\n");
}
else{
z.write(l+" "+(l+1)+" "+r+"\n");
}
}
else{
if(l%2==0){
z.write(l+" "+(l+1)+" "+(l+2)+"\n");
}
else{
z.write((l+1)+" "+(l+2)+" "+(l+3)+"\n");
}
}
z.flush();
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author null
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Input in = new Input(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, Input in, PrintWriter out) {
try {
int n = in.readInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.readInt();
}
Arrays.sort(a);
boolean[] b = new boolean[n];
int ans = 0;
while (true) {
int x = 0;
for (int i = 0; i < n; i++) {
if (!b[i] && x == 0) {
x = a[i];
}
if (x != 0 && a[i] % x == 0) {
b[i] = true;
}
}
if (x == 0) {
break;
}
ans++;
}
out.println(ans);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
static class Input {
public final BufferedReader reader;
private String line = "";
private int pos = 0;
public Input(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
private boolean isSpace(char ch) {
return ch <= 32;
}
public String readWord() throws IOException {
skip();
int start = pos;
while (pos < line.length() && !isSpace(line.charAt(pos))) {
pos++;
}
return line.substring(start, pos);
}
public int readInt() throws IOException {
return Integer.parseInt(readWord());
}
private void skip() throws IOException {
while (true) {
if (pos >= line.length()) {
line = reader.readLine();
pos = 0;
}
while (pos < line.length() && isSpace(line.charAt(pos))) {
pos++;
}
if (pos < line.length()) {
return;
}
}
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class CottageVillage
{
public Scanner in = new Scanner(System.in);
public PrintStream out = System.out;
public int n, t;
public Pair[] v;
public void main()
{
n = in.nextInt();
t = in.nextInt();
int i;
v = new Pair[n];
for(i=0;i<n;++i) v[i] = new Pair(in.nextInt() * 2, in.nextInt());
Arrays.sort(v);
int res = 2;
for(i=0;i+1<n;++i)
{
if(v[i].x + v[i].y + 2*t == v[i+1].x - v[i+1].y) ++res;
else if(v[i].x+v[i].y+2*t < v[i+1].x-v[i+1].y) res +=2;
}
out.println(res);
}//end public void main()
//int pair
private class Pair implements Comparable<Pair>
{
public int x, y;
public Pair(int xx, int yy) { x = xx; y = yy; }
public int compareTo(Pair u)
{
if(x!=u.x) return x-u.x;
return y-u.y;
}
public String toString() { return "(" + x + "," + y + ")"; }
}
public static void main(String[] args)
{
(new CottageVillage()).main();
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class C {
void solve(){
int n = readInt();
int q = readInt();
int max = 0;
int[] a = new int[n];
Deque<Integer> deque = new ArrayDeque<>();
for(int i = 0;i<n;i++){
a[i] = readInt();
deque.addLast(a[i]);
max = Math.max(max, a[i]);
}
List<String> ans = new ArrayList<>();
while(deque.peekFirst() != max){
int one = deque.pollFirst();
int two = deque.pollFirst();
ans.add(one + " " + two);
deque.addFirst(one > two ? one : two);
deque.addLast(one > two ? two : one);
if(one == max) break;
}
for(int i = 0;i<n;i++){
a[i] = deque.pollFirst();
}
for(int i = 0;i<q;i++){
long x = readLong();
if(x <= ans.size()){
out.println(ans.get((int)x - 1));
continue;
}
x -= ans.size();
int y =(int) (x%(n - 1) - 1%(n - 1) + (n - 1)) % (n - 1) + 1;
out.println(max + " " + a[y]);
}
}
public static void main(String[] args) {
new C().run();
}
void run(){
init();
solve();
out.close();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init(){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
String readLine(){
try{
return in.readLine();
}catch(Exception ex){
throw new RuntimeException(ex);
}
}
String readString(){
while(!tok.hasMoreTokens()){
String nextLine = readLine();
if(nextLine == null) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt(){
return Integer.parseInt(readString());
}
long readLong(){
return Long.parseLong(readString());
}
double readDouble(){
return Double.parseDouble(readString());
}
}
|
linear
|
1180_C. Valeriy and Deque
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
import static java.lang.Integer.*;
import static java.lang.Double.*;
import java.lang.Math.*;
public class two_squares {
public static void main(String[] args) throws Exception {
new two_squares().run();
}
public void run() throws Exception {
FastIO file = new FastIO();
double x1 = file.nextInt();
double y1 = file.nextInt();
double x2 = file.nextInt();
double y2 = file.nextInt();
double x3 = file.nextInt();
double y3 = file.nextInt();
double x4 = file.nextInt();
double y4 = file.nextInt();
double minx1, maxx1, miny1, maxy1;
minx1 = Math.min(x1, Math.min(x2, Math.min(x3, x4)));
maxx1 = Math.max(x1, Math.max(x2, Math.max(x3, x4)));
miny1 = Math.min(y1, Math.min(y2, Math.min(y3, y4)));
maxy1 = Math.max(y1, Math.max(y2, Math.max(y3, y4)));
double x5 = file.nextInt();
double y5 = file.nextInt();
double x6 = file.nextInt();
double y6 = file.nextInt();
double x7 = file.nextInt();
double y7 = file.nextInt();
double x8 = file.nextInt();
double y8 = file.nextInt();
double minx2, maxx2, miny2, maxy2;
minx2 = Math.min(x5, Math.min(x6, Math.min(x7, x8)));
maxx2 = Math.max(x5, Math.max(x6, Math.max(x7, x8)));
miny2 = Math.min(y5, Math.min(y6, Math.min(y7, y8)));
maxy2 = Math.max(y5, Math.max(y6, Math.max(y7, y8)));
Point _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16;
_1 = new Point(x1, y1);
_2 = new Point(x2, y2);
_3 = new Point(x3, y3);
_4 = new Point(x4, y4);
_5 = new Point(x5, y5);
_6 = new Point(x6, y6);
_7 = new Point(x7, y7);
_8 = new Point(x8, y8);
_9 = new Point(minx1, maxy1);
_10 = new Point(minx1, miny1);
_11 = new Point(maxx1, maxy1);
_12 = new Point(maxx1, miny1);
double m1 = (minx2 + maxx2) / 2;
double m2 = (miny2 + maxy2) / 2;
_13 = new Point(minx2, m2);
_14 = new Point(m1, miny2);
_15 = new Point(maxx2, m2);
_16 = new Point(m1, maxy2);
Point[] a = {_1, _2, _3, _4};
Point[] b = {_5, _6, _7, _8};
boolean works = false;
Line[] aa = {new Line(_9,_10), new Line(_10, _12), new Line(_12, _11), new Line(_11, _9)};
Line[] bb = {new Line(_13, _14), new Line(_14, _15), new Line(_15, _16), new Line(_16, _13)};
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (aa[i].intersection(bb[i]) != null) {
works = true;
}
}
}
for (Point p : b) {
if (p.x >= minx1 && p.x <= maxx1 && p.y >= miny1 && p.y <= maxy1) {
works = true;
}
}
for (Point p : a) {
boolean result = false;
for (int i = 0, j = b.length - 1; i < b.length; j = i++) {
if ((b[i].y > p.y) != (b[j].y > p.y) &&
(p.x < (b[j].x - b[i].x) * (p.y - b[i].y) / (b[j].y-b[i].y) + b[i].x)) {
result = !result;
}
}
if (result) works = true;
}
System.out.println(works ? "YES" : "NO");
}
public static class Point {
double x, y;
public Point(double a, double b) {
x = a;
y = b;
}
}
public static class Line {
Point a, b;
public Line(Point x, Point y) {
a = x;
b = y;
}
public Point intersection(Line o) {
double x1 = a.x;
double y1 = a.y;
double x2 = b.x;
double y2 = b.y;
double x3 = o.a.x;
double y3 = o.a.y;
double x4 = o.b.x;
double y4 = o.b.y;
double denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
double ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3))/denom;
double ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3))/denom;
if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
return new Point((int) (x1 + ua*(x2 - x1)), (int) (y1 + ua*(y2 - y1)));
}
return null;
}
}
public static class FastIO {
BufferedReader br;
StringTokenizer st;
public FastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static long pow(long n, long p, long mod) {
if (p == 0)
return 1;
if (p == 1)
return n % mod;
if (p % 2 == 0) {
long temp = pow(n, p / 2, mod);
return (temp * temp) % mod;
} else {
long temp = pow(n, p / 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 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;
}
}
|
constant
|
994_C. Two Squares
|
CODEFORCES
|
import java.io.*;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
import java.util.TreeSet;
public class ViewAngle{
private static int V,level[][],count=-1,lev_dfs[],degree=0,no_vert_conn_comp=0;
private static Stack <Integer>st=new Stack();
private static LinkedList<Integer > adj[];
private static boolean[][] Visite;
private static boolean [] Visited;
private static TreeSet<Integer> ts=new TreeSet();
// private static HashMap
private static Queue<Pair> queue = new LinkedList<Pair>();
ViewAngle(int V){
V++;
this.V=(V);
adj=new LinkedList[V];
Visite=new boolean[100][100];
Visited=new boolean[V];
lev_dfs=new int[V];
for(int i=0;i<V;i++)
adj[i]=new LinkedList<Integer>();
}
static File inFile,outFile;
static FileWriter fWriter;
static PrintWriter pWriter;
public static void main(String[] args) throws IOException {
inFile=new File("input.txt");
outFile = new File ("output.txt");
fWriter = new FileWriter (outFile);
pWriter = new PrintWriter (fWriter);
Scanner sc = new Scanner (inFile);
int n=sc.nextInt();
int m=sc.nextInt();
char c[][]=new char[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
c[i][j]='.';
}
}
setup(n, m);
int k=sc.nextInt();
for(int i=0;i<k;i++){
int x=sc.nextInt();
int y=sc.nextInt();
queue.add(new Pair(x-1, y-1));
c[x-1][y-1]='X';
level[x-1][y-1]=-1;
Visite[x-1][y-1]=true;
}
BFS(c, n, m);
pWriter.close();
sc.close();
}
static void addEdge(int v,int w){
if(adj[v]==null){
adj[v]=new LinkedList();
}
adj[v].add(w);
}
public static int BFS2(int startVert,int dest){
Visited=new boolean[V];
for(int i=1;i<V;i++){
lev_dfs[i]=-1;
}
Queue<Integer> q=new LinkedList<Integer>();
q.add(startVert);
lev_dfs[startVert]=0;
while(!q.isEmpty()){
int top=q.poll();
Iterator<Integer> i= adj[top].listIterator();
while(i.hasNext()){
int n=i.next();
if(!Visited[n]){
q.add(n);
Visited[n]=true;
lev_dfs[n]=lev_dfs[top]+1;
if(n==dest){
q.clear();
return lev_dfs[n];
}
}
}
}
q.clear();
return -1;
}
public int getEd(){
return degree/2;
}
public void get(int from,int to){
int h=lev_dfs[from]-lev_dfs[to];
if(h<=0){
System.out.println(-1);
}else{
System.out.println(h-1);
}
}
public static void setup(int n,int m){
level=new int[n][m];
Visite=new boolean[n][m];
}
private static boolean check(int x,int y,char c[][]){
if((x>=0 && y>=0) && (x<c.length && y<c[0].length) && c[x][y]=='.'){
return true;
}
return false;
}
public static int BFS(char[][] c,int n,int m)
{
//Visited[s]=true;
// queue.add(new Pair(x,y));
int count=0;
// level[x][y]=-1;
while (!queue.isEmpty())
{
Pair temp = queue.poll();
int x=temp.w;
int y=temp.h;
Visite[x][y]=true;
if(check(x+1,y,c) && !Visite[x+1][y]){
level[x+1][y]=level[x][y]+1;
queue.add(new Pair(x+1, y));
Visite[x+1][y]=true;
}
if(check(x-1,y,c) && !Visite[x-1][y]){
level[x-1][y]=level[x][y]+1;
queue.add(new Pair(x-1, y));
Visite[x-1][y]=true;
}
if(check(x,y+1,c) && !Visite[x][y+1]){
level[x][y+1]=level[x][y]+1;
queue.add(new Pair(x, y+1));
Visite[x][y+1]=true;
}
if(check(x,y-1,c) && !Visite[x][y-1]){
level[x][y-1]=level[x][y]+1;
queue.add(new Pair(x, y-1));
Visite[x][y-1]=true;
}
}
int prev_lev=-1,x=-1,y=-1;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(level[i][j]>=prev_lev){
prev_lev=level[i][j];
x=i;y=j;
}
//System.out.println(level[i][j]+" ");
}
//System.out.println();
}
pWriter.println((x+1)+" "+(y+1));
return V;
}
private void getAns(int startVertex){
for(int i=0;i<adj[startVertex].size();i++){
int ch=adj[startVertex].get(i);
for(int j=0;j<adj[ch].size();j++){
int ch2=adj[ch].get(j);
if(adj[ch2].contains(startVertex)){
System.out.println(startVertex+" "+ch+" "+ch2);
System.exit(0);
}
}
}
}
public long dfs(int startVertex){
// getAns(startVertex);
if(!Visited[startVertex]) {
return dfsUtil(startVertex,Visited);
//return getAns();
}
return 0;
}
private long dfsUtil(int startVertex, boolean[] Visited) {//0-Blue 1-Pink
//System.out.println(startVertex);
int c=1;
long cout=0;
degree=0;
Visited[startVertex]=true;
// lev_dfs[startVertex]=1;
st.push(startVertex);
while(!st.isEmpty()){
int top=st.pop();
Iterator<Integer> i=adj[top].listIterator();
degree+=adj[top].size();
while(i.hasNext()){
// System.out.println(top+" "+adj[top].size());
int n=i.next();
// System.out.print(n+" ");
if( !Visited[n]){
Visited[n]=true;
st.push(n);
// System.out.print(n+" ");
lev_dfs[n]=top;
}
}
// System.out.println("--------------------------------");
}
for(int i=1;i<V;i++){
if(lev_dfs[i]!=0){
System.out.print(lev_dfs[i]+" ");
}
}
return cout;
// System.out.println("NO");
// return c;
}
}
class Pair implements Comparable<Pair>{
int w;
int h;
Pair(int w,int h){
this.w=w;
this.h=h;
}
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
// Sort in increasing order
if(w>o.w){
return 1;
}else if(w<o.w){
return -1;
}else{
if(h>o.h)
return 1;
else if(h<o.h)
return -1;
else
return 0;
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.awt.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class FireAgain {
Point coordinate;
Queue<Point> q = new LinkedList<Point>();
int m, n;
boolean[][] arr;
PrintStream out ;
void bfs(Point start) {
while (!q.isEmpty()) {
Point front = q.poll();
Point p = new Point();
p.x = front.x - 1;
p.y = front.y;
if (p.x >= 1 && p.x <= n && p.y <= m && p.y >= 1) {
if (!arr[p.x][p.y]) {
arr[p.x][p.y] = true;
q.add(p);
}
}
p = new Point();
p.x = front.x + 1;
p.y = front.y;
if (p.x >= 1 && p.x <= n && p.y <= m && p.y >= 1)
if (!arr[p.x][p.y]) {
arr[p.x][p.y] = true;
q.add(p);
}
p = new Point() ;
p.x = front.x;
p.y = front.y + 1;
if (p.x >= 1 && p.x <= n && p.y <= m && p.y >= 1)
if (!arr[p.x][p.y]) {
arr[p.x][p.y] = true;
q.add(p);
}
p = new Point() ;
p.x = front.x;
p.y = front.y - 1;
if (p.x >= 1 && p.x <= n && p.y <= m && p.y >= 1)
if (!arr[p.x][p.y]) {
arr[p.x][p.y] = true;
q.add(p);
}
if (q.size() == 0)
out.print(front.x + " " + front.y);
}
}
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
FireAgain fa = new FireAgain();
Scanner Scan = new Scanner(new FileInputStream("input.txt"));
fa.out = new PrintStream(new File("output.txt"));
fa.n = Scan.nextInt();
fa.m = Scan.nextInt();
int k = Scan.nextInt();
fa.arr = new boolean[2001][2001];
for (int i = 0; i < k; i++) {
fa.coordinate = new Point();
fa.coordinate.x = Scan.nextInt();
fa.coordinate.y = Scan.nextInt();
fa.q.add(fa.coordinate);
fa.arr[fa.coordinate.x][fa.coordinate.y] = true;
}
fa.bfs(fa.q.peek());
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class C {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int n = in.nextInt();
int[] sol = new int[n];
sol[0] = 1;
int mod = 1000000007;
int maxind = 0;
boolean f = true;
for (int i = 0; i < n; i++) {
if (!f) {
//int accum = sol[0];
for (int j = 1; j <= maxind; j++) {
sol[j] += sol[j-1];
sol[j] %= mod;
}
//out.println(Arrays.toString(sol));
}
if (in.next().equals("f")) {
maxind++;
f = true;
}
else {
f = false;
}
}
int ans = 0;
for (int i = 0; i <= maxind; i++) {
ans += sol[i];
ans %= mod;
}
out.println(ans);
finish();
}
public static void finish() {
out.close();
in.close();
System.exit(0);
}
static class InputReader implements Iterator<String>, Closeable {
// Fast input reader. Based on Kattio.java from open.kattis.com
// but has method names to match Scanner
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
public InputReader(InputStream i) {
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasNext() {
return peekToken() != null;
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public String next() {
return nextToken();
}
public String nextLine() {
try {
line = r.readLine();
} catch (IOException e) {
line = null;
}
token = null;
st = null;
return line;
}
public void close() {
try {
r.close();
} catch (IOException e) {
}
}
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String args[]) {
InputStream intputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(intputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(in, out);
out.close();
}
static class TaskA {
public void solve(InputReader in, PrintWriter out) {
out.println(25);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1[]=br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
long x=Long.parseLong(s1[1]);
long y=Long.parseLong(s1[2]);
long S=0;
long mod=1000000007;
B a[]=new B[n];
TreeMap<Long,Long> tm=new TreeMap<Long,Long>();
long ans[]=new long[n];
for(int i=0;i<n;i++)
{
String s2[]=br.readLine().split(" ");
long l=Long.parseLong(s2[0]);
long r=Long.parseLong(s2[1]);
B b1=new B(l,r);
a[i]=b1;
}
Arrays.sort(a,new The_Comp());
for(int i=0;i<n;i++)
{
long l=a[i].x;
long r=a[i].y;
if(tm.floorKey(l-1)!=null)
{
long u=tm.floorKey(l-1);
long v=l;
if((v-u)*y<x)
{ ans[i]=((r-u)*y)%mod;
if(tm.get(u)>1)
tm.put(u,tm.get(u)-1);
else
tm.remove(u);
}
else
{ ans[i]=(x+(r-l)*y)%mod; }
}
else
ans[i]=(x+(r-l)*y)%mod;
S=(S+ans[i])%mod;
if(tm.containsKey(r))
tm.put(r,1+tm.get(r));
else
tm.put(r,(long)1);
}
System.out.println(S);
}
}
class The_Comp implements Comparator<B>
{
public int compare(B b1,B b2)
{
if(b1.x>b2.x)
return 1;
else if(b1.x==b2.x)
{
if(b1.y>b2.y)
return 1;
else if(b1.y==b2.y)
return 0;
else
return -1;
}
else
return -1;
}
}
class B
{
long x=(long)1;
long y=(long)1;
public B(long l1,long l2)
{ x=l1; y=l2; }
}
|
nlogn
|
1061_D. TV Shows
|
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.util.Iterator;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
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);
TaskE2 solver = new TaskE2();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++) {
solver.solve(i, in, out);
}
out.close();
}
static class TaskE2 {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int m = in.readInt();
int[][] a = in.readIntTable(n, m);
int[][] id = new int[n + 1][1 << n];
int[][] val = new int[n + 1][1 << n];
ArrayUtils.fill(id, m);
int[] sum = new int[1 << n];
int[] low = new int[1 << n];
boolean[] base = new boolean[1 << n];
int[] vv = new int[1 << n];
for (int i = 1; i < (1 << n); i++) {
low[i] = Integer.bitCount(Integer.lowestOneBit(i) - 1);
int current = i;
base[i] = true;
vv[i] = i;
for (int j = 0; j < n; j++) {
current = current << 1;
current += current >> n;
current -= (current >> n) << n;
if (current < i) {
base[i] = false;
vv[i] = vv[current];
break;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 1; j < (1 << n); j++) {
sum[j] = sum[j - (1 << low[j])] + a[low[j]][i];
}
for (int j = 1; j < (1 << n); j++) {
sum[vv[j]] = Math.max(sum[vv[j]], sum[j]);
}
for (int j = 1; j < (1 << n); j++) {
if (!base[j]) {
continue;
}
for (int k = n - 1; k >= 0; k--) {
if (sum[j] > val[k][j]) {
val[k + 1][j] = val[k][j];
id[k + 1][j] = id[k][j];
val[k][j] = sum[j];
id[k][j] = i;
} else {
break;
}
}
}
}
int[] tempVal = new int[n];
int[] tempId = new int[n];
for (int i = 1; i < (1 << n); i++) {
if (!base[i]) {
for (int j = 0; j < n; j++) {
val[j][i] = val[j][vv[i]];
id[j][i] = id[j][vv[i]];
}
} else {
for (int j = 0; j < n; j++) {
tempVal[j] = val[j][i];
tempId[j] = id[j][i];
}
ArrayUtils.orderBy(tempId, tempVal);
for (int j = 0; j < n; j++) {
val[j][i] = tempVal[j];
id[j][i] = tempId[j];
}
}
}
int[] at = new int[1 << n];
int[] current = new int[1 << n];
int[] next = new int[1 << n];
int all = (1 << n) - 1;
for (int i = 0; i < m; i++) {
System.arraycopy(current, 0, next, 0, (1 << n));
for (int j = 1; j < (1 << n); j++) {
if (at[j] == n || id[at[j]][j] != i) {
continue;
}
int other = all - j;
for (int k = other; k > 0; k = (k - 1) & other) {
next[k + j] = Math.max(next[k + j], current[k] + val[at[j]][j]);
}
next[j] = Math.max(next[j], val[at[j]][j]);
at[j]++;
}
int[] temp = current;
current = next;
next = temp;
}
out.printLine(current[all]);
}
}
static abstract class IntAbstractStream implements IntStream {
public String toString() {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
if (first) {
first = false;
} else {
builder.append(' ');
}
builder.append(it.value());
}
return builder.toString();
}
public boolean equals(Object o) {
if (!(o instanceof IntStream)) {
return false;
}
IntStream c = (IntStream) o;
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
if (it.value() != jt.value()) {
return false;
}
it.advance();
jt.advance();
}
return !it.isValid() && !jt.isValid();
}
public int hashCode() {
int result = 0;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
result *= 31;
result += it.value();
}
return result;
}
}
static interface IntList extends IntReversableCollection {
public abstract int get(int index);
public abstract void set(int index, int value);
public abstract void addAt(int index, int value);
public abstract void removeAt(int index);
default public void swap(int first, int second) {
if (first == second) {
return;
}
int temp = get(first);
set(first, get(second));
set(second, temp);
}
default public IntIterator intIterator() {
return new IntIterator() {
private int at;
private boolean removed;
public int value() {
if (removed) {
throw new IllegalStateException();
}
return get(at);
}
public boolean advance() {
at++;
removed = false;
return isValid();
}
public boolean isValid() {
return !removed && at < size();
}
public void remove() {
removeAt(at);
at--;
removed = true;
}
};
}
default public void add(int value) {
addAt(size(), value);
}
default public IntList sort(IntComparator comparator) {
Sorter.sort(this, comparator);
return this;
}
default public IntList subList(final int from, final int to) {
return new IntList() {
private final int shift;
private final int size;
{
if (from < 0 || from > to || to > IntList.this.size()) {
throw new IndexOutOfBoundsException("from = " + from + ", to = " + to + ", size = " + size());
}
shift = from;
size = to - from;
}
public int size() {
return size;
}
public int get(int at) {
if (at < 0 || at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size());
}
return IntList.this.get(at + shift);
}
public void addAt(int index, int value) {
throw new UnsupportedOperationException();
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int at, int value) {
if (at < 0 || at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size());
}
IntList.this.set(at + shift, value);
}
public IntList compute() {
return new IntArrayList(this);
}
};
}
}
static interface IntCollection extends IntStream {
public int size();
default public void add(int value) {
throw new UnsupportedOperationException();
}
default public int[] toArray() {
int size = size();
int[] array = new int[size];
int i = 0;
for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
array[i++] = it.value();
}
return array;
}
default public IntCollection addAll(IntStream values) {
for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) {
add(it.value());
}
return this;
}
}
static interface IntIterator {
public int value() throws NoSuchElementException;
public boolean advance();
public boolean isValid();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int[][] readIntTable(int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readIntArray(columnCount);
}
return table;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class Range {
public static IntList range(int from, int to) {
int[] result = new int[Math.abs(from - to)];
int current = from;
if (from <= to) {
for (int i = 0; i < result.length; i++) {
result[i] = current++;
}
} else {
for (int i = 0; i < result.length; i++) {
result[i] = current--;
}
}
return new IntArray(result);
}
}
static class ArrayUtils {
public static void fill(int[][] array, int value) {
for (int[] row : array) {
Arrays.fill(row, value);
}
}
public static int[] range(int from, int to) {
return Range.range(from, to).toArray();
}
public static int[] createOrder(int size) {
return range(0, size);
}
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) {
if (from == 0 && to == array.length) {
new IntArray(array).sort(comparator);
} else {
new IntArray(array).subList(from, to).sort(comparator);
}
return array;
}
public static int[] order(final int[] array) {
return sort(createOrder(array.length), new IntComparator() {
public int compare(int first, int second) {
if (array[first] < array[second]) {
return -1;
}
if (array[first] > array[second]) {
return 1;
}
return 0;
}
});
}
public static void orderBy(int[] base, int[]... arrays) {
int[] order = ArrayUtils.order(base);
order(order, base);
for (int[] array : arrays) {
order(order, array);
}
}
public static void order(int[] order, int[] array) {
int[] tempInt = new int[order.length];
for (int i = 0; i < order.length; i++) {
tempInt[i] = array[order[i]];
}
System.arraycopy(tempInt, 0, array, 0, array.length);
}
}
static class IntArrayList extends IntAbstractStream implements IntList {
private int size;
private int[] data;
public IntArrayList() {
this(3);
}
public IntArrayList(int capacity) {
data = new int[capacity];
}
public IntArrayList(IntCollection c) {
this(c.size());
addAll(c);
}
public IntArrayList(IntStream c) {
this();
if (c instanceof IntCollection) {
ensureCapacity(((IntCollection) c).size());
}
addAll(c);
}
public IntArrayList(IntArrayList c) {
size = c.size();
data = c.data.clone();
}
public IntArrayList(int[] arr) {
size = arr.length;
data = arr.clone();
}
public int size() {
return size;
}
public int get(int at) {
if (at >= size) {
throw new IndexOutOfBoundsException("at = " + at + ", size = " + size);
}
return data[at];
}
private void ensureCapacity(int capacity) {
if (data.length >= capacity) {
return;
}
capacity = Math.max(2 * data.length, capacity);
data = Arrays.copyOf(data, capacity);
}
public void addAt(int index, int value) {
ensureCapacity(size + 1);
if (index > size || index < 0) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
if (index != size) {
System.arraycopy(data, index, data, index + 1, size - index);
}
data[index] = value;
size++;
}
public void removeAt(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
if (index != size - 1) {
System.arraycopy(data, index + 1, data, index, size - index - 1);
}
size--;
}
public void set(int index, int value) {
if (index >= size) {
throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
}
data[index] = value;
}
public int[] toArray() {
return Arrays.copyOf(data, size);
}
}
static interface IntReversableCollection extends IntCollection {
}
static class IntArray extends IntAbstractStream implements IntList {
private int[] data;
public IntArray(int[] arr) {
data = arr;
}
public int size() {
return data.length;
}
public int get(int at) {
return data[at];
}
public void addAt(int index, int value) {
throw new UnsupportedOperationException();
}
public void removeAt(int index) {
throw new UnsupportedOperationException();
}
public void set(int index, int value) {
data[index] = value;
}
}
static interface IntComparator {
public int compare(int first, int second);
}
static interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
public IntIterator intIterator();
default public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private IntIterator it = intIterator();
public boolean hasNext() {
return it.isValid();
}
public Integer next() {
int result = it.value();
it.advance();
return result;
}
};
}
default public int compareTo(IntStream c) {
IntIterator it = intIterator();
IntIterator jt = c.intIterator();
while (it.isValid() && jt.isValid()) {
int i = it.value();
int j = jt.value();
if (i < j) {
return -1;
} else if (i > j) {
return 1;
}
it.advance();
jt.advance();
}
if (it.isValid()) {
return 1;
}
if (jt.isValid()) {
return -1;
}
return 0;
}
}
static class Sorter {
private static final int INSERTION_THRESHOLD = 16;
private Sorter() {
}
public static void sort(IntList list, IntComparator comparator) {
quickSort(list, 0, list.size() - 1, (Integer.bitCount(Integer.highestOneBit(list.size()) - 1) * 5) >> 1,
comparator);
}
private static void quickSort(IntList list, int from, int to, int remaining, IntComparator comparator) {
if (to - from < INSERTION_THRESHOLD) {
insertionSort(list, from, to, comparator);
return;
}
if (remaining == 0) {
heapSort(list, from, to, comparator);
return;
}
remaining--;
int pivotIndex = (from + to) >> 1;
int pivot = list.get(pivotIndex);
list.swap(pivotIndex, to);
int storeIndex = from;
int equalIndex = to;
for (int i = from; i < equalIndex; i++) {
int value = comparator.compare(list.get(i), pivot);
if (value < 0) {
list.swap(storeIndex++, i);
} else if (value == 0) {
list.swap(--equalIndex, i--);
}
}
quickSort(list, from, storeIndex - 1, remaining, comparator);
for (int i = equalIndex; i <= to; i++) {
list.swap(storeIndex++, i);
}
quickSort(list, storeIndex, to, remaining, comparator);
}
private static void heapSort(IntList list, int from, int to, IntComparator comparator) {
for (int i = (to + from - 1) >> 1; i >= from; i--) {
siftDown(list, i, to, comparator, from);
}
for (int i = to; i > from; i--) {
list.swap(from, i);
siftDown(list, from, i - 1, comparator, from);
}
}
private static void siftDown(IntList list, int start, int end, IntComparator comparator, int delta) {
int value = list.get(start);
while (true) {
int child = ((start - delta) << 1) + 1 + delta;
if (child > end) {
return;
}
int childValue = list.get(child);
if (child + 1 <= end) {
int otherValue = list.get(child + 1);
if (comparator.compare(otherValue, childValue) > 0) {
child++;
childValue = otherValue;
}
}
if (comparator.compare(value, childValue) >= 0) {
return;
}
list.swap(start, child);
start = child;
}
}
private static void insertionSort(IntList list, int from, int to, IntComparator comparator) {
for (int i = from + 1; i <= to; i++) {
int value = list.get(i);
for (int j = i - 1; j >= from; j--) {
if (comparator.compare(list.get(j), value) <= 0) {
break;
}
list.swap(j, j + 1);
}
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.awt.Point;
import java.util.Arrays;
import java.util.Scanner;
public class C {
static int[] DP;
static Point[] Next;
static int[][] pair;
static int[] single;
static int n;
public static int get(int mask) {
if (mask + 1 == (1 << n))
return 0;
if (DP[mask] != -1)
return DP[mask];
int x = 0;
for (;; x++)
if ((mask & (1 << x)) == 0)
break;
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0 || i == x)
continue;
int temp = pair[x][i] + get(mask | (1 << i) | (1 << x));
if (temp < min) {
min = temp;
Next[mask] = new Point(x, i);
}
}
int temp = single[x] + get(mask | (1 << x));
if (temp < min) {
min = temp;
Next[mask] = new Point(x, -1);
}
return DP[mask] = min;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Point start = new Point(in.nextInt(), in.nextInt());
n = in.nextInt();
Point[] A = new Point[n];
for (int i = 0; i < n; i++)
A[i] = new Point(in.nextInt(), in.nextInt());
DP = new int[1 << n];
Next = new Point[1 << n];
Arrays.fill(DP, -1);
pair = new int[n][n];
single = new int[n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
int dx1 = A[i].x - start.x;
int dy1 = A[i].y - start.y;
int dx2 = A[j].x - A[i].x;
int dy2 = A[j].y - A[i].y;
int dx3 = A[j].x - start.x;
int dy3 = A[j].y - start.y;
pair[i][j] = dx1 * dx1 + dy1 * dy1 + dx2 * dx2 + dy2 * dy2
+ dx3 * dx3 + dy3 * dy3;
single[i] = 2 * (dx1 * dx1 + dy1 * dy1);
}
int ans = get(0);
System.out.println(ans);
int mask = 0;
while (mask + 1 != (1 << n)) {
Point temp = Next[mask];
if (temp.y == -1)
System.out.print("0 " + (temp.x + 1) + " ");
else {
System.out
.print("0 " + (temp.x + 1) + " " + (temp.y + 1) + " ");
mask |= (1 << temp.y);
}
mask |= (1 << temp.x);
}
System.out.println("0");
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
//package com.krakn.CF.D1159;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, k;
n = sc.nextInt();
k = sc.nextInt();
int a = (n - k) / 2;
StringBuilder s = new StringBuilder();
int i;
while (s.length() < n) {
i = 0;
while (i < a && s.length() < n) {
s.append("0");
i++;
}
if (s.length() < n) s.append("1");
}
System.out.println(s);
}
}
|
linear
|
1159_D. The minimal unique substring
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A {
static class Scanner{
BufferedReader br=null;
StringTokenizer tk=null;
public Scanner(){
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException{
while(tk==null || !tk.hasMoreTokens())
tk=new StringTokenizer(br.readLine());
return tk.nextToken();
}
public int nextInt() throws NumberFormatException, IOException{
return Integer.valueOf(next());
}
public double nextDouble() throws NumberFormatException, IOException{
return Double.valueOf(next());
}
}
public static void main(String args[]) throws NumberFormatException, IOException{
Scanner sc=new Scanner();
int N=sc.nextInt();
int M=sc.nextInt();
int K=sc.nextInt();
int[] array=new int[N];
for(int i=0;i<N;i++)
array[i]=sc.nextInt();
Arrays.sort(array);
int val=K;
int index=N - 1;
while(index>=0 && val<M){
val--;
val+=array[index];
index--;
}
if (val<M)
System.out.println("-1");
else
System.out.println((N - 1) - index);
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.io.*;
public class Main
{
public static void main(String []args)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=0;
n=Integer.parseInt(br.readLine());
String inp="";
inp=br.readLine();
int no[]=new int[n];
String tinp[]=inp.split(" ");
for(int i=0;i<n;i++)
{
no[i]=Integer.parseInt(tinp[i]);
}
int eve=0,odd=0;
for(int i=0;i<3;i++)
{
int rem=no[i]%2;
if(rem==0)
eve++;
else
odd++;
}
if(eve>1)
{
for(int i=0;i<n;i++)
{
if(no[i]%2==1)
{
System.out.println(i+1);
break;
}
}
}
else
{
for(int i=0;i<n;i++)
{
if(no[i]%2==0)
{
System.out.println(i+1);
break;
}
}
}
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
/**
*
* @author bossbelik
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class Main{
static long N = 100;
static long CNT = 62;
static long INF = 1 << 62;
static long parsenum(long j, long l) {
String k = "";
long cur = 0;
for (int i = (int) j; i <= l; ++i) {
cur *= 10;
cur += k.charAt(i) - '0';
}
return cur;
}
static long gcd(long a, long b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
static boolean pri(int k) {
if (k == 1) return false;
for (int i = 2; i * i <= k; i++) {
if (k % i == 0) return false;
}
return true;
}
static int[] calcz(String s) {
int l = 0;
int r = 0;
int n = s.length();
int z[] = new int[n];
for (int i = 1; i < n; i++) {
if (i <= r) {
z[i] = Math.min(z[i - l], r - i + 1);
}
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) z[i]++;
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
static int[] calcpref(String s) {
int p[] = new int[s.length() + 1];
int n = s.length();
p[0] = 0;
for (int i = 2; i <= n; i++) {
p[i] = p[i - 1];
while (p[i] > 0 && s.charAt(p[i]) != s.charAt(i - 1)) p[i] = p[p[i]];
if (s.charAt(p[i]) == s.charAt(i - 1)) p[i]++;
}
return p;
}
static long MOD = 1000000007;
static long binpow (long a, long n)
{
if (n == 0)
return 1;
if (n % 2 == 1)
return binpow (a % MOD, (n-1) % MOD ) * a % MOD;
else {
long b = binpow(a % MOD, n/2 % MOD) % MOD;
return (b * b) % MOD;
}
}
static int maxnum=105;
static int a[][] = new int[maxnum][maxnum];
static boolean used[] = new boolean[maxnum];
static int curr , cnt ,n ,m;
static void dfs(int i)
{
int j;
boolean flag;
if(i > n)
{
cnt = curr;
return ;
}
flag=true;
for(j = 1 ; j < i; j++)
{
if (used[j] && a[j][i] == 0)
{
flag = false;
break;
}
}
if(flag)
{
curr++;
used[i]=true;
dfs(i+1);
curr--;
}
if(curr + n - i > cnt)
{
used[i]=false;
dfs(i+1);
}
}
public static void main(String[] args) throws Exception
{
//
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter((System.out));
n = in.nextInt();
m = in.nextInt();
for(int i = 1 ; i <= n ; i++)
{
for (int j = 1; j <= n; j++)
{
a[i][j] = in.nextInt();
}
}
dfs(1);
out.printf( "%.10f", (double) m * m * (cnt-1) / (2 * cnt ));
out.println();
out.close();
return;
}
}
|
np
|
839_E. Mother of Dragons
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class AA implements Runnable {
public static void main(String[] args) {
new Thread(new AA()).run();
}
static class Utils {
private Utils() {
}
public static void mergeSort(int[] a) {
mergeSort(a, 0, a.length - 1);
}
private static void mergeSort(int[] a, int leftIndex, int rightIndex) {
final int MAGIC_VALUE = 50;
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergeSort(a, leftIndex, middleIndex);
mergeSort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int leftIndex, int middleIndex,
int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
int[] leftArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++]
: rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
}
BufferedReader br;
StringTokenizer str = new StringTokenizer("");
PrintWriter pw;
public Integer ni() {
return Integer.parseInt(nextToken());
}
public Double nd() {
return Double.parseDouble(nextToken());
}
public Long nl() {
return Long.parseLong(nextToken());
}
public boolean EOF() {
try {
if (!br.ready() && !str.hasMoreTokens()) {
return true;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public String nextToken() {
while (!str.hasMoreTokens())
try {
str = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str.nextToken();
}
@Override
public void run() {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
// try {
// br = new BufferedReader(new FileReader("input.txt"));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// try {
// pw = new PrintWriter(new FileWriter("output.txt"));
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
solve();
pw.close();
}
public void solve() {
int n = ni();
int[] a = new int[n];
int total = 0;
for (int i = 0; i < n; i++) {
a[i] = ni();
total+=a[i];
}
Arrays.sort(a);
int c =0;
int left=0;
for(int i=n-1; i>=0;i--){
if (left<=total){
c++;
left+=a[i];
total-=a[i];
}
}
pw.print(c);
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class P023A {
public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
String string = inScanner.next();
int n = string.length();
for (int l = n - 1; l > 0; l--) {
Set<String> seen = new HashSet<String>();
for (int i = 0; i < n - l + 1; i++) {
String subString = string.substring(i, i + l);
if (seen.contains(subString)) {
System.out.println(l);
return;
}
seen.add(subString);
}
}
System.out.println("0");
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE1 solver = new TaskE1();
solver.solve(1, in, out);
out.close();
}
static class TaskE1 {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int numTests = in.nextInt();
for (int test = 0; test < numTests; test++) {
int n = in.nextInt();
int m = in.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
}
}
int[] d = new int[1 << n];
int[] nd = new int[1 << n];
for (int j = 0; j < m; j++) {
System.arraycopy(d, 0, nd, 0, d.length);
for (int mask = 0; mask < 1 << n; mask++) {
for (int submask = mask; submask > 0; submask = (submask - 1) & mask) {
for (int shift = 0; shift < n; shift++) {
int sum = 0;
for (int i = 0; i < n; i++) {
if ((submask & (1 << i)) > 0) {
sum += a[(i + shift) % n][j];
}
}
nd[mask] = Math.max(nd[mask], d[mask ^ submask] + sum);
}
}
}
int[] t = d;
d = nd;
nd = t;
}
int ans = 0;
for (int x : d) {
ans = Math.max(ans, x);
}
out.println(ans);
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.util.*;
public class A {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int n=in.nextInt(),s=0;
int[] a= new int[n];
for (int i=0;i<n;i++) {a[i]=in.nextInt(); s+=a[i];}
Arrays.sort(a); int k=0,ans=0;
for (int i=n-1;i>=0;i--)
if (k<=s/2) {k+=a[i];ans++;}
System.out.println(ans);
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.util.Scanner;
/**
*
* @author msagimbekov
*/
public class Codeforces908C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int r = sc.nextInt();
int[] x = new int[n];
double[] res = new double[n];
for (int i = 0; i < n; i++) {
x[i] = sc.nextInt();
res[i] = (double)r;
for (int j = i - 1; j >= 0; j--) {
int diff = x[j] - x[i];
if (Math.abs(x[j] - x[i]) <= 2 * r) {
res[i] = Math.max(res[i], res[j] + Math.sqrt(4 * r * r - diff * diff));
}
}
}
for (int i = 0; i < n; i++) {
System.out.print(res[i] + " ");
}
System.out.println("");
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
public class F2 {
private static int n;
private static int[] a;
private static Collection<Segment> answer;
public static void main(String[] args) {
in();
solution();
out();
}
private static void in() {
Scanner in = new Scanner(System.in);
n = in.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
}
private static void solution() {
HashMap<Long, LinkedList<Segment>> segments = new HashMap<>();
for (int i = 0; i < n; i++) {
long sum = 0;
for (int j = i; j < n; j++) {
sum += a[j];
if (segments.containsKey(sum)) {
segments.get(sum).add(new Segment(i, j));
} else {
LinkedList<Segment> toPut = new LinkedList<>();
toPut.add(new Segment(i, j));
segments.put(sum, toPut);
}
}
}
answer = null;
for (Map.Entry<Long, LinkedList<Segment>> sums : segments.entrySet()) {
LinkedList<Segment> currentSegments = sums.getValue();
Collections.sort(currentSegments);
LinkedList<Segment> segmentsWithoutCrossing = new LinkedList<>();
for (Segment segment : currentSegments) {
if ( segmentsWithoutCrossing.isEmpty() || !segmentsWithoutCrossing.getLast().isCrossingToNextSegment(segment)) {
segmentsWithoutCrossing.add(segment);
} else if (segmentsWithoutCrossing.getLast().getR() > segment.getR()) {
segmentsWithoutCrossing.removeLast();
segmentsWithoutCrossing.add(segment);
}
}
answer = segmentsWithoutCrossing.size() > (answer != null ? answer.size() : 0) ? segmentsWithoutCrossing : answer;
}
}
private static void out() {
System.out.println(answer.size());
for (Segment segment : answer) {
System.out.println( (segment.getL() + 1) + " " + (segment.getR() + 1));
}
}
}
class Segment implements Comparable<Segment>{
private int l, r;
Segment(int l, int r) {
this.l = l;
this.r = r;
}
int getL() {
return l;
}
int getR() {
return r;
}
@Override
public int compareTo(Segment segment) {
if (l == segment.l && r == segment.r) {
return 0;
}
return l != segment.l ? l - segment.l : r - segment.r;
}
boolean isCrossingToNextSegment(Segment segment) {
if (l == segment.l || r == segment.r) {
return true;
} else if (l < segment.l) {
return r >= segment.l;
} else if (r > segment.r) {
return l <= segment.r;
} else {
return true;
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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();
}
static class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Arrays.sort(a);
int nc = 0;
for (int i = 0; i < n; i++) {
boolean divs = false;
for (int j = 0; j < i; j++) {
if (a[i] % a[j] == 0) {
divs = true;
break;
}
}
if (!divs) {
nc++;
}
}
out.println(nc);
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.Scanner;
public class sub {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
while(num-->0) {
int a = in.nextInt();
int b = in.nextInt();
int res = 0;
while(a!=0 && b!=0) {
if(a>=b) {
res += a/b;
a %= b;
} else {
res += b/a;
b %= a;
}
}
System.out.println(res);
}
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.util.Scanner;
public class LuckySubstring {
static int[] luck;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int i = -1;
boolean ehLuck = false;
preencheLucky();
while (n >= luck[++i]) {
if (i > 13) {
break;
}
if (n % luck[i] == 0) {
ehLuck = true;
break;
}
}
if (ehLuck) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
static void preencheLucky() {
luck = new int[15];
luck[0] = 4;
luck[1] = 7;
luck[2] = 44;
luck[3] = 47;
luck[4] = 74;
luck[5] = 77;
luck[6] = 444;
luck[7] = 447;
luck[8] = 474;
luck[9] = 477;
luck[10] = 744;
luck[11] = 747;
luck[12] = 774;
luck[13] = 777;
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author gaidash
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
final int SIZE = 256;
final int UNDEF = -1;
int nPixels = in.nextInt();
int groupSize = in.nextInt();
int[] a = in.nextIntArray(nPixels);
boolean[] exists = new boolean[SIZE];
int[] left = new int[SIZE];
int[] right = new int[SIZE];
int[] ret = new int[nPixels];
Arrays.fill(ret, UNDEF);
for (int i = 0; i < nPixels; i++) {
for (int p = 0; p < SIZE; p++) {
if (exists[p] && left[p] <= a[i] && a[i] <= right[p]) {
ret[i] = left[p];
left[a[i]] = left[p];
right[a[i]] = right[p];
break;
}
}
if (ret[i] == UNDEF) {
int l = Math.max(a[i] - groupSize + 1, 0);
int r = l + groupSize - 1;
for (int p = a[i] - 1; p >= 0; p--) {
if (exists[p]) {
if (p >= l) {
int d = p - l;
l = p + 1;
r += d + 1;
}
if (right[p] >= l) {
right[p] = l - 1;
}
}
}
for (int p = a[i] + 1; p < SIZE; p++) {
if (exists[p] && left[p] <= r) {
r = left[p] - 1;
}
}
left[a[i]] = l;
right[a[i]] = r;
ret[i] = l;
}
exists[a[i]] = true;
}
// for (int p : a) {
// System.out.println("Segment for pixel " + p + " = " + "(" + left[p] + " , " + right[p] + ")");
// }
out.print(ret);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
quadratic
|
980_C. Posterized
|
CODEFORCES
|
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws IOException {
File f = new File("input.txt");
Scanner sc = new Scanner(f);
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt")));
int n = sc.nextInt();
int m = sc.nextInt();
boolean[][] grid = new boolean[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
grid[i][j] = false;
Queue<Pair> q = new LinkedList<>();
int cnt = sc.nextInt();
for (int i = 0; i < cnt; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
x--;
y--;
grid[x][y] = true;
q.add(new Pair(x, y));
}
Pair last = new Pair(-1, -1);
while (!q.isEmpty()) {
Pair current = q.poll();
last = current;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i != 0 && j != 0) continue;
if (inside(current.x + i, current.y + j, n, m) &&
!grid[current.x + i][current.y + j]) {
grid[current.x + i][current.y + j] = true;
q.add(new Pair(current.x + i, current.y + j));
//bw.append((current.x + i) + " " + (current.y + j) + "\n");
}
}
}
}
bw.append((last.x + 1) + " " + (last.y + 1) + "\n");
bw.flush();
bw.close();
sc.close();
}
static class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
private static boolean inside(int a, int b, int n, int m) {
return (a >= 0 && a < n && b >= 0 && b < m);
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class C {
private static boolean marked[][] ;
public static void main(String[] args) throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// InputStream inputStream = System.in;
// OutputStream outputStream = System.out;
// InputReader s = new InputReader(inputStream);
// PrintWriter out = new PrintWriter(outputStream);
// input.txt / output.txt
File file = new File("input.txt") ;
Scanner s = new Scanner(file) ;
int n = s.nextInt();
int m = s.nextInt();
marked = new boolean [n + 1 ][m + 1] ;
int k = s.nextInt();
Queue<Point> queue = new LinkedList<Point>();
for(int i =0 ; i < k ; ++i){
int tempX = s.nextInt() ;
int tempY = s.nextInt() ;
marked[tempX][tempY] = true ;
queue.add(new Point(tempX , tempY));
}
Point c = null ;
while(!queue.isEmpty()){
c = queue.poll() ;
if(c.x>1 && !marked[c.x-1][c.y]){
marked[c.x -1 ][c.y] = true ;
queue.add(new Point(c.x-1,c.y));
}
if(c.y>1 && !marked[c.x][c.y-1]){
marked[c.x][c.y-1] = true ;
queue.add(new Point(c.x,c.y-1));
}
if(c.x < n && !marked[c.x+1][c.y]){
marked[c.x + 1 ][c.y] = true ;
queue.add(new Point(c.x + 1,c.y));
}
if(c.y < m && !marked[c.x][c.y+1]){
marked[c.x][c.y+1] = true ;
queue.add(new Point(c.x,c.y+1));
}
}
PrintWriter out = new PrintWriter(new File("output.txt"));
out.println(c.x+" "+c.y);
out.close();
}
static class Point {
int x ;
int y ;
public Point(int x ,int y ){
this.x = x ;
this.y = y ;
}
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
public class algo_1802
{
public static void main(String args[])
{
Scanner ex=new Scanner(System.in);
int n=ex.nextInt();
int k=ex.nextInt();
int x=(int)((Math.sqrt(9.0+8.0*((double)n+(double)k))-3.0)/2.0);
System.out.println(n-x);
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] nums = new int[n];
int kisu = 0;
int gusu = 0;
for(int i = 0 ; i < n ; i++){
nums[i] = sc.nextInt();
if(nums[i] % 2 == 0)gusu++;
if(nums[i] % 2 == 1)kisu++;
}
int ans = -1;
if(gusu == 1){
for(int i = 0 ; i < n ; i++){
if(nums[i]%2 == 0){
ans = i+1;
break;
}
}
}
else{
for(int i = 0 ; i < n ; i++){
if(nums[i]%2 == 1){
ans = i+1;
break;
}
}
}
System.out.println(ans);
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.util.regex.*;
public class Codeforces{
static class MyScanner{
BufferedReader br;
StringTokenizer st;
MyScanner(FileReader fileReader){
br = new BufferedReader(fileReader);
}
MyScanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String nn(){
while(st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
char nc(){
return nn().charAt(0);
}
int ni(){
return Integer.parseInt(nn());
}
long nl(){
return Long.parseLong(nn());
}
double nd(){
return Double.parseDouble(nn());
}
int[] niArr0(int n){
int[] ar = new int[n];
for(int i = 0; i < n; i++) ar[i] = ni();
return ar;
}
int[] niArr1(int n){
int[] ar = new int[n + 1];
for(int i = 1; i <= n; i++) ar[i] = ni();
return ar;
}
long[] nlArr0(int n){
long[] ar = new long[n];
for(int i = 0; i < n; i++) ar[i] = nl();
return ar;
}
}
public static <T> void mprintln(T ... ar){
for(T i: ar) out.print(i + " ");
out.println();
}
private static PrintWriter out;
public static void main(String[] args) throws FileNotFoundException{
// Input from file
// File inputFile = new File("JavaFile.txt");
// File outputFile = new File("JavaOutputFile.txt");
// FileReader fileReader = new FileReader(inputFile);
// Here it ends
MyScanner sc = new MyScanner();
// MyScanner sc = new MyScanner(fileReader);
out = new PrintWriter(new BufferedOutputStream(System.out)); // Output to console
// out = new PrintWriter(new PrintStream(outputFile)); // Output to file
getAns(sc);
out.close();
}
private static void getAns(MyScanner sc){
int n = sc.ni();
long[] ar = sc.nlArr0(n);
HashMap<Long, ArrayList<int[]>> map = new HashMap();
for(int i = 0; i < n; i++){
long cur = 0;
for(int j = i; j >= 0; j--){
cur += ar[j];
if(!map.containsKey(cur)) map.put(cur, new ArrayList());
map.get(cur).add(new int[]{j + 1, i + 1});
}
}
// System.out.println(map);
Set<Long> set = map.keySet();
// System.out.println(set);
ArrayList<int[]> ans = new ArrayList();
for(Long l: set){
ArrayList<int[]> cur = new ArrayList();
int right = -1;
for(int[] arc: map.get(l)) if(arc[0] > right){
right = arc[1];
cur.add(arc);
}
if(cur.size() > ans.size()) ans = cur;
}
out.println(ans.size());
for(int[] arc: ans) mprintln(arc[0], arc[1]);
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.InputMismatchException;
import java.io.*;
import java.util.Vector;
import java.util.Collections;
import java.util.Arrays;
/**
* Generated by Contest helper plug-in
* Actual solution is at the bottom
*/
public class Main {
public static void main(String[] args) {
InputReader in = new StreamInputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in, out);
}
public static void run(InputReader in, PrintWriter out) {
Solver solver = new Sellerman();
solver.solve(1, in, out);
Exit.exit(in, out);
}
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
@Override
public void close() {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
abstract class InputReader {
private boolean finished = false;
public abstract int read();
public int nextInt() {
return Integer.parseInt(nextToken());
}
public String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public abstract void close();
}
interface Solver {
public void solve(int testNumber, InputReader in, PrintWriter out);
}
class Exit {
private Exit() {
}
public static void exit(InputReader in, PrintWriter out) {
in.setFinished(true);
in.close();
out.close();
}
}
class Sellerman implements Solver {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int x0 = in.nextInt();
int y0 = in.nextInt();
int n = in.nextInt() + 1;
int[] x = new int[n];
int[] y = new int[n];
x[n - 1] = x0;
y[n - 1] = y0;
for (int i = 0; i < n - 1; ++i) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int [][] g = new int[n][n];
for(int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
g[i][j] = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
}
-- n;
int[] dm = new int[1 << n];
int[] prev = new int[1 << n];
byte [] bit = new byte[1 << n];
byte [] item0 = new byte[1 << n];
byte [] item1 = new byte[1 << n];
for (int i = 0; i < n; ++i) {
bit[1 << i] = (byte) i;
}
Arrays.fill(dm, -1);
dm[0] = 0;
int tt[][] = new int[n][n];
for (int i = 0; i < n; ++i)
for (int j =0 ; j < n; ++j) {
tt[i][j] = Math.min(g[n][i] + g[i][j] + g[j][n],
g[n][j] + g[i][j] + g[i][n]);
}
for (int i = 0; i < (1 << n); ++i) {
if (dm[i] == -1)continue;
int t = (i ^ ((1 << n) - 1));
int left = bit[t - (t & (t - 1))];
for (int j = left; j < n; ++j) {
if ((i & (1 << j)) > 0) continue;
int nm = i | (1 << left) | (1 << j);
if (dm[nm] == -1 || dm[nm] > dm[i] + tt[left][j]) {
dm[nm] = dm[i] + tt[left][j];
prev[nm] = i;
item0[nm] = (byte)left;
item1[nm] = (byte)j;
}
}
}
out.println(dm[(1 << n) - 1]);
Vector<Vector<Integer>> path = new Vector<Vector<Integer>> () ;
int cmask = (1 << n) - 1;
while (cmask > 0) {
int p = prev[cmask];
Vector<Integer> tmp = new Vector<Integer> () ;
tmp.add(0);
tmp.add(item0[cmask] + 1);
tmp.add(item1[cmask] + 1);
cmask = prev[cmask];
path.add(tmp);
}
Collections.reverse(path);
int len = 0;
for (Vector<Integer> vec : path)
len += vec.size();
int ans[] = new int[len];
boolean[] valid = new boolean[len];
Arrays.fill(valid, true);
len = 0;
for (Vector<Integer> vec : path) {
for (int ttt : vec) {
ans[len ++] = ttt;
}
}
for (int i = 0; i < len - 1; ++i) {
if (ans[i] == ans[i + 1])
valid[i] = false;
}
for (int i = 0; i < len; ++i) {
if (valid[i]) {
out.print(ans[i] + " ");
}
}
out.print("0");
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class CODEFORCES
{
@SuppressWarnings("rawtypes")
static InputReader in;
static PrintWriter out;
static void solve()
{
int n = in.ni();
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = in.ni();
int cnt = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < i; j++)
if (arr[j] > arr[i])
cnt++;
}
cnt %= 2;
int m = in.ni();
while (m-- > 0)
{
int l = in.ni(), r = in.ni();
int fin = r - l + 1;
fin *= (fin - 1);
fin >>= 1;
if ((fin & 1) == 1)
cnt++;
cnt %= 2;
if ((cnt & 1) == 1)
out.println("odd");
else
out.println("even");
}
}
@SuppressWarnings("rawtypes")
static void soln()
{
in = new InputReader(System.in);
out = new PrintWriter(System.out);
solve();
out.flush();
}
static void debug(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
public static void main(String[] args)
{
new Thread(null, new Runnable()
{
public void run()
{
try
{
soln();
} catch (Exception e)
{
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
// To Get Input
// Some Buffer Methods
static class InputReader<SpaceCharFilter>
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ni()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nl()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = ni();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nl();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.Reader;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.List;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
int m = in.nextInt();
int[] from = new int[m];
int[] to = new int[m];
for (int i = 0; i < m; i++) {
from[i] = in.nextInt() - 1;
to[i] = in.nextInt() - 1;
}
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
KuhnMatchingGraph g = new KuhnMatchingGraph(n, n);
int count = 0;
for (int j = 0; j < m; j++) {
if (from[j] != i && to[j] != i) {
g.addEdge(from[j], to[j]);
++count;
}
}
int cur = (n - 1 + count) - 2 * g.getMaximalMatching();
boolean[] a = new boolean[n];
boolean[] b = new boolean[n];
for (int j = 0; j < m; j++) {
if (from[j] == i) {
a[to[j]] = true;
}
if (to[j] == i) {
b[from[j]] = true;
}
}
for (int j = 0; j < n; j++) {
if (j == i) {
if (!a[j]) ++cur;
} else {
if (!a[j]) ++cur;
if (!b[j]) ++cur;
}
}
ans = Math.min(ans, cur);
}
out.println(ans);
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
}
class KuhnMatchingGraph {
int n;
int m;
List<Integer>[] edges;
int[] p1;
int[] p2;
int[] was;
int VER;
public KuhnMatchingGraph(int n, int m) {
this.n = n;
this.m = m;
edges = new ArrayList[n];
for (int i = 0; i < n; i++) {
edges[i] = new ArrayList<Integer>(2);
}
}
public void addEdge(int from, int to) {
edges[from].add(to);
}
public int getMaximalMatching() {
p1 = new int[n];
p2 = new int[m];
was = new int[n];
VER = 0;
Arrays.fill(p1, -1);
Arrays.fill(p2, -1);
int answer = 0;
for (int i = 0; i < n; i++) {
for (int j : edges[i]) {
if (p2[j] < 0) {
p2[j] = i;
p1[i] = j;
answer++;
break;
}
}
}
for (int i = 0; i < n; i++) {
if (p1[i] >= 0) {
continue;
}
VER++;
if (dfs(i)) {
answer++;
}
}
return answer;
}
boolean dfs(int v) {
if (was[v] == VER) {
return false;
}
was[v] = VER;
for (int i = 0; i < edges[v].size(); i++) {
int e = edges[v].get(i);
if (p2[e] < 0 || dfs(p2[e])) {
p2[e] = v;
p1[v] = e;
return true;
}
}
return false;
}
}
|
cubic
|
387_D. George and Interesting Graph
|
CODEFORCES
|
import java.util.*;
public class Main{
private static final int MAX_SIZE = 100005;
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
if(((m + 1) / 60 < a) || ((m + 1) / 60 == a && (m + 1) % 60 <= b)) {
out(0, 0);
System.exit(0);
}
for(int i = 2; i <= n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
int bb = b + 2 * m + 2;
int aa = a + bb / 60;
bb %= 60;
if((aa < x) || (aa == x && bb <= y)) {
b = b + m + 1;
a = a + b / 60;
b %= 60;
out(a, b);
System.exit(0);
}
a = x;
b = y;
}
b = b + m + 1;
a = a + b / 60;
b = b % 60;
out(a, b);
}
private static void out(int a, int b) {
cout(a);
cout(" ");
cout(b);
}
private static void cout(Object a) {
System.out.print(a);
}
}
|
linear
|
967_A. Mind the Gap
|
CODEFORCES
|
import java.awt.Point;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.StringTokenizer;
import static java.lang.Math.*;
import static java.lang.Integer.*;
import static java.lang.Long.*;
import static java.lang.Character.*;
import static java.lang.String.*;
@SuppressWarnings("unused")
public class round169D {
static PrintWriter out = new PrintWriter(System.out);
static BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer st = new StringTokenizer("");
static int nextInt() throws Exception {
return Integer.parseInt(next());
}
static String next() throws Exception {
while (true) {
if (st.hasMoreTokens()) {
return st.nextToken();
}
String s = br.readLine();
if (s == null) {
return null;
}
st = new StringTokenizer(s);
}
}
public static void main(String[] args)throws Exception {
long l = parseLong(next());
long r = parseLong(next());
long [] min = new long [61];
for(int i = 1 ; i <= 60 ; ++i){//(2^i)-1 is obtained by min[i]^min[i]+1
min[i] = (long) pow(2, i - 1) - 1;
}
for(int i = 60 ; i >= 0 ; --i){//try to get 2^i-1 as answer.
if(min[i] >= r)
continue;
if(min[i] >= l && min[i] + 1 <= r){
out.println((1L << i) - 1);
out.flush();
return;
}
if(min[i] < l){
long one_jump = (long) pow(2, i);
long jumps = (long) ceil((l - min[i]) / (one_jump * 1.0));
long cur = min[i] + (jumps * one_jump);
if(cur >= l && cur + 1 <= r){
out.println((1L << i) - 1);
out.flush();
return;
}
}
}
out.println(0);
out.flush();
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author George Marcus
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
StreamInputReader in = new StreamInputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, StreamInputReader in, PrintWriter out) {
int N = in.readInt();
int K = in.readInt();
int[] A = new int[N];
for(int i = 0; i < N; i++)
A[i] = in.readInt();
int num = 0;
int left = 0;
int right = 0;
int[] seen = new int[100005];
while(right < N && num < K) {
if(seen[A[right]] == 0)
num++;
seen[A[right]]++;
right++;
}
right--;
if(num == K) {
while(seen[A[left]] > 1) {
seen[A[left]]--;
left++;
}
out.print((left + 1) + " " + (right + 1));
return;
}
out.print("-1 -1");
}
}
class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
}
abstract class InputReader {
public abstract int read();
public int readInt() {
return Integer.parseInt(readString());
}
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;
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int T = in.nextInt();
while(T!=0){
T--;
int a = in.nextInt();
int b = in.nextInt();
int ans=0;
while(a>0&&b>0){
if(a>b){
int c = a;
a = b;
b = c;
}
ans += (b-(b%a))/a;
b = b%a;
}
System.out.println(ans);
}
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Stack;
import java.util.StringTokenizer;
public class Test
{
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args)throws Exception
{
Reader.init(System.in);
int n = Reader.nextInt();
int p = Reader.nextInt();
int L = Reader.nextInt();
int R = Reader.nextInt();
int a = 1;
int b = n;
int res = 0;
if(a == L && b == R)
{
res = 0;
}
else if(L != a && R != b && p >= L && p <= R)
{
res = Math.min(p-L, R-p);
res += R- L + 2;
}
else if(L != a && R != b && p < L )
{
res += L-p + 1;
res += R - L +1;
}
else if(L != a && R != b && p > R)
{
res += p-R + 1;
res += R - L +1;
}
else if(a == L && p >=L && p<=R)
{
res += R - p + 1;
}
else if(R == b && p>=L && p<=R)
{
res += p - L + 1;
}
else if(a == L && p > R)
{
res += p - R + 1;
}
else if(R == b && p<L)
{
res += L - p + 1;
}
pw.print(res);
pw.close();
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
public static int pars(String x) {
int num = 0;
int i = 0;
if (x.charAt(0) == '-') {
i = 1;
}
for (; i < x.length(); i++) {
num = num * 10 + (x.charAt(i) - '0');
}
if (x.charAt(0) == '-') {
return -num;
}
return num;
}
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static void init(FileReader input) {
reader = new BufferedReader(input);
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return pars(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
|
constant
|
915_B. Browser
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.text.*;
public class CF_1515_B{
//SOLUTION BEGIN
void pre() throws Exception{}
void solve(int TC) throws Exception{
long N = nl();
if(N%2 == 1){
pn("NO");
return;
}
N /= 2;
boolean yes = ps(N);
if(N%2 == 0)yes |= ps(N/2);
pn(yes?"YES":"NO");
}
boolean ps(long N){
long T = (long)Math.sqrt(N);
while(T*T > N)T--;
while (T*T < N)T++;
return (T*T == N);
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
void exit(boolean b){if(!b)System.exit(0);}
static void dbg(Object... o){System.err.println(Arrays.deepToString(o));}
final long IINF = (long)1e17;
final int INF = (int)1e9+2;
DecimalFormat df = new DecimalFormat("0.00000000000");
double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
static boolean multipleTC = true, memory = true, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
long ct = System.currentTimeMillis();
if (fileIO) {
in = new FastReader("");
out = new PrintWriter("");
} else {
in = new FastReader();
out = new PrintWriter(System.out);
}
//Solution Credits: Taranpreet Singh
int T = multipleTC? ni():1;
pre();
for (int t = 1; t <= T; t++) solve(t);
out.flush();
out.close();
System.err.println(System.currentTimeMillis() - ct);
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new CF_1515_B().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 28).start();
else new CF_1515_B().run();
}
int[][] make(int n, int e, int[] from, int[] to, boolean f){
int[][] g = new int[n][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = to[i];
if(f)g[to[i]][--cnt[to[i]]] = from[i];
}
return g;
}
int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){
int[][][] g = new int[n][][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0};
if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1};
}
return g;
}
int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));}
int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object... o){for(Object oo:o)out.print(oo+" ");}
void pn(Object... o){for(int i = 0; i< o.length; i++)out.print(o[i]+(i+1 < o.length?" ":"\n"));}
void pni(Object... o){for(Object oo:o)out.print(oo+" ");out.println();out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str;
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main{
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] nextArray(long n) {
long[] a = new long[(int) n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
static class FastWriter extends PrintWriter {
FastWriter(){
super(System.out);
}
void println(int[] array) {
for(int i=0; i<array.length; i++) {
print(array[i]+" ");
}
println();
}
void println(long [] array) {
for(int i=0; i<array.length; i++) {
print(array[i]+" ");
}
println();
}
}
static class Interval {
long start,end;
Interval(long start, long end)
{
this.start=start;
this.end=end;
}
}
static int MOD=998244353;
public static void main(String[] args){
FastScanner in = new FastScanner();
FastWriter out = new FastWriter();
Scanner sc=new Scanner(System.in);
int t=in.nextInt();
//int t=1;
while (t-->0){
int n=in.nextInt();
int[] ar=in.nextArray(n);
int[] level=new int[1005];
int j=1;
level[1]=1;
out.println(1);
for (int i = 1; i < n; i++) {
if(ar[i]==1) {
j++;
level[j] = 1;
}else {
while (j>=1){
if(level[j]+1!=ar[i]){
j--;
}else {
break;
}
}
level[j]++;
}
for (int k = 1; k <= j; k++) {
if(k==j){
out.print(level[k]);
}else {
out.print(level[k]+".");
}
}
out.println();
}
}
out.close();
}
static int highestPowerOf2(int n) {
if (n < 1){ return 0; }
int res = 1;
for (int i = 0; i < 8 * Integer.BYTES; i++) {
int curr = 1 << i;
if (curr > n){ break; }
res = curr;
}
return res;
}
static int reduceFraction(int x, int y) {
int d= gcd(x, y);
return x/d+y/d;
}
static boolean subset(int[] ar,int n,int sum){
if(sum==0){
return true;
}
if(n<0||sum<0){
return false;
}
return subset(ar,n-1,sum)||subset(ar,n-1,sum-ar[n]);
}
static boolean isPrime(int n){
if(n<=1) return false;
for(int i = 2;i<=Math.sqrt(n);i++){
if (n % i == 0) return false;
}
return true;
}
static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
static long gcd(long a, long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
static boolean isPowerOfTwo(int n) {
if(n==0||n==1){return false;}
double v = Math.log(n) / Math.log(2);
return ((int)(Math.ceil(v)) == (int)(Math.floor(v)));
}
static boolean isPerfectSquare(int x){
if (x >= 0) {
int sr = (int)Math.sqrt(x);
return ((sr * sr) == x);
}
return false;
}
static int lower_bound(int[] arr, int x) {
int low_limit = 0, high_limit = arr.length, mid = -1;
while (low_limit < high_limit) {
mid = (low_limit + high_limit) / 2;
if (arr[mid] >= x){
high_limit = mid;
}else{
low_limit = mid + 1;
}
}
return low_limit;
}
static int upper_bound(int[] arr, int x) {
int low_limit = 0, high_limit = arr.length, mid = -1;
while (low_limit < high_limit) {
mid = (low_limit + high_limit) / 2;
if (arr[mid] > x){
high_limit = mid;
}else{
low_limit = mid + 1;
}
}
return low_limit;
}
static int binarySearch(int[] ar,int n,int num){
int low=0,high=n-1;
while (low<=high){
int mid=(low+high)/2;
if(ar[mid]==num){
return mid;
}else if(ar[mid]>num){
high=mid-1;
}else {
low=mid+1;
}
}
return -1;
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.*;
/**
* Created by IntelliJ IDEA.
* User: piyushd
* Date: 4/13/11
* Time: 8:07 PM
* To change this template use File | Settings | File Templates.
*/
public class TaskA1 {
void run(){
int n = nextInt();
int ans = 2 * n - (n / 2);
System.out.println(ans);
}
int nextInt(){
try{
int c = System.in.read();
if(c == -1) return c;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return c;
}
if(c == '-') return -nextInt();
int res = 0;
do{
res *= 10;
res += c - '0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
long nextLong(){
try{
int c = System.in.read();
if(c == -1) return -1;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return -1;
}
if(c == '-') return -nextLong();
long res = 0;
do{
res *= 10;
res += c-'0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
double nextDouble(){
return Double.parseDouble(next());
}
String next(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(Character.isWhitespace(c))
c = System.in.read();
do{
res.append((char)c);
}while(!Character.isWhitespace(c=System.in.read()));
return res.toString();
}catch(Exception e){
return null;
}
}
String nextLine(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(c == '\r' || c == '\n')
c = System.in.read();
do{
res.append((char)c);
c = System.in.read();
}while(c != '\r' && c != '\n');
return res.toString();
}catch(Exception e){
return null;
}
}
public static void main(String[] args){
new TaskA1().run();
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String [] args ) {
try{
String str;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedOutputStream bos = new BufferedOutputStream(System.out);
String eol = System.getProperty("line.separator");
byte [] eolb = eol.getBytes();
byte[] spaceb= " ".getBytes();
str = br.readLine();
int n = Integer.parseInt(str);
int ans = 0;
if(n>=0) {
ans = n;
} else {
if ( str.length()==2) {
if(str.charAt(0)!='-') {
int a =Integer.parseInt(str.substring(0,1));
int b = Integer.parseInt(str.substring(1,2));
ans = Math.max(a, b);
} else {
ans = Integer.parseInt(str.substring(1,2));
}
} else {
String s1 = str.substring(0,str.length()-2).concat(str.substring(str.length()-2,str.length()-1));
String s2 = str.substring(0,str.length()-2).concat(str.substring(str.length()-1,str.length()));
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
ans = Math.max(a, b);
}
}
bos.write(new Integer(ans).toString().getBytes());
bos.write(eolb);
bos.flush();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
public void solve () throws Exception {
int n = sc.nextInt();
int k = sc.nextInt();
TreeSet<Integer> bad = new TreeSet<>();
int a [] = new int [n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
Random rnd = new Random();
for (int i = 1; i < n; i++) {
int j = rnd.nextInt(i + 1);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
Arrays.sort(a);
int result = 0;
for (int i = 0; i < n; i++) {
if (!bad.contains(a[i])) {
result++;
long next = (long) a[i] * k;
if (next <= 1000000000)
bad.add((int) next);
}
}
out.println(result);
}
BufferedReader in;
PrintWriter out;
FastScanner sc;
static Throwable uncaught;
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
solve();
} catch (Throwable t) {
Solution.uncaught = t;
} finally {
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread t = new Thread(null, new Solution(), "", (1 << 26));
t.start();
t.join();
if (uncaught != null) {
throw uncaught;
}
}
}
class FastScanner {
BufferedReader reader;
StringTokenizer strTok;
public FastScanner(BufferedReader reader) {
this.reader = reader;
}
public String nextToken() throws IOException {
while (strTok == null || !strTok.hasMoreTokens()) {
strTok = new StringTokenizer(reader.readLine());
}
return strTok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Math.*;
// Solution is at the bottom of code
public class B implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new B(), "", 128 * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
solve();
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken(delim);
}
String readLine() throws IOException{
return in.readLine();
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() throws IOException{
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
}
char[] readCharArray() throws IOException{
return readLine().toCharArray();
}
/////////////////////////////////////////////////////////////////
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
try {
array[index] = readInt();
} catch (Exception e) {
System.err.println(index);
return null;
}
}
return array;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
int[] readIntArrayWithDecrease(int size) throws IOException {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
long readLong() throws IOException{
return Long.parseLong(readString());
}
long[] readLongArray(int size) throws IOException{
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) throws IOException{
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
BigInteger readBigInteger() throws IOException {
return new BigInteger(readString());
}
BigDecimal readBigDecimal() throws IOException {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
Point readPoint() throws IOException{
int x = readInt();
int y = readInt();
return new Point(x, y);
}
Point[] readPointArray(int size) throws IOException{
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
throws IOException{
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<B.IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<B.IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
public IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
public int getRealIndex() {
return index + 1;
}
}
IntIndexPair[] readIntIndexArray(int size) throws IOException {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
protected int precision;
protected String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
static final boolean check(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
static final boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
static final long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
static final Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
void solve() throws IOException {
int n = readInt();
int a = readInt();
int b = readInt();
Map<Integer, Integer> numbers = new HashMap<>();
int[] p = readIntArray(n);
for (int index = 0; index < n; ++index) {
numbers.put(p[index], index);
}
Set<Integer> used = new HashSet<Integer>();
Deque<Integer> q = new ArrayDeque<Integer>();
int[] answers = new int[n];
for (int i = 0; i < n; ++i) {
if (used.contains(p[i])) continue;
int leftSize = 0;
for (int number = p[i], cur = a, next = b;
numbers.containsKey(number) && !used.contains(number);
number = cur - number, cur = (a ^ b ^ cur), next = (a ^ b ^ next)) {
q.addFirst(number);
used.add(number);
++leftSize;
}
for (int number = b - p[i], cur = a, next = b;
numbers.containsKey(number) && !used.contains(number);
number = cur - number, cur = (a ^ b ^ cur), next = (a ^ b ^ next)) {
q.addLast(number);
used.add(number);
}
int curColor = (leftSize & 1);
if ((q.size() & 1) == 1) {
int first = q.peekFirst();
// 0 - a, 1 - b
if (curColor == 0 && (first << 1) == b
||
curColor == 1 && (first << 1) == a) {
q.poll();
curColor ^= 1;
int firstIndex = numbers.get(first);
answers[firstIndex] = curColor;
} else {
int last = q.peekLast();
// 0 - b, 1 - a
if (curColor == 0 && (last << 1) == a
||
curColor == 1 && (first << 1) == b) {
q.poll();
int firstIndex = numbers.get(first);
answers[firstIndex] = curColor;
} else {
out.println("NO");
return;
}
}
}
while (q.size() > 0) {
int first = q.poll();
int second = q.poll();
int firstIndex = numbers.get(first);
int secondIndex = numbers.get(second);
answers[firstIndex] = curColor;
answers[secondIndex] = curColor;
}
}
out.println("YES");
for (int answer : answers) {
out.print(answer + " ");
}
out.println();
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main implements Runnable {
class House implements Comparable<House> {
int x;
int a;
public House(int x, int a) {
this.x = x;
this.a = a;
}
@Override
public int compareTo(House other) {
return x - other.x;
}
}
// private void solution() throws IOException {
// int t = in.nextInt();
// while (t-- > 0) {
// int n =in.nextInt();
// int m = in.nextInt();
// int x1 = in.nextInt();
// int y1 = in.nextInt();
// int x2 = in.nextInt();
// int y2 = in.nextInt();
//
// }
// }
private void solution() throws IOException {
int n = in.nextInt();
int t = in.nextInt();
House[] h = new House[n];
for (int i = 0; i < h.length; ++i) {
h[i] = new House(in.nextInt(), in.nextInt());
}
Arrays.sort(h);
int res = 2;
for (int i = 0; i < h.length - 1; ++i) {
double dist = h[i + 1].x - h[i + 1].a / 2.0 - (h[i].x + h[i].a / 2.0);
if (dist >= t) {
if (dist == t) {
++res;
} else {
res += 2;
}
}
}
out.println(res);
}
public void run() {
try {
solution();
in.reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
private class Scanner {
private BufferedReader reader;
private StringTokenizer tokenizer;
public Scanner(Reader reader) {
this.reader = new BufferedReader(reader);
this.tokenizer = new StringTokenizer("");
}
public boolean hasNext() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String next = reader.readLine();
if (next == null) {
return false;
}
tokenizer = new StringTokenizer(next);
}
return true;
}
public String next() throws IOException {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public String nextLine() throws IOException {
tokenizer = new StringTokenizer("");
return reader.readLine();
}
}
public static void main(String[] args) throws IOException {
new Thread(null, new Main(), "", 1 << 28).start();
}
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
Scanner in = new Scanner(new InputStreamReader(System.in));
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.awt.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int qq = readInt();
while(qq-- > 0) {
pw.println(solve(readInt(), readInt()));
}
pw.close();
}
public static int solve(int a, int b) {
if(a < b) {
return solve(b,a);
}
if(a%b == 0) {
return a / b;
}
return a/b + solve(b,a%b);
}
/* NOTEBOOK CODE */
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
pw.close();
System.exit(0);
}
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A
{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok;
public void go() throws IOException
{
ntok();
int n = ipar();
ArrayList<Integer> list = new ArrayList<>();
ntok();
for (int i = 0; i < n; i++)
{
list.add(ipar());
}
Collections.sort(list);
HashSet<Integer> set = new HashSet<>();
for (int x : list)
{
boolean add = true;
for (int y : set)
{
if (x % y == 0)
{
add = false;
break;
}
}
if (add)
{
set.add(x);
}
}
out.println(set.size());
out.flush();
in.close();
}
public void ntok() throws IOException
{
tok = new StringTokenizer(in.readLine());
}
public int ipar()
{
return Integer.parseInt(tok.nextToken());
}
public int[] iapar(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = ipar();
}
return arr;
}
public long lpar()
{
return Long.parseLong(tok.nextToken());
}
public long[] lapar(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = lpar();
}
return arr;
}
public double dpar()
{
return Double.parseDouble(tok.nextToken());
}
public String spar()
{
return tok.nextToken();
}
public static void main(String[] args) throws IOException
{
new A().go();
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class SolutionArch2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.valueOf(scanner.nextLine());
String s = scanner.nextLine();
int[] arr = Arrays.stream(s.split(" "))
.mapToInt(Integer::valueOf)
.toArray();
int[] prefixSum = new int[n + 1];
for (int i = 0; i < n; i++) {
prefixSum[i + 1] = prefixSum[i] + arr[i];
}
Map<Integer, List<int[]>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int subarraySum = prefixSum[j + 1] - prefixSum[i];
map.putIfAbsent(subarraySum, new ArrayList<>());
int l = i + 1, r = j + 1;
map.get(subarraySum).add(new int[]{l, r});
}
}
List<int[]> resultPairs = new ArrayList<>();
for (Map.Entry<Integer, List<int[]>> e : map.entrySet()) {
List<int[]> result = new ArrayList<>();
int[] curr = new int[2];
List<int[]> pairs = e.getValue();
Collections.sort(pairs, Comparator.<int[]>comparingInt(a -> a[1]));
for (int[] next : pairs) {
if (next[0] > curr[1]) {
result.add(next);
curr = next;
}
}
if (resultPairs.size() < result.size()) {
resultPairs = result;
}
}
printResult(resultPairs);
}
private static void printResult(List<int[]> list) {
StringBuilder sb = new StringBuilder();
sb.append(list.size()).append("\n");
for (int[] pair : list) {
sb.append(pair[0]).append(" ").append(pair[1]).append("\n");
}
System.out.print(sb);
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static int MOD = 1000000007;
// After writing solution, quick scan for:
// array out of bounds
// special cases e.g. n=1?
// npe, particularly in maps
//
// Big numbers arithmetic bugs:
// int overflow
// sorting, or taking max, after MOD
void solve() throws IOException {
int T = ri();
for (int Ti = 0; Ti < T; Ti++) {
int n = ri();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ri();
Deque<int[]> stack = new ArrayDeque<>();
stack.addLast(new int[]{1});
pw.println("1");
for (int i = 1; i < n; i++) {
if (a[i] == 1) {
int[] prev = stack.peekLast();
int[] curr = new int[prev.length+1];
System.arraycopy(prev, 0, curr, 0, prev.length);
curr[curr.length-1] = 1;
printArr(curr);
stack.addLast(curr);
continue;
}
while (!stack.isEmpty()) {
int[] prev = stack.removeLast();
if (a[i] == prev[prev.length-1] + 1) {
prev[prev.length-1]++;
printArr(prev);
stack.addLast(prev);
break;
} else {
continue;
}
}
}
}
}
// IMPORTANT
// DID YOU CHECK THE COMMON MISTAKES ABOVE?
void printArr(int[] a) {
pw.print(a[0]);
for (int j = 1; j < a.length; j++) pw.print("." + a[j]);
pw.println();
}
// Template code below
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
Main m = new Main();
m.solve();
m.close();
}
void close() throws IOException {
pw.flush();
pw.close();
br.close();
}
int ri() throws IOException {
return Integer.parseInt(br.readLine().trim());
}
long rl() throws IOException {
return Long.parseLong(br.readLine().trim());
}
int[] ril(int n) throws IOException {
int[] nums = new int[n];
int c = 0;
for (int i = 0; i < n; i++) {
int sign = 1;
c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
nums[i] = x * sign;
}
while (c != '\n' && c != -1) c = br.read();
return nums;
}
long[] rll(int n) throws IOException {
long[] nums = new long[n];
int c = 0;
for (int i = 0; i < n; i++) {
int sign = 1;
c = br.read();
long x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
nums[i] = x * sign;
}
while (c != '\n' && c != -1) c = br.read();
return nums;
}
int[] rkil() throws IOException {
int sign = 1;
int c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
return ril(x);
}
long[] rkll() throws IOException {
int sign = 1;
int c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
return rll(x);
}
char[] rs() throws IOException {
return br.readLine().toCharArray();
}
void sort(int[] A) {
Random r = new Random();
for (int i = A.length-1; i > 0; i--) {
int j = r.nextInt(i+1);
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
Arrays.sort(A);
}
void printDouble(double d) {
pw.printf("%.16f", d);
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
@SuppressWarnings("unused")
public class Solution{
static long inf = (long)1e18+100;
static final long mod = (long)1e9+7;
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int tt = 1;
outer:
while(tt-->0) {
int n = fs.nextInt(), T = fs.nextInt();
int[] t = new int[n], g = new int[n];
for(int i=0;i<n;i++) {
t[i] = fs.nextInt(); g[i] = fs.nextInt();
}
//dp[mask][pre] -- number of ways to order mask songs last song has prev genre
long[][] dp = new long[1<<n][4];
dp[0][0] = 1;
long ans = 0;
for(int mask=0;mask<(1<<n);mask++) {
for(int pre=0;pre<=3;pre++) {
for(int i=0;i<n;i++)
if((mask&(1<<i))==0 && g[i]!=pre)
dp[mask^(1<<i)][g[i]] = add(dp[mask^(1<<i)][g[i]], dp[mask][pre]);
int sum = 0;
for(int i=0;i<n;i++) {
if((mask&(1<<i))!=0) sum += t[i];
}
if(sum==T) ans = add(ans, dp[mask][pre]);
}
}
out.println(ans);
}
out.close();
}
static long add(long a, long b) {
a += b;
if(a>mod) return a - mod;
return a;
}
static final Random random=new Random();
static <T> void shuffle(T[] arr) {
int n = arr.length;
for(int i=0;i<n;i++ ) {
int k = random.nextInt(n);
T temp = arr[k]; arr[k] = arr[i]; arr[i] = temp;
}
}
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n); int temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n); long temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void reverse(int[] arr, int l, int r) {
for(int i=l;i<l+(r-l)/2;i++){
int temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp;
}
}
static void reverse(long[] arr, int l, int r) {
for(int i=l;i<l+(r-l)/2;i++){
long temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp;
}
}
static <T> void reverse(T[] arr, int l, int r) {
for(int i=l;i<l+(r-l)/2;i++) {
T temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp;
}
}
static class FastScanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next(){
while(!st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
} catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt(){
return Integer.parseInt(next());
}
public int[] readArray(int n){
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = nextInt();
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().toCharArray()[0];
}
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
InputReader in = new InputReader(System.in);
int n = in.readInt();
int m = in.readInt();
int k = in.readInt();
long wrong = n - m;
long c = wrong * (k) + k - 1;
long xk = n - c;
if (xk <= 0)
System.out.println((n - wrong) % 1000000009);
else {
long x = (long) Math.ceil(xk / (k * 1.0));
long power = Long.parseLong((BigInteger.valueOf(2).modPow(
BigInteger.valueOf(x + 1), BigInteger.valueOf(1000000009))
.subtract(BigInteger.valueOf(2))) + "");
power += 1000000009;
power %= 1000000009;
long first = (power * k) % 1000000009;
// System.out.println(first);
first += (n - x * k - wrong);
System.out.println(first % 1000000009);
}
}
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;
}
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int []a = new int [n];
boolean []used = new boolean[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a);
int ans = 0;
for (int i = 0; i < used.length; i++) {
if (!used[i]){
ans++;
for (int j = i; j < used.length; j++) {
if (a[j]%a[i] == 0){
used[j] = true;
}
}
}
}
System.out.print(ans);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class A125D2 {
public static void main(String[] args) throws Exception {
InputReader in = new InputReader(System.in);
System.out.println(0 + " " + 0 + " " + in.nextInt());
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class D {
static HashMap<Long, Integer> comp = new HashMap<Long, Integer>();
static HashMap<Integer, Long> rev = new HashMap<Integer, Long>();
static long freq[];
public static void main(String[] args) {
FastScanner in = new FastScanner();
int n = in.nextInt();
long a[] = new long[n];
long copy[] = new long[n];
long sum = 0;
for(int i = 0; i < n; i++){
a[i] = in.nextLong();
copy[i] = a[i];
sum+=a[i];
}
Arrays.sort(copy);
for(int i = 0; i < n; i++) //Compress values to be 1-indexed
if(!comp.containsKey(copy[i])){
comp.put(copy[i], (comp.size()+1));
//rev.put(comp.get(copy[i]), copy[i]);
}
// BIT bit = new BIT(n);
freq = new long[n+1];
Arrays.fill(freq, 0);
for(int i = 0; i < n; i++){
int v = comp.get(a[i]);
freq[v]++;
}
long res = 0;
BigInteger res2 = new BigInteger("0");
for(int i = 0; i < n; i++){ //Go through each element in the array
long x = a[i];
//freq[comp.get(x)]--;
//Find the amount of values equal to (x-1), x, and (x+1);
long below = getFreq(x-1);
long eq = getFreq(x);
long above = getFreq(x+1);
long other = (n-i)-below-eq-above;
// System.out.println("x= "+x+" b:"+below+" e:"+eq+" a:"+above);
long leaveOut = below*(x-1) + eq*(x) + above*(x+1);
long cur = (sum-leaveOut)-(x*other);
// System.out.println("sum:"+sum+" leave:"+leaveOut+" oth:"+other+" cur:"+cur+"\n");
res2 = res2.add(new BigInteger(""+cur));
res += cur;
sum -= x;
freq[comp.get(x)]--;
}
System.out.println(res2);
}
static long getFreq(long n){
if(!comp.containsKey(n)) return 0;
else return freq[comp.get(n)];
}
static class FastScanner{
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try{
br = new BufferedReader(new FileReader(s));
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while(st == null ||!st.hasMoreElements()){
try {
st = new StringTokenizer(br.readLine());}
catch(IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
String next() {
return nextToken();
}
}
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class practice {
public static void main(String[] args) throws Exception {
//Scanner in = new Scanner(new File("practice.in"));
Scanner in = new Scanner(System.in);
String str = in.nextLine();
long n = Long.parseLong(str.substring(0, str.indexOf(" ")));
long m = Long.parseLong(str.substring(str.indexOf(" ") + 1));
if(m - n < 2) {
System.out.println("-1");
} else {
if(m - n == 2 && m % 2 == 1) {
System.out.println("-1");
} else {
System.out.println((n + n % 2) + " " + (n + 1 + n % 2) + " " + (n + 2 + n % 2));
}
}
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.util.*;
public class ErrorCorrectSystem
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String a = scan.next();
String b = scan.next();
int[][] mismatch = new int[26][26];
for(int i = 0; i < 26; i++) Arrays.fill(mismatch[i], -1);
int[][] pair = new int[2][26];
for(int i = 0; i < 2; i++) Arrays.fill(pair[i], -1);
int hd = 0;
for(int i = 0; i < n; i++) {
if(a.charAt(i) != b.charAt(i)) {
hd++;
mismatch[a.charAt(i)-'a'][b.charAt(i)-'a'] = i;
pair[0][a.charAt(i)-'a'] = i;
pair[1][b.charAt(i)-'a'] = i;
}
}
for(int i = 0; i < 26; i++) {
for(int j = i+1; j < 26; j++) {
if(mismatch[i][j] > -1 && mismatch[j][i] > -1) {
System.out.println(hd-2);
System.out.println((mismatch[i][j]+1)+" "+(mismatch[j][i]+1));
return;
}
}
}
for(int i = 0; i < n; i++) {
if(a.charAt(i) != b.charAt(i)) {
//try a gets b's letter
if(pair[0][b.charAt(i)-'a'] > -1) {
System.out.println(hd-1);
System.out.println((i+1)+" "+(pair[0][b.charAt(i)-'a']+1));
return;
}
}
}
System.out.println(hd);
System.out.println("-1 -1");
}
}
|
linear
|
527_B. Error Correct System
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class AnnoyingPresent {
//UPSOLVED
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
long n = Long.parseLong(st.nextToken()) , m = Long.parseLong(st.nextToken());
long sum = 0;
for(int i=0;i<m;i++){
StringTokenizer st1 = new StringTokenizer(br.readLine());
sum+= n* Long.parseLong(st1.nextToken());
Long a= Long.parseLong(st1.nextToken());
if(a < 0){
if(n % 2 == 0)
sum += n*n / 4*a;
else{
sum += (n/2) * (n/2+1) * a;
}
}
else
sum += (a*(n) * (n-1) / 2);
}
System.out.println((double)sum/n);
}
}
|
linear
|
1009_C. Annoying Present
|
CODEFORCES
|
//package codeforces;
import java.io.PrintWriter;
import java.util.*;
public class codeforces {
public static void main(String[] args) {
PrintWriter out=new PrintWriter(System.out);
Scanner s=new Scanner(System.in);
int t=s.nextInt();
for(int tt=0;tt<t;tt++) {
long n=s.nextInt();
long x=(long)Math.sqrt(n/2);
long y=(long)Math.sqrt(n/4);
if(x*x*2==n || y*y*4==n) {
out.println("YES");
}else {
out.println("NO");
}
}
out.close();
s.close();
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import javafx.util.Pair;
public class Solve6 {
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
new Solve6().solve(pw);
pw.flush();
pw.close();
}
public void solve(PrintWriter pw) throws IOException {
FastReader sc = new FastReader();
int n = sc.nextInt();
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = sc.nextInt();
}
HashMap<Integer, LinkedList<Pair<Integer, Integer>>> h = new HashMap();
for (int i = 1; i <= n; i++) {
int s = 0;
for (int j = i; j >= 1; j--) {
s += a[j];
LinkedList<Pair<Integer, Integer>> l;
if (!h.containsKey(s)) {
l = new LinkedList();
} else {
l = h.get(s);
}
l.add(new Pair(j, i));
h.put(s, l);
}
}
int max = 0, index = 0;
for (Map.Entry<Integer, LinkedList<Pair<Integer, Integer>>> entrySet : h.entrySet()) {
int i = 0, size = 0;
for (Pair<Integer, Integer> pair : entrySet.getValue()) {
if (pair.getKey() > i) {
i = pair.getValue();
size++;
}
}
if (size > max) {
max = size;
index = entrySet.getKey();
}
}
pw.println(max);
int i = 0;
for (Pair<Integer, Integer> pair : h.get(index)) {
if (pair.getKey() > i) {
pw.println(pair.getKey() + " " + pair.getValue());
i = pair.getValue();
}
}
}
static class FastReader {
StringTokenizer st;
BufferedReader br;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public boolean hasNext() throws IOException {
String s = br.readLine();
if (s == null || s.isEmpty()) {
return false;
}
st = new StringTokenizer(s);
return true;
}
public String next() throws IOException {
if (st == null || !st.hasMoreTokens()) {
String s = br.readLine();
if (s.isEmpty()) {
return null;
}
st = new StringTokenizer(s);
}
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.*;
public class First {
StreamTokenizer in;
PrintWriter out;
int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
long nextLong() throws IOException {
in.nextToken();
return (long) in.nval;
}
String nextString() throws IOException {
in.nextToken();
return in.sval;
}
void run() throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
solve();
out.flush();
}
void solve() throws IOException {
int n = nextInt(), k = nextInt(), sum = 0, count = 0;
String str = nextString();
char[] arr = str.toCharArray();
boolean[] bool = new boolean[26];
for(char ch: arr){
bool[((int)ch)-97] = true;
}
for(int i = 0; i < 26; i++){
if(bool[i]){
sum += i+1;
count++;
i += 1;
}
if(count == k) break;
}
if(count == k) out.println(sum);
else out.println(-1);
}
public static void main(String[] args) throws IOException {
new First().run();
}
}
|
linear
|
1011_A. Stages
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class EdE {
static long[] mods = {1000000007, 998244353, 1000000009};
static long mod = mods[0];
public static MyScanner sc;
public static PrintWriter out;
static ArrayList<Integer> primes;
public static void main(String[] omkar) throws Exception{
// TODO Auto-generated method stub
sc = new MyScanner();
out = new PrintWriter(System.out);
int t = sc.nextInt();
primes = new ArrayList<>();
prime(3165);
int[] freq = new int[10000001];
while(t--> 0){
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = readArrayInt(n);
for(int j = 0;j<n;j++){
arr[j] = factorize(arr[j]);
}
int[][] left = new int[n][k+1];
for(int m = 0;m<=k;m++){
int l = 0;
int count = 0;
for(int i = 0;i<n;i++){
if (freq[arr[i]] > 0){
count++;
}
freq[arr[i]]++;
while(count > m){
freq[arr[l]]--;
if (freq[arr[l]] > 0){
count--;
}
l++;
}
left[i][m] = l;
}
while(l < n){
freq[arr[l]]--;
l++;
}
}
long[][] dp = new long[n][k+1];
for(int i=0;i<n;i++){
Arrays.fill(dp[i], Integer.MAX_VALUE);
}
for(int i = 0;i<n;i++){
for(int j = 0;j<=k;j++){
for(int s = 0;s<=j;s++){
if (left[i][s] == 0){
dp[i][j] = 1;
continue;
}
dp[i][j] = Math.min(dp[i][j], dp[left[i][s]-1][j-s]+1);
}
}
}
out.println(dp[n-1][k]);
}
out.close();
}
static class MS{
// TreeSet<Long> set;
HashMap<Long, Integer> map;
public MS() {
// set = new TreeSet<Long>();
map = new HashMap<Long, Integer>();
}
public void add(long x) {
if(map.containsKey(x)){
map.put(x, map.get(x)+1);
}
else{
map.put(x, 1);
// set.add(x);
}
}
public void remove(long x) {
if(!map.containsKey(x))
return;
if(map.get(x)==1){
map.remove(x);
// set.remove(x);
}
else
map.put(x, map.get(x)-1);
}
// public long getFirst() {
// return set.first();
// }
// public long getLast() {
// return set.last();
// }
public int size() {
return map.keySet().size();
}
public void removeAll(int x) {
map.remove(x);
}
public int getFreq(long x){
if (map.containsKey(x))
return map.get(x);
return 0;
}
}
public static void prime(int n){
int[] isPrime = new int[n+1];
Arrays.fill(isPrime, 1);
for(long i = 2;i<=n;i++){
if (isPrime[(int)i] == 1){
for(long j = i*i;j<=n;j+=i){
isPrime[(int)j] = 0;
}
}
}
for(int j = 3;j<=n;j++){
if (isPrime[j] == 1){
primes.add(j);
}
}
}
public static int factorize(long n) {
long prod = 1;
int count = 0;
while (n%2 == 0){
n >>= 1;
count++;
}
if (count > 0 && count%2 == 1)
prod *= 2L;
for (long i : primes) {
if (i*i > n)
break;
count = 0;
while (n % i == 0) {
count++;
n = n / i;
}
if (count > 0 && count%2 == 1)
prod *= i;
}
if (n > 2)
prod *= n;
return (int)prod;
}
public static void sort(int[] array){
ArrayList<Integer> copy = new ArrayList<>();
for (int i : array)
copy.add(i);
Collections.sort(copy);
for(int i = 0;i<array.length;i++)
array[i] = copy.get(i);
}
static String[] readArrayString(int n){
String[] array = new String[n];
for(int j =0 ;j<n;j++)
array[j] = sc.next();
return array;
}
static int[] readArrayInt(int n){
int[] array = new int[n];
for(int j = 0;j<n;j++)
array[j] = sc.nextInt();
return array;
}
static int[] readArrayInt1(int n){
int[] array = new int[n+1];
for(int j = 1;j<=n;j++){
array[j] = sc.nextInt();
}
return array;
}
static long[] readArrayLong(int n){
long[] array = new long[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextLong();
return array;
}
static double[] readArrayDouble(int n){
double[] array = new double[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextDouble();
return array;
}
static int minIndex(int[] array){
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(long[] array){
long minValue = Long.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(double[] array){
double minValue = Double.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static long power(long x, long y){
if (y == 0)
return 1;
if (y%2 == 1)
return (x*power(x, y-1))%mod;
return power((x*x)%mod, y/2)%mod;
}
static void verdict(boolean a){
out.println(a ? "YES" : "NO");
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is
|
cubic
|
1497E2
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class C{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-9;
int n, m;
void run(){
n=sc.nextInt();
m=sc.nextInt();
solve();
}
void solve(){
if(n<m){
int t=n;
n=m;
m=t;
}
int full=(1<<m)-1;
int[][] dp=new int[1<<m][1<<m];
int[][] tmp=new int[1<<m][1<<m];
for(int i=0; i<1<<m; i++){
fill(dp[i], INF);
}
for(int i=0; i<1<<m; i++){
int b1=(i|(i>>1)|(i<<1))&full;
int b2=i;
dp[b1][b2]=Integer.bitCount(i);
debug(Integer.toBinaryString(b1), dp[b1]);
}
debug();
for(int j=0; j<n-1; j++){
for(int i=0; i<1<<m; i++){
System.arraycopy(dp[i], 0, tmp[i], 0, 1<<m);
fill(dp[i], INF);
}
for(int b1=0; b1<1<<m; b1++){
for(int b2=0; b2<1<<m; b2++){
for(int i=0; i<1<<m; i++){
if((b1|i)!=full){
continue;
}
if(false)
debug(Integer.toBinaryString(b1),
Integer.toBinaryString(b2),
Integer.toBinaryString(i));
int b=(i|(i>>1)|(i<<1))&full;
dp[b2|b][i]=min(dp[b2|b][i],
tmp[b1][b2]+Integer.bitCount(i));
}
}
}
debug(j);
for(int i=0; i<1<<m; i++){
debug(Integer.toBinaryString(i), dp[i]);
}
}
int min=INF;
for(int i=0; i<1<<m; i++){
min=min(min, dp[full][i]);
}
debug(min);
int ans=m*n-min;
debug("ans",ans);
println(ans+"");
}
void println(String s){
System.out.println(s);
}
void print(String s){
System.out.print(s);
}
void debug(Object... os){
// System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args){
new C().run();
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;
public class Main {
public static void main(String[] args) throws IOException {
try {
if (new File("input.txt").exists()) {
System.setIn(new FileInputStream("input.txt"));
}
} catch (SecurityException e) {
}
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
boolean[] erat = new boolean [1000 + 1];
int[] primes = new int [1000 + 1];
int pNum = 0;
void run() throws IOException {
for (int i = 2; i <= 1000; i++) {
if (!erat[i]) {
primes[pNum++] = i;
for (int j = i * i; j <= 1000; j += i)
erat[j] = true;
}
}
int[] cnt = new int [1000 + 1];
cnt[2] = 0;
for (int i = 3; i <= 1000; i++) {
cnt[i] = cnt[i - 1];
if (!erat[i]) {
int r = i - 1;
for (int j = 1; j < pNum; j++) {
if (r == primes[j - 1] + primes[j]) {
cnt[i]++;
break;
}
}
}
}
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = nextInt();
int k = nextInt();
out.println(k <= cnt[n] ? "YES" : "NO");
out.close();
}
String nextToken() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.util.Scanner;
public class maestro{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
long mod = (long)Math.pow(10,9)+7;
long[][] arr = new long[N][N];
arr[0][0]=1;
for (int i=1;i<N;i++){
char c = sc.next().charAt(0);
if (c=='f'){
for (int j=1;j<N;j++) arr[i][j] = arr[i - 1][j - 1];
}
else {
long sum=0;
for (int j=N-1;j>=0;j--){
sum=(sum+arr[i-1][j])%mod;
arr[i][j] = sum;
}
}
}
long ans=0;
for (int i=0;i<N;i++) ans=(ans+arr[N-1][i])%mod;
System.out.println(ans);
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class cf {
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
pw.println(n/2+1);
pw.close();
}
}
|
constant
|
964_A. Splits
|
CODEFORCES
|
import java.util.*;
import java.text.*;
import java.io.*;
import java.math.*;
public class code5 {
InputStream is;
PrintWriter out;
static long mod=pow(10,9)+7;
static int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
String arr[];
long dp[][];
void solve() throws IOException
{
int n=ni();
arr=new String[n];
for(int i=0;i<n;i++)
arr[i]=ns();
dp=new long[n+1][n+1];
dp[0][0]=1;
for(int i=0;i<n;i++)
{
long next[]=new long[n+1];
for(int j=0;j<=i;j++)
{
if(arr[i].charAt(0)=='s')
{
next[0]+=dp[i][j];
next[j+1]-=dp[i][j];
}else {
next[j+1]+=dp[i][j];
next[j+2]-=dp[i][j];
}
}
long count=0;
for(int j=0;j<n;j++)
{
count+=next[j];
count=(count+mod)%mod;
dp[i+1][j]=count;
}
}
long ans=0;
for(int i=0;i<n;i++)
{
ans+=dp[n-1][i];
ans%=mod;
}
out.print(ans);
}
long rec(int index,int level)
{
if(index>=arr.length-1)
return 1;
if(dp[index][level]!=-1)
return dp[index][level];
dp[index][level]=0;
if(arr[index].charAt(0)=='s')
{
dp[index][level]+=rec(index+1,level);
dp[index][level]%=mod;
if(level>0)
{
dp[index][level]+=rec(index+1,0);
dp[index][level]%=mod;
}
}
else {
dp[index][level]+=rec(index+1,level+1);
dp[index][level]%=mod;
}
return dp[index][level];
}
double a[],b[],p;
int sum(int i)
{
int sum=0;
while(i!=0)
{
if((i%10)%2==1)
sum+=i%10;
i/=10;
}
return sum;
}
ArrayList<Integer> al[];
void take(int n,int m)
{
al=new ArrayList[n];
for(int i=0;i<n;i++)
al[i]=new ArrayList<Integer>();
for(int i=0;i<m;i++)
{
int x=ni()-1;
int y=ni()-1;
al[x].add(y);
al[y].add(x);
}
}
int check(long n)
{
int count=0;
while(n!=0)
{
if(n%10!=0)
break;
n/=10;
count++;
}
return count;
}
public static int count(int x)
{
int num=0;
while(x!=0)
{
x=x&(x-1);
num++;
}
return num;
}
static long d, x, y;
void extendedEuclid(long A, long B) {
if(B == 0) {
d = A;
x = 1;
y = 0;
}
else {
extendedEuclid(B, A%B);
long temp = x;
x = y;
y = temp - (A/B)*y;
}
}
long modInverse(long A,long M) //A and M are coprime
{
extendedEuclid(A,M);
return (x%M+M)%M; //x may be negative
}
public static void mergeSort(int[] arr, int l ,int r){
if((r-l)>=1){
int mid = (l+r)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,r,mid);
}
}
public static void merge(int arr[], int l, int r, int mid){
int n1 = (mid-l+1), n2 = (r-mid);
int left[] = new int[n1];
int right[] = new int[n2];
for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
int i =0, j =0, k = l;
while(i<n1 && j<n2){
if(left[i]>right[j]){
arr[k++] = right[j++];
}
else{
arr[k++] = left[i++];
}
}
while(i<n1) arr[k++] = left[i++];
while(j<n2) arr[k++] = right[j++];
}
public static void mergeSort(long[] arr, int l ,int r){
if((r-l)>=1){
int mid = (l+r)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,r,mid);
}
}
public static void merge(long arr[], int l, int r, int mid){
int n1 = (mid-l+1), n2 = (r-mid);
long left[] = new long[n1];
long right[] = new long[n2];
for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
int i =0, j =0, k = l;
while(i<n1 && j<n2){
if(left[i]>right[j]){
arr[k++] = right[j++];
}
else{
arr[k++] = left[i++];
}
}
while(i<n1) arr[k++] = left[i++];
while(j<n2) arr[k++] = right[j++];
}
static class Pair implements Comparable<Pair>{
int x,y,k;
int i,dir;
long val;
Pair (int x,int y){
this.x=x;
this.y=y;
}
public int compareTo(Pair o) {
if(this.x!=o.x)
return this.x-o.x;
return this.y-o.y;
}
public String toString(){
return x+" "+y+" "+k+" "+i;}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Long(x).hashCode()*31 + new Long(y).hashCode() ;
}
}
public static boolean isPal(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
public static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x,long y){
if(y==0)
return x;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y){
if(y==0)
return x;
return gcd(y,x%y);
}
public static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
public static int abs(int a,int b){
return (int)Math.abs(a-b);
}
public static long abs(long a,long b){
return (long)Math.abs(a-b);
}
public static int max(int a,int b){
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b){
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b){
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b){
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
void run() throws Exception {
is = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
public void run() {
try {
new code5().run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
//new code5().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 long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
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();
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
public class Main {
public static void main(String[] args){
System.out.println("25");
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.util.Scanner;
import java.util.Vector;
import java.util.HashMap;
import java.util.Comparator;
public class F2{
static class Pair{
int l;
int r;
Pair(int l, int r){
this.l = l;
this.r = r;
}
public String toString(){
return "(" + l + ", " + r + ")";
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n+1];
for(int i = 1;i<=n;++i){
a[i] = in.nextInt();
}
HashMap<Integer, Vector<Pair>> map = new HashMap<>();
for(int i = 1;i<=n;++i){
int sum = 0;
for(int j = i;j<=n;++j){
sum+=a[j];
if(!map.containsKey(sum))
map.put(sum,new Vector<>());
map.get(sum).add(new Pair(i,j));
}
}
Vector<Pair> an = null;
for(Integer key : map.keySet()){
Vector<Pair> vec = map.get(key);
Vector<Pair> ans = new Vector<>();
ans.add(vec.get(0));
int size = 1;
for(int i = 1;i<vec.size();++i){
if(ans.get(size-1).r > vec.get(i).r)
ans.set(size-1,vec.get(i));
else if(ans.get(size-1).r < vec.get(i).l){
ans.add(vec.get(i));
size++;
}
}
if(an == null || an.size() < size) an = ans;
}
StringBuilder res = new StringBuilder().append(an.size() + "\n");
for(int i = 0;i<an.size();++i)
res.append(an.get(i).l + " " + an.get(i).r + "\n");
System.out.println(res);
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class CF {
long getAns(long a, long b) {
if (a == b)
return 1;
if (a < b) {
return getAns(b, a);
}
// a > b
long cnt = (a - 1) / b;
return cnt + getAns(b, a - b * cnt);
}
void solve() {
long a = in.nextLong();
long b = in.nextLong();
out.println(getAns(a, b));
}
FastScaner in;
PrintWriter out;
void run() {
in = new FastScaner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
void runWithFiles() {
in = new FastScaner(new File("input.txt"));
try {
out = new PrintWriter(new File("output.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
solve();
out.close();
}
public static void main(String[] args) {
new CF().run();
}
class FastScaner {
BufferedReader br;
StringTokenizer st;
FastScaner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
FastScaner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
long totalBlocks = 0;
long a[] = new long[n];
for(int i = 0; i < n; ++i) {
a[i] = sc.nextLong();
totalBlocks += a[i];
}
Arrays.sort(a);
long selected = 0;
for(int i = 0; i < n; ++i) {
if(a[i] > selected)
selected++;
}
long leftCols = a[n - 1] - selected;
long remBlocks = totalBlocks - leftCols - n;
System.out.print(remBlocks);
}
}
|
nlogn
|
1061_B. Views Matter
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
static int myLevel;
static int[] level;
static int[] loyalty;
static double get(int n) {
double ret = 0;
for (int mask = 0; mask < 1 << n; mask++) {
int k = Integer.bitCount(mask);
double prob = 1.;
int sum = 0;
for (int i = 0; i < n; i++) {
if (((mask >> i) & 1) == 1) {
prob *= loyalty[i] * .1;
} else {
prob *= (10 - loyalty[i]) * .1;
sum += level[i];
}
}
if (k * 2 > n) {
ret += prob;
} else {
ret += prob * myLevel / (myLevel + sum);
}
}
return ret;
}
static double go(int x, int k, int n) {
if (x == n) {
return get(n);
}
double ret = 0;
for (int i = 0; i <= k && loyalty[x] + i <= 10; i++) {
loyalty[x] += i;
ret = Math.max(go(x + 1, k - i, n), ret);
loyalty[x] -= i;
}
return ret;
}
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
int k = in.nextInt();
myLevel = in.nextInt();
level = new int[n];
loyalty = new int[n];
for (int i = 0; i < n; i++) {
level[i] = in.nextInt();
loyalty[i] = in.nextInt() / 10;
}
out.println(go(0, k, n));
}
}
class FastScanner extends BufferedReader {
boolean isEOF;
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
if (isEOF && ret < 0) {
throw new InputMismatchException();
}
isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= -1 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (!isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Liavontsi Brechka
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static
@SuppressWarnings("Duplicates")
class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int m = in.nextInt();
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) count = (count + 1) % 2;
}
}
StringBuilder res = new StringBuilder();
int l, r, temp;
while (m-- > 0) {
l = in.nextInt() - 1;
r = in.nextInt() - 1;
for (int i = 0; i < (r - l + 1) / 2; i++) {
temp = a[l + i];
a[l + i] = a[r - i];
a[r - i] = temp;
}
count = count ^ (((r - l + 1) * (r - l) / 2) % 2);
res.append(count == 1 ? "odd" : "even").append('\n');
}
out.print(res);
}
}
static class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public int[] nextIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; ++i) {
array[i] = nextInt();
}
return array;
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(readLine());
}
return tokenizer.nextToken();
}
public String readLine() {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
//package Educational35;
//import FastScanner.Competitive;
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 D {
String INPUT = "4\n" +
"1 2 4 3\n" +
"4\n" +
"1 1\n" +
"1 4\n" +
"1 4\n" +
"2 3";
void solve()
{
int n = i();
int[] a = ia(n);
int count = 0 ;
for(int i = 0 ; i<n-1 ; i++)
{
for(int j = i+1; j<n ; j++)
{
if(a[j]<a[i])
{
count++;
}
}
}
int q = i();
for(int i = 0 ; i<q ; i++)
{
int l = i(), r=i();
int mid = (r-l+1)/2;
if(mid%2==0)
{
out.println(count%2==0?"even":"odd");
}
else
{
count++;
out.println(count%2==0?"even":"odd");
}
}
}
///////////////////////////////////////
void run() throws Exception{
is = oj ? System.in: new ByteArrayInputStream(INPUT.getBytes());
//is = System.in;
out = new PrintWriter(System.out);
int t = 1;
while(t-->0) solve();
out.flush();
}
public static void main(String[] args)throws Exception {
new D().run();
}
InputStream is;
PrintWriter out;
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 d() { return Double.parseDouble(s()); }
private char c() { return (char)skip(); }
private String s()
{
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[] sa(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] = sa(m);
return map;
}
private int[] ia(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = i();
return a;
}
private int i()
{
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 l()
{
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
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Coder{
static class FastScanner{
BufferedReader s;
StringTokenizer st;
public FastScanner(){
st = new StringTokenizer("");
s = new BufferedReader(new InputStreamReader(System.in));
}
public int nextInt() throws IOException{
if(st.hasMoreTokens())
return Integer.parseInt(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextInt();
}
}
}
public static void main(String[] args) throws IOException{
FastScanner s = new FastScanner();
PrintWriter ww = new PrintWriter(new OutputStreamWriter(System.out));
int test = s.nextInt(); int cnt=0;
while(test-->0){
int a = s.nextInt();
int b = s.nextInt();
cnt=0;
while(a!=0 && b!=0){
int max = Math.max(a, b);
if(max == b){
int divi = b/a;
b -= divi*a;
cnt+=divi;
}else{
int divi = a/b;
a -= divi*b;
cnt+=divi;
}
// System.out.println(a+" "+b);
}
ww.println(cnt);
}
ww.close();
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Main implements Runnable {
PrintWriter out;
Scanner in;
public static void main(String[] args) throws IOException {
new Thread(new Main()).start();
}
public void run() {
try {
out = new PrintWriter(new BufferedOutputStream(System.out));
in = new Scanner(System.in);
solve();
out.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
public void solve() throws IOException {
int n = in.nextInt();
if (n >= 0) {
out.println(n);
} else {
String s = String.valueOf(n);
int l = s.length();
String s1 = s.substring(0, l - 2);
if (s.charAt(l - 1) > s.charAt(l - 2)) {
s1 += s.charAt(l - 2);
} else {
s1 += s.charAt(l - 1);
}
out.println(Integer.parseInt(s1));
}
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()) {
int n=sc.nextInt();
String s=sc.next();
int sum=0;
for(int i=0;i<s.length();i++) {
if(s.charAt(i)=='+') {
sum++;
}
if(s.charAt(i)=='-'&&sum!=0) {
sum--;
}
}
System.out.println(sum);
}
}
}
|
linear
|
1159_A. A pile of stones
|
CODEFORCES
|
import java.util.*;
public class Main {
static int n=5;
static int[] arr=new int[5];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for (int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
for (int i=0;i<n;i++)
{
if (arr[i]>=0)
{
arr[i]=-arr[i]-1;
}
}
if (n%2!=0)
{
int min=0;
for (int i=1;i<n;i++)
{
if (arr[i]<arr[min])
min=i;
}
arr[min]=-arr[min]-1;
}
for (int x:arr)
{
System.out.print(x + " ");
}
}
}
|
linear
|
1180_B. Nick and Array
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String args[] ) {
FastReader sc = new FastReader();
int n = sc.nextInt();
int m = sc.nextInt();
int[] arr = new int[105];
for(int i=0;i<m;i++){
int a = sc.nextInt();
arr[a]++;
}
for(int i=1;i<=1000;i++){
int sum=0;
for(int a:arr){
if(a!=0){
sum+=(a/i);
}
}
if(sum<n){
System.out.println(i-1);
return;
}
}
}
}
|
quadratic
|
1011_B. Planning The Expedition
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class Main {
Scanner in;
static PrintWriter out;
static class Scanner {
StreamTokenizer in;
Scanner(InputStream is) {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(is)));
in.resetSyntax();
in.whitespaceChars(0, 32);
in.wordChars(33, 255);
}
String readLine() {
try {
in.nextToken();
asserT(in.ttype == StreamTokenizer.TT_WORD);
return in.sval;
} catch (IOException e) {
throw new Error();
}
}
int nextInt() {
return Integer.parseInt(readLine());
}
}
void solve() {
int n = in.nextInt();
long k = in.nextInt();
int ar[] = new int[n];
TreeMap <Integer, Integer> nums = new TreeMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
ar[i] = in.nextInt();
nums.put(ar[i], i);
}
if (k == 1) {
out.println(n);
return;
}
int next[] = new int[n];
Arrays.fill(next, -1);
int count = 0;
for (int i = 0; i < n; i++) {
long val = ar[i] * k;
int intVal = (int)val;
if (intVal == val) {
if (nums.containsKey(intVal)) {
int idx = nums.get(intVal);
next[i] = idx;
continue;
}
}
if (ar[i] % k == 0) {
intVal = ar[i] / (int)k;
if (nums.containsKey(intVal)) {
continue;
}
}
count++;
}
for (int i = 0; i < n; i++) {
int curr = nums.pollFirstEntry().getValue();
boolean odd = false;
while (next[curr] != -1) {
if (!odd) {
count++;
}
int to = next[curr];
next[curr] = -1;
curr = to;
odd = !odd;
if (next[curr] == -1) {
if (!odd) {
count++;
}
}
}
}
out.println(count);
}
static void asserT(boolean e) {
if (!e) {
throw new Error();
}
}
public void run() {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
try {
solve();
} finally {
out.close();
}
}
public static void main(String[] args) {
new Main().run();
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author John Martin
*/
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);
ASubtractions solver = new ASubtractions();
solver.solve(1, in, out);
out.close();
}
static class ASubtractions {
public void solve(int testNumber, InputReader c, OutputWriter w) {
int tc = c.readInt();
while (tc-- > 0) {
int a = c.readInt(), b = c.readInt();
int op = 0;
while (a != b) {
if (a > b) {
int tm = b;
b = a;
a = tm;
}
int left = b - a;
int rem = (left - 1) / a + 1;
b -= rem * a;
op += rem;
}
op++;
w.printLine(op);
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class A {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int nums = Integer.parseInt(reader.readLine());
String line = reader.readLine();
int[] ar = new int[nums];
String[] par = line.split(" ");
for(int i=0; i<nums; i++){
ar[i] = Integer.parseInt(par[i]);
}
A a = new A();
System.out.print(a.getDif(ar));
}
private int getDif(int[] input){
int odd = 0, even = 0, d = 0;
int p = 0, q = 0;
for(int i=0; i<input.length; i++){
int t = input[i]%2;
if(t==0){
even++;
p = i+1;
}
else{
odd++;
q = i+1;
}
if(odd>0 && even>0 && (odd!=even)){
if(even>odd)
return q;
else
return p;
}
}
return d;
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
Scanner cin = new Scanner(new BufferedInputStream(System.in));
long n;
long maxlcm;
void run(){
n = cin.nextInt();
if(n == 1 || n ==2)
maxlcm = n;
else if(n >= 3){
if(n % 2 != 0){
maxlcm = n * (n-1) * (n - 2);
}
else if(n%3 != 0)
maxlcm = n * (n - 1) * (n - 3);
else maxlcm = (n - 1) * (n - 2) * (n - 3);
}
System.out.println(maxlcm);
}
public static void main(String[] args) {
new Main().run();
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.util.Scanner;
public class P_1177B {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long k = scan.nextLong();
long k2 = k - 10;
int cont = 1, pos;
String out; //System.out.println(getString((int)k));
if(k <= 9)
System.out.println(k);
else {
cont++;
while(k2 >= cont*(long)(Math.pow(10, cont)-Math.pow(10, cont-1))) {
k2 -= cont*(long)(Math.pow(10, cont)-Math.pow(10, cont-1));
cont++;
}
pos = (int)(k2%cont);
k2 /= cont;
k2 += (long)Math.pow(10, cont-1);
out = String.valueOf(k2);
System.out.println(out.charAt(pos));
}
}
/*public static String getString(int number) {
int contador = 1;
String salida = "";
while(salida.length() <= number) {
salida += contador;
contador++;
}
return salida.substring(0, number);
}*/
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.util.*;
public class Beta15PA {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Beta15PA temp = new Beta15PA();
temp.solve();
}
public void solve() {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt(), t = scan.nextInt();
House[] houses = new House[n];
for(int i=0; i<n; i++) {
houses[i] = new House(scan.nextInt(), scan.nextInt());
}
Arrays.sort(houses);
int res = 2;
for(int i=0; i<n-1; i++) {
double cnt = houses[i+1].coordinate - houses[i].coordinate;
cnt -= 1.0*(houses[i+1].side+houses[i].side)/2;
if(cnt>t) res += 2;
else if(Math.abs(cnt-t)<1e-7) res += 1;
}
System.out.println(res);
}
public class House implements Comparable<House> {
public int coordinate, side;
public House(int coordinate, int side) {
this.coordinate = coordinate;
this.side = side;
}
@Override
public int compareTo(House arg0) {
// TODO Auto-generated method stub
return this.coordinate - arg0.coordinate;
}
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.util.function.IntPredicate;
import static java.lang.Math.*;
public class Main {
FastScanner in;
PrintWriter out;
static final String FILE = "";
public static final int TEST = 0;
class Interact {
Rect a, b;
public Interact(int x11, int y11, int x12, int y12, int x21, int y21, int x22, int y22) {
a = new Rect(x11, y11, x12, y12);
b = new Rect(x21, y21, x22, y22);
}
int query(int x1, int y1, int x2, int y2) {
int ans = 0;
if (x1 <= a.x1 && x2 >= a.x2 && y1 <= a.y1 && y2 >= a.y2)
ans++;
if (x1 <= b.x1 && x2 >= b.x2 && y1 <= b.y1 && y2 >= b.y2)
ans++;
return ans;
}
}
Interact interact;
class Rect {
int x1, y1, x2, y2;
public Rect() {
}
public Rect(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
@Override
public String toString() {
return x1 + " " + y1 + " " + x2 + " " + y2;
}
}
int calls;
int query(int x1, int y1, int x2, int y2, Rect rect) {
calls++;
if (calls >= 190)
throw new RuntimeException();
if (TEST == 0) {
out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
out.flush();
int ans = in.nextInt();
if (x1 <= rect.x1 && x2 >= rect.x2 && y1 <= rect.y1 && y2 >= rect.y2)
ans--;
return ans;
} else {
int ans = interact.query(x1, y1, x2, y2);
if (x1 <= rect.x1 && x2 >= rect.x2 && y1 <= rect.y1 && y2 >= rect.y2)
ans--;
return ans;
}
}
static int binarySearchFirstTrue(IntPredicate predicate, int fromInclusive, int toInclusive) {
int a = fromInclusive, b = toInclusive;
while (a != b) {
int la = a, lb = b;
int mid = (a + b) / 2;
if (predicate.test(mid))
b = mid;
else
a = mid;
if (la == a && lb == b) {
if (predicate.test(a))
b = a;
else
a = b;
}
}
return a;
}
static int binarySearchLastTrue(IntPredicate predicate, int fromInclusive, int toInclusive) {
int a = fromInclusive, b = toInclusive;
while (a != b) {
int la = a, lb = b;
int mid = (a + b) / 2;
if (predicate.test(mid))
a = mid;
else
b = mid;
if (la == a && lb == b) {
if (predicate.test(b))
a = b;
else
b = a;
}
}
return a;
}
static Rect rect;
void test() {
Random random = new Random(13);
for (int test = 0; test < 1000; test++) {
}
}
void solve() {
rect = new Rect();
if (TEST == 0) {
int n = in.nextInt();
List<Rect> list = new ArrayList<>();
for (int r = 0; r < 2; r++) {
int x2 = binarySearchFirstTrue(i -> query(1, 1, i, n, rect) >= 1, 1, n);
int x1 = binarySearchLastTrue(i -> query(i, 1, x2, n, rect) >= 1, 1, x2);
int y2 = binarySearchFirstTrue(i -> query(x1, 1, x2, i, rect) >= 1, 1, n);
int y1 = binarySearchLastTrue(i -> query(x1, i, x2, y2, rect) >= 1, 1, y2);
rect = new Rect(x1, y1, x2, y2);
list.add(rect);
}
out.println("! " + list.get(0) + " " + list.get(1));
out.flush();
} else {
int n = in.nextInt();
int x11 = in.nextInt(), y11 = in.nextInt(), x12 = in.nextInt(), y12 = in.nextInt();
int x21 = in.nextInt(), y21 = in.nextInt(), x22 = in.nextInt(), y22 = in.nextInt();
interact = new Interact(x11, y11, x12, y12, x21, y21, x22, y22);
List<Rect> list = new ArrayList<>();
for (int r = 0; r < 2; r++) {
int x2 = binarySearchFirstTrue(i -> query(1, 1, i, n, rect) >= 1, 1, n);
int x1 = binarySearchLastTrue(i -> query(i, 1, x2, n, rect) >= 1, 1, x2);
int y2 = binarySearchFirstTrue(i -> query(x1, 1, x2, i, rect) >= 1, 1, n);
int y1 = binarySearchLastTrue(i -> query(x1, i, x2, y2, rect) >= 1, 1, y2);
rect = new Rect(x1, y1, x2, y2);
list.add(rect);
}
out.println("! " + list.get(0) + " " + list.get(1));
out.flush();
}
}
public void run() {
if (FILE.equals("")) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
try {
in = new FastScanner(new FileInputStream(FILE +
".in"));
out = new PrintWriter(new FileOutputStream(FILE +
".out"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
solve();
out.close();
}
public static void main(String[] args) {
(new Main()).run();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
}
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
import java.util.Scanner;
public class Test {
private static long sum(long value) {
long ans = 0;
while (value > 0) {
ans += value % 10;
value /= 10;
}
return ans;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long n , s , ans = 0;
n = scan.nextLong();
s = scan.nextLong();
long current = s;
while (current <= n && current <= s + 20 * 9) {
// current - sum(current) >= s
long temp = sum(current);
if (current - temp >= s) {
ans ++;
}
current ++;
}
if (current <= n) {
ans += (n - current + 1);
}
System.out.println(ans);
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.util.Scanner;
/**
*
* @author igor_kz
*/
public class C46 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int number = in.nextInt();
String s = in.next();
int cH = 0;
int n = s.length();
for (int i = 0 ; i < n ; i++)
if (s.charAt(i) == 'H') cH++;
String ss = "";
for (int i = 0 ; i < cH ; i++)
ss += "H";
for (int i = 0 ; i < n - cH ; i++)
ss += "T";
int res = Integer.MAX_VALUE;
for (int i = 0 ; i < n ; i++) {
int cur = countDifference(ss , s);
res = Math.min(res , cur);
ss = ss.substring(1) + ss.charAt(0);
}
System.out.println(res);
}
public static int countDifference(String ss, String s) {
int cnt = 0;
for (int i = 0 ; i < ss.length() ; i++)
if (ss.charAt(i) != s.charAt(i)) cnt++;
return cnt / 2;
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
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();
long k = in.nextLong();
long[] a = new long[n];
for (int i = 0; i < n; ++i) a[i] = in.nextLong();
Arrays.sort(a);
boolean[] take = new boolean[n];
Arrays.fill(take, true);
int j = 0;
int res = n;
for (int i = 0; i < n; ++i) {
while (j < i && a[j] * k < a[i]) ++j;
if (j < i && take[j] && a[j] * k == a[i]) {
take[i] = false;
--res;
}
}
out.println(res);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.